@peopl-health/nexus 5.56.16 → 5.56.18

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.
@@ -1,5 +1,7 @@
1
1
  const { ladderFor, renderLadder } = require('../services/ctcaeLadderService');
2
- const { itemForQuestionId, affirmative, sentinelKind, dimensionsFor } = require('../../fhir/helpers/terminologyHelper');
2
+ const {
3
+ itemForQuestionId, affirmative, sentinelKind, dimensionsFor, isItemDimension,
4
+ } = require('../../fhir/helpers/terminologyHelper');
3
5
  const { daysSince } = require('../../utils/dateUtils');
4
6
  const { detectSafetyFlags } = require('./safetyFlagsHelper');
5
7
 
@@ -108,8 +110,15 @@ function reportedSymptomEvidence(symptom, catalog) {
108
110
  .map((dimension) => `${DIMENSION_ES[dimension] || dimension}: ${answers[dimension]}`)
109
111
  .join(' · ')}`);
110
112
  }
113
+ const setAside = Object.entries(symptom.supplementaryAnswers || {});
114
+ if (setAside.length) {
115
+ lines.push(` Preguntas complementarias de PEOPL, fuera del grado: ${setAside
116
+ .map(([dimension, answer]) => `${DIMENSION_ES[dimension] || dimension}: ${answer}`)
117
+ .join(' · ')}. Miden otra cosa que el ítem del PRO-CTCAE; no confirman ni descartan el síntoma.`);
118
+ }
111
119
  if (Array.isArray(catalog?.symptoms?.[symptom.term]?.dimensions)) {
112
- const missing = dimensionsFor(catalog, symptom.term).filter((dimension) => !answered.includes(dimension));
120
+ const missing = dimensionsFor(catalog, symptom.term)
121
+ .filter((dimension) => isItemDimension(catalog, symptom.term, dimension) && !answered.includes(dimension));
113
122
  if (missing.length) {
114
123
  lines.push(` Atributos que este ítem del PRO-CTCAE no preguntó: ${missing
115
124
  .map((dimension) => DIMENSION_ES[dimension] || dimension).join(', ')}. No preguntado no es `
@@ -38,6 +38,8 @@ const triageRecommendationEventSchema = new mongoose.Schema({
38
38
  droppedComboCount: { type: Number, default: null },
39
39
  rankReordered: { type: Number, default: null },
40
40
  classifierPending: { type: Boolean, default: null },
41
+ classifierOutcome: { type: String, enum: ['ready', 'timeout', 'no_free_text', null], default: null },
42
+ classifierWaitMs: { type: Number, default: null },
41
43
  deniedCardsDropped: { type: Number, default: null },
42
44
  deniedTargetsStripped: { type: Number, default: null },
43
45
  adherenceRecorded: { type: Number, default: null },
@@ -72,6 +72,9 @@ const GATE_MAX_ATTEMPTS = 2;
72
72
  const PLAN_MAX_ATTEMPTS = 2;
73
73
  const DEFAULT_PROVIDER_RETRY_BACKOFF_MS = [15000, 45000];
74
74
  const DEFAULT_SETTLE_WRITE_BACKOFF_MS = [1000, 5000];
75
+ const DEFAULT_CLASSIFIER_WAIT_MS = [15000, 30000, 45000, 60000, 90000];
76
+ const CLASSIFIER_WINDOW_MS = 4 * 60 * 1000;
77
+ const DEFAULT_CLASSIFIER_DEADLINE_MS = 5 * 60 * 1000;
75
78
  const RAW_EXCERPT_MAX = 2000;
76
79
  const PRIOR_TRIAGE_RX = /^rec[A-Za-z0-9]{14,}$/;
77
80
  const PATIENT_LOOKUP_FIELD = 'patient_id (from triaje_symptoms) (from cluster_recommendations)';
@@ -247,15 +250,20 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
247
250
  const code = payload.patientCode;
248
251
  const settle = { runId: rid };
249
252
 
250
- const classifier = await readFreeTextDerivedSymptoms(payload.triageRecordId, code);
253
+ const catalog = getCatalog();
254
+ const { triageResponse, unmappedQuestionIds } = buildTriageResponse(catalog, payload);
255
+ settle.unmappedAnswerCount = unmappedQuestionIds.length;
256
+
257
+ const hasFreeText = Boolean(triageResponse.otherSymptomsText || triageResponse.otherSymptomsNotProctcae.length
258
+ || triageResponse.pain?.otherText);
259
+ const classifier = await awaitFreeTextClassifier(payload.triageRecordId, code, { hasFreeText });
251
260
  if (classifier === null) {
252
261
  return { ...settle, status: 'failed', stage: 'assemble', reason: 'triage_patient_mismatch' };
253
262
  }
254
263
  const freeTextDerivedSymptoms = classifier.terms;
255
264
  settle.classifierPending = classifier.pending;
256
- const catalog = getCatalog();
257
- const { triageResponse, unmappedQuestionIds } = buildTriageResponse(catalog, payload);
258
- settle.unmappedAnswerCount = unmappedQuestionIds.length;
265
+ settle.classifierOutcome = classifier.outcome;
266
+ settle.classifierWaitMs = classifier.waitMs;
259
267
 
260
268
  let supportContext = { triage: triageResponse, freeTextDerivedSymptoms };
261
269
  let supportPromise;
@@ -536,7 +544,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
536
544
  affirmedKeys: reportedKeys,
537
545
  riskAssessment,
538
546
  riskReadFailed: riskRead.failed,
539
- freeTextPending: settle.classifierPending === true && freeTextBits.length > 0,
547
+ freeTextPending: classifier.outcome === 'timeout',
540
548
  };
541
549
 
542
550
  supportContext = { ...supportContext, case: casoBaseFor('support-routing') };
@@ -961,13 +969,47 @@ function stripOtcOffers(elements, repairs) {
961
969
 
962
970
  // auna calls handleTriageCompleted directly, so the classifier's rows are resolved here rather
963
971
  // than in the controller: 989 of 1002 production runs never pass through it.
972
+ async function awaitFreeTextClassifier(triageRecordId, code, { hasFreeText }) {
973
+ const startedAt = Date.now();
974
+ let read = await readFreeTextDerivedSymptoms(triageRecordId, code);
975
+ if (!hasFreeText) return read && { ...read, outcome: 'no_free_text', waitMs: 0 };
976
+ const schedule = backoffSchedule('TRIAGE_CLASSIFIER_WAIT_MS', DEFAULT_CLASSIFIER_WAIT_MS);
977
+ const deadlineMs = Number(runtimeConfig.get('TRIAGE_CLASSIFIER_DEADLINE_MS')) || DEFAULT_CLASSIFIER_DEADLINE_MS;
978
+ for (let tries = 0; read && !classifierSettled(read) && tries < schedule.length; tries += 1) {
979
+ if (Date.now() - startedAt + schedule[tries] > deadlineMs) break;
980
+ await sleep(schedule[tries], { keepAlive: true });
981
+ try {
982
+ read = await readFreeTextDerivedSymptoms(triageRecordId, code);
983
+ } catch (err) {
984
+ logger.warn('[triageRecommendation] free-text classifier re-read failed; keeping the last read', {
985
+ code, triageRecordId, error: err?.message,
986
+ });
987
+ }
988
+ }
989
+ if (!read) return read;
990
+ const outcome = classifierSettled(read) ? 'ready' : 'timeout';
991
+ if (outcome === 'timeout') {
992
+ logger.warn('[triageRecommendation] free-text classifier did not settle; cards built without its symptoms', {
993
+ code, triageRecordId, pending: read.pending, derived: read.derived,
994
+ });
995
+ }
996
+ return { ...read, outcome, waitMs: Date.now() - startedAt };
997
+ }
998
+
999
+ function classifierSettled(read) {
1000
+ if (read.pending !== false) return false;
1001
+ if (read.derived > 0) return true;
1002
+ const createdMs = Date.parse(read.createdAt || '');
1003
+ return !Number.isFinite(createdMs) || Date.now() - createdMs >= CLASSIFIER_WINDOW_MS;
1004
+ }
1005
+
964
1006
  async function readFreeTextDerivedSymptoms(triageRecordId, code) {
965
- if (!/^rec[A-Za-z0-9]+$/.test(triageRecordId || '')) return { terms: [], pending: null };
1007
+ if (!/^rec[A-Za-z0-9]+$/.test(triageRecordId || '')) return { terms: [], pending: null, derived: 0, createdAt: null };
966
1008
  const rows = await getRecordByFilter(Symptoms_ID, 'triaje_symptoms', `RECORD_ID()='${triageRecordId}'`);
967
1009
  const row = Array.isArray(rows) ? rows[0] : rows;
968
1010
  if (!row) {
969
1011
  logger.warn('[triageRecommendation] triage row unreadable; no classifier anchors', { code, triageRecordId });
970
- return { terms: [], pending: null };
1012
+ return { terms: [], pending: null, derived: 0, createdAt: null };
971
1013
  }
972
1014
  const owner = Array.isArray(row.whatsapp_id) ? row.whatsapp_id[0] : row.whatsapp_id;
973
1015
  if (owner && owner !== code) {
@@ -976,19 +1018,18 @@ async function readFreeTextDerivedSymptoms(triageRecordId, code) {
976
1018
  }
977
1019
  // The classifier writes its rows ~96 s after the triage: an unfinished one is not an empty one.
978
1020
  const pending = row.symptoms_processed !== true;
1021
+ const createdAt = row.Created || null;
979
1022
  const ids = (Array.isArray(row.symptoms) ? row.symptoms : []).filter((id) => /^rec[A-Za-z0-9]+$/.test(id || ''));
980
- if (!ids.length) {
981
- if (pending) logger.warn('[triageRecommendation] classifier had not finished; free-text symptoms unavailable', { code, triageRecordId });
982
- return { terms: [], pending };
983
- }
1023
+ if (!ids.length) return { terms: [], pending, derived: 0, createdAt };
984
1024
  const formula = `OR(${ids.map((id) => `RECORD_ID()='${id}'`).join(',')})`;
985
1025
  const symptoms = await getRecordByFilter(Symptoms_ID, 'symptoms', formula, null, FREE_TEXT_SYMPTOM_FIELDS, true);
986
- const terms = (Array.isArray(symptoms) ? symptoms : [])
987
- .filter((symptom) => symptom.freetext_derived === true && Number(symptom.grade_num) >= 1)
1026
+ const derived = (Array.isArray(symptoms) ? symptoms : []).filter((symptom) => symptom.freetext_derived === true);
1027
+ const terms = derived
1028
+ .filter((symptom) => Number(symptom.grade_num) >= 1)
988
1029
  .map((symptom) => (Array.isArray(symptom.corresponding_CTCAE) ? symptom.corresponding_CTCAE[0] : symptom.corresponding_CTCAE))
989
1030
  .map((term) => String(term ?? '').trim())
990
1031
  .filter(Boolean);
991
- return { terms, pending };
1032
+ return { terms, pending, derived: derived.length, createdAt };
992
1033
  }
993
1034
 
994
1035
  async function readPriorResolutions(adherence = [], patientRecordId = null) {
@@ -1,6 +1,8 @@
1
1
  const { logger } = require('../../utils/logger');
2
2
  const {
3
3
  itemForQuestionId,
4
+ isSupplementaryQuestion,
5
+ isItemDimension,
4
6
  canonicalAnswer,
5
7
  affirmative,
6
8
  standardOrdinal,
@@ -18,15 +20,19 @@ function gradeComposites(catalog, input) {
18
20
  const item = itemForQuestionId(catalog, questionId);
19
21
  if (!item) continue;
20
22
  const [term, dimension] = item;
21
- if (!answersByTerm.has(term)) answersByTerm.set(term, {});
22
- answersByTerm.get(term)[dimension] = String(canonicalAnswer(catalog, questionId, label));
23
+ if (!answersByTerm.has(term)) answersByTerm.set(term, { own: {}, supplementary: {} });
24
+ const lane = isSupplementaryQuestion(catalog, questionId) ? 'supplementary' : 'own';
25
+ answersByTerm.get(term)[lane][dimension] = { label: String(canonicalAnswer(catalog, questionId, label)), raw: String(label) };
23
26
  }
24
27
 
25
28
  const pain = painDimensionAnswers(catalog, input.pain, input.triageId);
26
- if (pain) answersByTerm.set(PAIN_TERM, pain);
29
+ const lanes = [...answersByTerm]
30
+ .filter(([term]) => !(pain && term === PAIN_TERM))
31
+ .map(([term, answers]) => [term, splitSupplementary(catalog, term, answers)]);
32
+ if (pain) lanes.push([PAIN_TERM, { dimensionAnswers: pain, setAside: {} }]);
27
33
 
28
34
  const graded = [];
29
- for (const [term, dimensionAnswers] of answersByTerm) {
35
+ for (const [term, { dimensionAnswers, setAside }] of lanes) {
30
36
  const ordinals = {};
31
37
  for (const [dimension, label] of Object.entries(dimensionAnswers)) {
32
38
  const ordinal = dimension === 'presence' ? presenceOrdinal(catalog, label) : standardOrdinal(catalog, dimension, label);
@@ -73,12 +79,27 @@ function gradeComposites(catalog, input) {
73
79
  effective: input.authored || null,
74
80
  triageId: input.triageId,
75
81
  dimensionAnswers: dimensionAnswers,
82
+ ...(Object.keys(setAside).length ? { supplementaryAnswers: setAside } : {}),
76
83
  source: 'triage',
77
84
  });
78
85
  }
79
86
  return graded;
80
87
  }
81
88
 
89
+ function splitSupplementary(catalog, term, { own, supplementary }) {
90
+ const dimensionAnswers = Object.fromEntries(Object.entries(own).map(([dimension, { label }]) => [dimension, label]));
91
+ const hasOwn = Object.keys(own).length > 0;
92
+ const setAside = {};
93
+ for (const [dimension, { label, raw }] of Object.entries(supplementary)) {
94
+ if (dimensionAnswers[dimension] == null && (isItemDimension(catalog, term, dimension) || !hasOwn)) {
95
+ dimensionAnswers[dimension] = label;
96
+ } else {
97
+ setAside[dimension] = raw;
98
+ }
99
+ }
100
+ return { dimensionAnswers, setAside };
101
+ }
102
+
82
103
  function presenceOrdinal(catalog, label) {
83
104
  const ordinal = standardOrdinal(catalog, 'presence', label);
84
105
  if (ordinal !== null) return ordinal;
@@ -18,10 +18,12 @@ const DIMENSION_SCALES = {
18
18
  const DIMENSION_ORDER = ['presence', 'frequency', 'intensity', 'interference', 'amount'];
19
19
 
20
20
  const CANONICAL_SOURCE = 'original';
21
+ const SUPPLEMENTARY_SOURCE = 'extra-question';
21
22
 
22
23
  function buildCatalog(items, composites = [], source = null) {
23
24
  const symptoms = {};
24
25
  const questionIndex = {};
26
+ const questionSource = {};
25
27
  const answerMap = {};
26
28
  const itemIndex = {};
27
29
 
@@ -57,6 +59,7 @@ function buildCatalog(items, composites = [], source = null) {
57
59
  if (questionId != null && dimension) {
58
60
  if (gradeableOnScale(dimension, options, map)) {
59
61
  questionIndex[String(questionId)] = [term, dimension];
62
+ questionSource[String(questionId)] = row.source ?? null;
60
63
  } else {
61
64
  logger.warn('[buildCatalog] question not indexed: no answer option grades on its dimension scale', {
62
65
  questionId,
@@ -86,6 +89,7 @@ function buildCatalog(items, composites = [], source = null) {
86
89
  },
87
90
  symptoms,
88
91
  question_index: questionIndex,
92
+ question_source: questionSource,
89
93
  item_index: itemIndex,
90
94
  answer_map: answerMap,
91
95
  composite_grades: compositeGrades,
@@ -169,6 +173,16 @@ function itemForQuestionId(catalog, questionId) {
169
173
  return Array.isArray(entry) && entry.length >= 2 ? [entry[0], entry[1]] : null;
170
174
  }
171
175
 
176
+ function isSupplementaryQuestion(catalog, questionId) {
177
+ return (catalog.question_source || {})[String(questionId).trim()] === SUPPLEMENTARY_SOURCE;
178
+ }
179
+
180
+ function isItemDimension(catalog, term, dimension) {
181
+ const rec = getSymptom(catalog, term);
182
+ return (rec ? rec.dimensions : [])
183
+ .some((d) => d.dimension === dimension && d.source !== SUPPLEMENTARY_SOURCE);
184
+ }
185
+
172
186
  function termForItem(catalog, item) {
173
187
  return catalog.item_index[String(item ?? '').trim()] || null;
174
188
  }
@@ -313,6 +327,8 @@ module.exports = {
313
327
  allTerms,
314
328
  compositeTableHash,
315
329
  itemForQuestionId,
330
+ isSupplementaryQuestion,
331
+ isItemDimension,
316
332
  termForItem,
317
333
  getSymptom,
318
334
  canonicalAnswer,
@@ -14,6 +14,7 @@ const schema = z.strictObject({
14
14
  effective: dateTime.nullable().default(null),
15
15
  triageId: z.string(),
16
16
  dimensionAnswers: z.record(z.string(), z.string()).default({}),
17
+ supplementaryAnswers: z.record(z.string(), z.string()).optional(),
17
18
  source: z.string().default('triage'),
18
19
  });
19
20
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.56.16",
3
+ "version": "5.56.18",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",