@peopl-health/nexus 6.0.9 → 6.0.10

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.
@@ -0,0 +1,73 @@
1
+ const { foldAccents } = require('../../utils/formatUtils');
2
+ const { termKey } = require('../../fhir/utils/normalizeUtils');
3
+ const { getSymptom } = require('../../fhir/helpers/terminologyHelper');
4
+ const { knownFor, withCurrentAnchor } = require('./triageCaseBaseHelper');
5
+
6
+ // Only the ADL question the anchor answers is dropped: "¿te impide bañarte o vestirte, o más bien cocinar o salir?".
7
+ // A false positive costs the patient a question, so the match is narrow and anything else on the line keeps it.
8
+ const LIMITS_RX = /\b(impide\w*|impedir\w*|limita\w*)\b/;
9
+ const SELF_CARE_RX = /\b(bana\w*|vest\w+)\b/;
10
+ const INSTRUMENTAL_RX = /\b(cocin\w+|compras|mandados|salir|trabaj\w+)\b/g;
11
+ const SAFETY_RX = new RegExp(`\\b(${[
12
+ 'fiebre', 'febril', 'temperatura', 'escalofrios?', 'pecho', 'aire', 'respir\\w*', 'ahog\\w*', 'disnea', 'aliento',
13
+ 'sangr\\w*', 'heces', 'negr\\w*', 'orina\\w*', 'vomit\\w*', 'liquidos?', 'beber', 'deshidrat\\w*', 'desmay\\w*',
14
+ 'confus\\w*', 'convuls\\w*', 'ca[ei]\\w*', 'dano', 'suicid\\w*', 'morir', 'no estar aqui', 'sentido seguir', 'reposo',
15
+ ].join('|')})\\b`);
16
+
17
+ function asksFunctionalImpact(question) {
18
+ const text = foldAccents(question).toLowerCase();
19
+ if (!LIMITS_RX.test(text) || SAFETY_RX.test(text) || /\d/.test(text)) return false;
20
+ if ((text.match(/\?/g) || []).length > 1) return false;
21
+ const instrumental = new Set(text.match(INSTRUMENTAL_RX) || []).size;
22
+ return SELF_CARE_RX.test(text) ? instrumental >= 1 : instrumental >= 2;
23
+ }
24
+
25
+ const keysOf = (catalog, term) => {
26
+ const ctcaeV5 = catalog?.symptoms ? getSymptom(catalog, term)?.ctcae_v5 : null;
27
+ return [term, ctcaeV5 && String(ctcaeV5).split('\n')[0]].map(termKey).filter(Boolean);
28
+ };
29
+
30
+ // Today's grade comes from the questionnaire, never from the grade the plan model wrote on its card.
31
+ function todayGradesByTerm(graded = [], catalog = null) {
32
+ const grades = new Map();
33
+ for (const { term, grade } of graded) {
34
+ if (!Number.isFinite(grade)) continue;
35
+ for (const key of keysOf(catalog, term)) grades.set(key, Math.max(grades.get(key) ?? grade, grade));
36
+ }
37
+ return grades;
38
+ }
39
+
40
+ function gradeFor(todayGrades, catalog, term) {
41
+ const key = keysOf(catalog, term).find((candidate) => todayGrades.has(candidate));
42
+ return key ? todayGrades.get(key) : null;
43
+ }
44
+
45
+ // Every term on the card needs today's grade and a current anchor: on a mixed card the question may be about the other term.
46
+ function anchorsCover(element, { known, catalog, todayGrades }) {
47
+ const terms = [...new Set([...element.targetedCtcaeTerms, ...element.symptoms.map((symptom) => symptom.ctcaeTerm)].filter(Boolean))];
48
+ if (!terms.length) return false;
49
+ return terms.every((term) => {
50
+ const todayGrade = gradeFor(todayGrades, catalog, term);
51
+ if (todayGrade === null) return false;
52
+ return Boolean(withCurrentAnchor(knownFor(known, term, catalog, null), todayGrade).entry?.functionalAnchor);
53
+ });
54
+ }
55
+
56
+ function dropKnownFunctionalAsks(elements, { known, catalog, todayGrades } = {}, repairs = []) {
57
+ if (!known?.size || !todayGrades?.size) return 0;
58
+ let dropped = 0;
59
+ for (const element of elements) {
60
+ if (!element.minCharacterizationVariables.length || !anchorsCover(element, { known, catalog, todayGrades })) continue;
61
+ const kept = element.minCharacterizationVariables.filter((question) => !asksFunctionalImpact(question));
62
+ const removed = element.minCharacterizationVariables.length - kept.length;
63
+ if (!removed) continue;
64
+ dropped += removed;
65
+ element.minCharacterizationVariables = kept;
66
+ if (!kept.length) element.characterizationNeeded = false;
67
+ repairs.push(`min_characterization_variables (rank ${element.rank}): ${removed} pregunta(s) de impacto funcional `
68
+ + 'eliminada(s); el caso abierto ya lo caracterizó en conversación y sigue vigente');
69
+ }
70
+ return dropped;
71
+ }
72
+
73
+ module.exports = { asksFunctionalImpact, dropKnownFunctionalAsks, todayGradesByTerm };
@@ -71,6 +71,12 @@ function buildElement(raw, repairs) {
71
71
  followupUrgency: nullableStr(rawRec?.followup_urgency),
72
72
  };
73
73
  const rawEsc = raw?.escalation || {};
74
+ const urgentUnder24h = rawEsc?.urgent_under_24h === true;
75
+ let maxActionTimeHours = num(rawEsc?.max_action_time_hours);
76
+ if (!urgentUnder24h && maxActionTimeHours !== null && (maxActionTimeHours < 1 || maxActionTimeHours > 24)) {
77
+ repairs.push(`max_action_time_hours (rank ${raw?.rank ?? '?'}) ${maxActionTimeHours}h descartado: fuera de 1-24h en un elemento no urgente`);
78
+ maxActionTimeHours = null;
79
+ }
74
80
  return {
75
81
  rank: num(raw?.rank) || 0,
76
82
  type: str(raw?.type).trim(),
@@ -84,8 +90,8 @@ function buildElement(raw, repairs) {
84
90
  characterizationNeeded: typeof raw?.characterization_is_needed === 'boolean' ? raw.characterization_is_needed : null,
85
91
  minCharacterizationVariables: strList(raw?.min_characterization_variables),
86
92
  escalation: {
87
- urgentUnder24h: rawEsc?.urgent_under_24h === true,
88
- maxActionTimeHours: num(rawEsc?.max_action_time_hours),
93
+ urgentUnder24h,
94
+ maxActionTimeHours,
89
95
  routes: strList(rawEsc?.routes).map((route) => route.trim()).filter(Boolean),
90
96
  clinicalCriteria: nullableStr(rawEsc?.clinical_criteria),
91
97
  },
@@ -599,6 +599,8 @@ function buildCasoBase({
599
599
 
600
600
  module.exports = {
601
601
  characterizationByTerm,
602
+ knownFor,
603
+ withCurrentAnchor,
602
604
  buildExposureBlock,
603
605
  buildOpenCaseBlock,
604
606
  buildEscalationBlock,
@@ -54,6 +54,7 @@ const triageRecommendationEventSchema = new mongoose.Schema({
54
54
  deniedCardsDropped: { type: Number, default: null },
55
55
  deniedTargetsStripped: { type: Number, default: null },
56
56
  cardsTruncated: { type: Number, default: null },
57
+ knownAsksDropped: { type: Number, default: null },
57
58
  adherenceRecorded: { type: Number, default: null },
58
59
  adherenceSkipped: { type: Number, default: null },
59
60
  adherenceNoTask: { type: Number, default: null },
@@ -50,6 +50,9 @@ const REMINDER_TYPE_TO_AIRTABLE = {
50
50
  const PENDING_ROW_FILTER = 'IF({is_active}, "true", "false") = "true", IF({is_sent}, "true", "false") = "false"';
51
51
  const ROUTINE_OUTREACH_FILTER = 'OR({type} = "seguimiento", LEFT({schedule_id}, 9) = "recovery_")';
52
52
  const RECOVERY_FILTER = 'LEFT({schedule_id}, 9) = "recovery_"';
53
+ // `reminder` and `contingency` have no `source`; the lookup through the patient link carries it.
54
+ const ROW_PROGRAM_FIELD = 'source (from patient_id)';
55
+ const patientRowsOf = (code) => `${fieldEquals('whatsapp_id', code)}, ${programSourceFormula({ field: ROW_PROGRAM_FIELD, allowBlank: true })}`;
53
56
  const FIRE_TRIGGER_GRACE_MS = 10 * 60 * 1000;
54
57
 
55
58
  // intake.source only offers self|doctor; team_relay carries "según médico" authority.
@@ -456,7 +459,7 @@ async function readPendingFollowUpsForPatient({ code, now = new Date() }) {
456
459
  const rows = await airtableService.getRecordByFilter(
457
460
  Monitoreo_ID,
458
461
  'reminder',
459
- `AND(${fieldEquals('whatsapp_id', code)}, ${ROUTINE_OUTREACH_FILTER}, ${PENDING_ROW_FILTER})`,
462
+ `AND(${patientRowsOf(code)}, ${ROUTINE_OUTREACH_FILTER}, ${PENDING_ROW_FILTER})`,
460
463
  null,
461
464
  ['schedule_id', 'reminder_date', 'description', 'expires_at', 'window_reasoning'],
462
465
  );
@@ -482,7 +485,7 @@ async function hasCheckInNear({ code, withinMinutes, excludeReminderId, fireAt =
482
485
  const rows = await airtableService.getRecordByFilter(
483
486
  Monitoreo_ID,
484
487
  'reminder',
485
- `AND(${fieldEquals('whatsapp_id', code)}, OR(RIGHT({schedule_id}, 8) = "-patient", ${ROUTINE_OUTREACH_FILTER}), NOT(${fieldEquals('schedule_id', excludeReminderId)}), OR(${pending}, ${sent}))`,
488
+ `AND(${patientRowsOf(code)}, OR(RIGHT({schedule_id}, 8) = "-patient", ${ROUTINE_OUTREACH_FILTER}), NOT(${fieldEquals('schedule_id', excludeReminderId)}), OR(${pending}, ${sent}))`,
486
489
  null,
487
490
  ['schedule_id', 'reminder_date', 'is_sent'],
488
491
  );
@@ -522,7 +525,7 @@ async function cancelPendingFollowUps({ code, trace = null, reason = 'patient_re
522
525
  table: 'reminder',
523
526
  planId: null,
524
527
  standDownReason: reason,
525
- filter: `AND(${fieldEquals('whatsapp_id', code)}, ${recoveryOnly ? RECOVERY_FILTER : ROUTINE_OUTREACH_FILTER}, ${PENDING_ROW_FILTER})`,
528
+ filter: `AND(${patientRowsOf(code)}, ${recoveryOnly ? RECOVERY_FILTER : ROUTINE_OUTREACH_FILTER}, ${PENDING_ROW_FILTER})`,
526
529
  });
527
530
  }
528
531
 
@@ -648,7 +651,7 @@ async function standDownRow({ code, trace, table, filter, planId, standDownReaso
648
651
 
649
652
  // Stands down every pending reminder and contingency row of a patient, whatever their type.
650
653
  async function standDownAllPendingRows({ code, reason }) {
651
- const filter = `AND(${fieldEquals('whatsapp_id', code)}, ${PENDING_ROW_FILTER})`;
654
+ const filter = `AND(${patientRowsOf(code)}, ${PENDING_ROW_FILTER})`;
652
655
  const remindersOk = await standDownRow({ code, trace: null, planId: null, standDownReason: reason, table: 'reminder', filter });
653
656
  const escalationsOk = await standDownRow({ code, trace: null, planId: null, table: 'contingency', filter });
654
657
  return remindersOk && escalationsOk;
@@ -127,6 +127,10 @@ function validate(elements, options = {}) {
127
127
  problem: 'no puede contener puntos suspensivos ni texto truncado',
128
128
  });
129
129
  }
130
+ const hours = element.escalation.maxActionTimeHours;
131
+ if (hours !== null && (hours < 1 || hours > 24)) {
132
+ issues.push({ path: `${path}.escalation.max_action_time_hours`, problem: `max_action_time_hours debe estar entre 1 y 24; recibido ${hours}` });
133
+ }
130
134
  if (element.escalation.urgentUnder24h && !element.escalation.routes.length) {
131
135
  issues.push({ path: `${path}.escalation.routes`, problem: 'elemento con escalamiento <24h ⇒ routes debe llevar al menos una ruta' });
132
136
  }
@@ -19,7 +19,9 @@ const {
19
19
  buildCasoBase,
20
20
  buildSafetySignals,
21
21
  hasActionableFindings,
22
+ characterizationByTerm,
22
23
  } = require('../helpers/triageCaseBaseHelper');
24
+ const { dropKnownFunctionalAsks, todayGradesByTerm } = require('../helpers/knownCharacterizationHelper');
23
25
  const { buildLegacyStep1, buildLegacyStep2, buildLegacyStep3 } = require('../helpers/legacyRecommendationFormatHelper');
24
26
  const { chemoContextLive } = require('../flags/clinicalContextFlags');
25
27
  const { mexicoDay } = require('../../utils/dateUtils');
@@ -599,6 +601,8 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
599
601
  uncodedKeys: new Set(freeTextUnmatchedSymptoms.map(keyOf).filter(Boolean)),
600
602
  deniedAeKeys: deniedAeKeySet(catalog, gate),
601
603
  reported: reportedSymptoms(catalog, reportedTerms),
604
+ known: characterizationByTerm(openCases),
605
+ todayGrades: todayGradesByTerm(graded, catalog),
602
606
  };
603
607
  const rankContext = buildRankContext({ catalog, graded, reportedTerms, priorResolutions, openCases });
604
608
  const symptomSignals = buildSymptomSignals({
@@ -623,6 +627,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
623
627
  settle.deniedCardsDropped = planOutcome.deniedCardsDropped;
624
628
  settle.cardsTruncated = planOutcome.cardsTruncated;
625
629
  settle.deniedTargetsStripped = planOutcome.deniedTargetsStripped;
630
+ settle.knownAsksDropped = planOutcome.knownAsksDropped;
626
631
 
627
632
  try {
628
633
  await storeRecommendationPlan({
@@ -927,6 +932,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
927
932
  let deniedCardsDropped = 0;
928
933
  let deniedTargetsStripped = 0;
929
934
  let cardsTruncated = 0;
935
+ let knownAsksDropped = 0;
930
936
  const budget = newTransientBudget();
931
937
  for (let attempt = 1; attempt <= PLAN_MAX_ATTEMPTS; attempt += 1) {
932
938
  const content = attempt === 1 || !lastIssues.length
@@ -987,6 +993,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
987
993
  }
988
994
  rankReordered = applyRankOrder(elements, gate, repairs, rankContext);
989
995
  cardsTruncated = truncateToCardLimit(elements, repairs);
996
+ knownAsksDropped = dropKnownFunctionalAsks(elements, boundary || {}, repairs);
990
997
  const issues = validate(elements, { gate, lane: 'triage', urgentReframed });
991
998
  const blocking = blockingIssues(issues);
992
999
  if (blocking.length) {
@@ -1012,6 +1019,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
1012
1019
  deniedCardsDropped,
1013
1020
  deniedTargetsStripped,
1014
1021
  cardsTruncated,
1022
+ knownAsksDropped,
1015
1023
  modelInput: content,
1016
1024
  model: typeof result?.model === 'string' ? result.model : null,
1017
1025
  });
@@ -26,7 +26,7 @@ const definition = {
26
26
  },
27
27
  elements: {
28
28
  type: 'array',
29
- description: 'Ranked plan elements (contiguous ranks 1..N). Each: `{rank, type(cluster|individual), name_short, time_window, symptoms[{ctcae_term, grade, verification_status}], targeted_ctcae_terms[], why_relevant, qol_impact, improvement_capacity, escalation{urgent_under_24h, max_action_time_hours, routes[], clinical_criteria}, recommendation{symptoms_patient_facing[], is_pharmacological_med_needed, patient{main_recommendation, when_to_escalate, contraindications, expected_effectiveness}, otc_offer?, followup?, followup_urgency?}, grounded_in[]}`.',
29
+ description: 'Ranked plan elements (contiguous ranks 1..N). Each: `{rank, type(cluster|individual), name_short, time_window, symptoms[{ctcae_term, grade, verification_status}], targeted_ctcae_terms[], why_relevant, qol_impact, improvement_capacity, escalation{urgent_under_24h, max_action_time_hours, routes[], clinical_criteria} (max_action_time_hours: integer 1-24 or null), recommendation{symptoms_patient_facing[], is_pharmacological_med_needed, patient{main_recommendation, when_to_escalate, contraindications, expected_effectiveness}, otc_offer?, followup?, followup_urgency?}, grounded_in[]}`.',
30
30
  items: { type: 'object' },
31
31
  },
32
32
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.9",
3
+ "version": "6.0.10",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",