@peopl-health/nexus 5.59.4 → 5.59.5

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.
@@ -139,6 +139,7 @@ function buildSymptomsMetadata({
139
139
  declined = [],
140
140
  additionalSymptoms = [],
141
141
  freeTextDerivedSymptoms = [],
142
+ freeTextUnmatchedSymptoms = [],
142
143
  nonIdentifiedSymptoms = null,
143
144
  stage = 'gate',
144
145
  catalog = null,
@@ -177,6 +178,14 @@ function buildSymptomsMetadata({
177
178
  + 'clasificador y puede no ser el correcto: verifícalo con el paciente antes de darlo por confirmado.',
178
179
  );
179
180
  }
181
+ if (freeTextUnmatchedSymptoms.length) {
182
+ parts.push(
183
+ 'Síntomas que el paciente escribió en el TEXTO LIBRE y que no tienen ítem PRO-CTCAE: '
184
+ + freeTextUnmatchedSymptoms.join(', ')
185
+ + '. Están PRESENTES, sin grado, y son material válido de recomendación. No los traduzcas a un '
186
+ + 'ítem PRO-CTCAE parecido: si les haces una tarjeta, pon exactamente esa etiqueta en targeted_ctcae_terms.',
187
+ );
188
+ }
180
189
  if (denied.length) {
181
190
  parts.push(
182
191
  'Síntomas NEGADOS explícitamente en la ventana de reporte del triaje (respuesta grado 0 a preguntas del triaje): '
@@ -370,6 +379,7 @@ function buildCasoBase({
370
379
  freeText = null,
371
380
  additionalSymptoms = [],
372
381
  freeTextDerivedSymptoms = [],
382
+ freeTextUnmatchedSymptoms = [],
373
383
  nonIdentifiedSymptoms = null,
374
384
  stage = 'gate',
375
385
  catalog = null,
@@ -396,6 +406,7 @@ function buildCasoBase({
396
406
  declined,
397
407
  additionalSymptoms,
398
408
  freeTextDerivedSymptoms,
409
+ freeTextUnmatchedSymptoms,
399
410
  nonIdentifiedSymptoms,
400
411
  stage,
401
412
  catalog,
@@ -51,12 +51,13 @@ function canonicalCtcaeTerm(catalog, term) {
51
51
  return resolved ? spellingOf(catalog.symptoms[resolved], resolved) || term : term;
52
52
  }
53
53
 
54
- function canonicaliseTerms(element, catalog) {
55
- element.targetedCtcaeTerms = [...new Set(
56
- element.targetedCtcaeTerms.map((term) => canonicalCtcaeTerm(catalog, term)),
57
- )];
54
+ // A free-text complaint the classifier could not code keeps the patient's label: a fuzzy
55
+ // alias match would rename it to a catalog term she never reported, and drop the card.
56
+ function canonicaliseTerms(element, catalog, uncodedKeys = new Set()) {
57
+ const canonical = (term) => (uncodedKeys.has(keyOf(term)) ? term : canonicalCtcaeTerm(catalog, term));
58
+ element.targetedCtcaeTerms = [...new Set(element.targetedCtcaeTerms.map(canonical))];
58
59
  for (const symptom of element.symptoms) {
59
- symptom.ctcaeTerm = canonicalCtcaeTerm(catalog, symptom.ctcaeTerm);
60
+ symptom.ctcaeTerm = canonical(symptom.ctcaeTerm);
60
61
  }
61
62
  }
62
63
 
@@ -166,7 +167,7 @@ function applyCardSurfaceBoundary(elements, boundary, repairs = [], { rescue = f
166
167
  let dropped = 0;
167
168
  let stripped = 0;
168
169
  for (const element of elements) {
169
- canonicaliseTerms(element, boundary.catalog);
170
+ canonicaliseTerms(element, boundary.catalog, boundary.uncodedKeys);
170
171
  const breach = breachOf(element, boundary);
171
172
  if (!breach) {
172
173
  kept.push(element);
@@ -89,7 +89,7 @@ function buildRankContext({ catalog, graded = [], reportedTerms = [], priorResol
89
89
 
90
90
  function buildSymptomSignals({
91
91
  catalog, graded = [], ungradedTerms = [], additionalSymptoms = [], freeTextDerivedSymptoms = [],
92
- priorResolutions = [], openCases = [],
92
+ freeTextUnmatchedSymptoms = [], priorResolutions = [], openCases = [],
93
93
  }) {
94
94
  const gradeByKey = new Map();
95
95
  for (const symptom of graded) keepHighest(gradeByKey, aliasKeysOf(catalog, symptom.term), symptom.grade);
@@ -109,6 +109,7 @@ function buildSymptomSignals({
109
109
  ungradedTerms.forEach((term) => add(term, 'cuestionario'));
110
110
  additionalSymptoms.forEach((symptom) => add(symptom.label, 'checkbox', symptom));
111
111
  freeTextDerivedSymptoms.forEach((term) => add(term, 'texto libre'));
112
+ freeTextUnmatchedSymptoms.forEach((label) => add(label, 'texto libre'));
112
113
 
113
114
  return signals.map(({ keys, ...signal }) => ({
114
115
  ...signal,
@@ -38,6 +38,7 @@ const {
38
38
  const { gradeComposites, PAIN_TERM } = require('../../fhir/helpers/compositeHelper');
39
39
  const { affirmative } = require('../../fhir/helpers/terminologyHelper');
40
40
  const { buildTriageResponse } = require('../../fhir/helpers/triagePayloadHelper');
41
+ const { keyOf } = require('../../fhir/helpers/symptomAliasHelper');
41
42
  const { getCatalog } = require('../../fhir/services/terminologyService');
42
43
  const { getRecordByFilter } = require('../../services/airtableService');
43
44
  const { RecommendationPlan } = require('../../shared/dtos/RecommendationPlan');
@@ -262,11 +263,12 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
262
263
  return { ...settle, status: 'failed', stage: 'assemble', reason: 'triage_patient_mismatch' };
263
264
  }
264
265
  const freeTextDerivedSymptoms = classifier.terms;
266
+ const freeTextUnmatchedSymptoms = classifier.unmatched || [];
265
267
  settle.classifierPending = classifier.pending;
266
268
  settle.classifierOutcome = classifier.outcome;
267
269
  settle.classifierWaitMs = classifier.waitMs;
268
270
 
269
- let supportContext = { triage: triageResponse, freeTextDerivedSymptoms };
271
+ let supportContext = { triage: triageResponse, freeTextDerivedSymptoms, freeTextUnmatchedSymptoms };
270
272
  let supportPromise;
271
273
  let existingClinicalMirrorId = null;
272
274
  const startSupport = () => {
@@ -527,6 +529,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
527
529
  freeText: freeTextLabelled.join(' · ') || null,
528
530
  additionalSymptoms,
529
531
  freeTextDerivedSymptoms,
532
+ freeTextUnmatchedSymptoms,
530
533
  nonIdentifiedSymptoms: triageResponse.nonIdentifiedSymptoms,
531
534
  stage,
532
535
  catalog,
@@ -539,6 +542,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
539
542
  ...reported.map((symptom) => symptom.term),
540
543
  ...additionalSymptoms.map((symptom) => symptom.term).filter(Boolean),
541
544
  ...freeTextDerivedSymptoms,
545
+ ...freeTextUnmatchedSymptoms,
542
546
  ];
543
547
  const reportedKeys = symptomKeySet(catalog, reportedTerms);
544
548
  const floorConfig = await getRedFlagMinRoutes()
@@ -581,12 +585,14 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
581
585
  gate,
582
586
  deniedKeys,
583
587
  reportedKeys,
588
+ uncodedKeys: new Set(freeTextUnmatchedSymptoms.map(keyOf).filter(Boolean)),
584
589
  deniedAeKeys: deniedAeKeySet(catalog, gate),
585
590
  reported: reportedSymptoms(catalog, reportedTerms),
586
591
  };
587
592
  const rankContext = buildRankContext({ catalog, graded, reportedTerms, priorResolutions, openCases });
588
593
  const symptomSignals = buildSymptomSignals({
589
- catalog, graded, ungradedTerms, additionalSymptoms, freeTextDerivedSymptoms, priorResolutions, openCases,
594
+ catalog, graded, ungradedTerms, additionalSymptoms, freeTextDerivedSymptoms, freeTextUnmatchedSymptoms,
595
+ priorResolutions, openCases,
590
596
  });
591
597
  const planOutcome = await runPlan({
592
598
  provider, presetId: planPresetId, casoBase: casoBaseFor('plan', symptomSignals),
@@ -1022,18 +1028,19 @@ async function awaitFreeTextClassifier(triageRecordId, code, { hasFreeText }) {
1022
1028
 
1023
1029
  function classifierSettled(read) {
1024
1030
  if (read.pending !== false) return false;
1025
- if (read.derived > 0) return true;
1031
+ // The classifier writes the complaints it could not code too, so an all-NO MATCH run is done, not empty.
1032
+ if (read.derived > 0 || read.unmatched.length > 0) return true;
1026
1033
  const createdMs = Date.parse(read.createdAt || '');
1027
1034
  return !Number.isFinite(createdMs) || Date.now() - createdMs >= CLASSIFIER_WINDOW_MS;
1028
1035
  }
1029
1036
 
1030
1037
  async function readFreeTextDerivedSymptoms(triageRecordId, code) {
1031
- if (!/^rec[A-Za-z0-9]+$/.test(triageRecordId || '')) return { terms: [], pending: null, derived: 0, createdAt: null };
1038
+ if (!/^rec[A-Za-z0-9]+$/.test(triageRecordId || '')) return { terms: [], unmatched: [], pending: null, derived: 0, createdAt: null };
1032
1039
  const rows = await getRecordByFilter(Symptoms_ID, 'triaje_symptoms', `RECORD_ID()='${triageRecordId}'`);
1033
1040
  const row = Array.isArray(rows) ? rows[0] : rows;
1034
1041
  if (!row) {
1035
1042
  logger.warn('[triageRecommendation] triage row unreadable; no classifier anchors', { code, triageRecordId });
1036
- return { terms: [], pending: null, derived: 0, createdAt: null };
1043
+ return { terms: [], unmatched: [], pending: null, derived: 0, createdAt: null };
1037
1044
  }
1038
1045
  const owner = Array.isArray(row.whatsapp_id) ? row.whatsapp_id[0] : row.whatsapp_id;
1039
1046
  if (owner && owner !== code) {
@@ -1043,8 +1050,9 @@ async function readFreeTextDerivedSymptoms(triageRecordId, code) {
1043
1050
  // The classifier writes its rows ~96 s after the triage: an unfinished one is not an empty one.
1044
1051
  const pending = row.symptoms_processed !== true;
1045
1052
  const createdAt = row.Created || null;
1053
+ const unmatched = unmatchedMentionsOf(row.freetext_unmatched);
1046
1054
  const ids = (Array.isArray(row.symptoms) ? row.symptoms : []).filter((id) => /^rec[A-Za-z0-9]+$/.test(id || ''));
1047
- if (!ids.length) return { terms: [], pending, derived: 0, createdAt };
1055
+ if (!ids.length) return { terms: [], unmatched, pending, derived: 0, createdAt };
1048
1056
  const formula = `OR(${ids.map((id) => `RECORD_ID()='${id}'`).join(',')})`;
1049
1057
  const symptoms = await getRecordByFilter(Symptoms_ID, 'symptoms', formula, null, FREE_TEXT_SYMPTOM_FIELDS, true);
1050
1058
  const derived = (Array.isArray(symptoms) ? symptoms : []).filter((symptom) => symptom.freetext_derived === true);
@@ -1053,7 +1061,15 @@ async function readFreeTextDerivedSymptoms(triageRecordId, code) {
1053
1061
  .map((symptom) => (Array.isArray(symptom.corresponding_CTCAE) ? symptom.corresponding_CTCAE[0] : symptom.corresponding_CTCAE))
1054
1062
  .map((term) => String(term ?? '').trim())
1055
1063
  .filter(Boolean);
1056
- return { terms, pending, derived: derived.length, createdAt };
1064
+ return { terms, unmatched, pending, derived: derived.length, createdAt };
1065
+ }
1066
+
1067
+ // One complaint per line, `mención — "cita literal"`: only the mention names the symptom.
1068
+ function unmatchedMentionsOf(value) {
1069
+ const mentions = String(value || '').split('\n')
1070
+ .map((line) => line.split(' — ')[0].trim())
1071
+ .filter(Boolean);
1072
+ return [...new Set(mentions)];
1057
1073
  }
1058
1074
 
1059
1075
  async function readPriorResolutions(adherence = [], patientRecordId = null) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.59.4",
3
+ "version": "5.59.5",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",