@peopl-health/nexus 6.0.7 → 6.0.9

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,8 +1,9 @@
1
1
  const { ladderFor, renderLadder } = require('../services/ctcaeLadderService');
2
2
  const {
3
- itemForQuestionId, affirmative, sentinelKind, dimensionsFor, isItemDimension,
3
+ itemForQuestionId, affirmative, sentinelKind, dimensionsFor, isItemDimension, getSymptom,
4
4
  } = require('../../fhir/helpers/terminologyHelper');
5
- const { daysSince } = require('../../utils/dateUtils');
5
+ const { termKey } = require('../../fhir/utils/normalizeUtils');
6
+ const { daysSince, mexicoDay } = require('../../utils/dateUtils');
6
7
  const { detectSafetyFlags } = require('./safetyFlagsHelper');
7
8
 
8
9
  const GRADE_FLOOR = 3;
@@ -110,6 +111,114 @@ const CHANGE_ES = {
110
111
 
111
112
  const ABSENT_CHANGE_RX = /^absent_(.+)_cluster$/;
112
113
 
114
+ const CHARACTERIZATION_WINDOW_DAYS = 14;
115
+ const CHARACTERIZATION_NOTE_LIMIT = 2;
116
+ const CHARACTERIZATION_NOTE_MAX_CHARS = 240;
117
+
118
+ const FUNCTIONAL_ANCHOR_ES = {
119
+ not_limited: 'no limita sus actividades',
120
+ instrumental_adl_limited: 'limita actividades instrumentales (cocinar, salir, trabajar)',
121
+ self_care_adl_limited: 'limita el autocuidado (bañarse, vestirse, comer)',
122
+ };
123
+
124
+ const REASK_RULE = 'no lo vuelvas a pedir en min_characterization_variables salvo que hoy suba el grado o el '
125
+ + 'paciente reporte un cambio';
126
+
127
+ // PRO-CTCAE G3 is the self-care clause: a composite that high re-opens any milder functional anchor.
128
+ const ANCHOR_REOPEN_GRADE = 3;
129
+
130
+ const KNOWN_HEADER = `Ya caracterizado en conversación (últimos ${CHARACTERIZATION_WINDOW_DAYS} días; es contexto, `
131
+ + `no evidencia de hoy; ${REASK_RULE}):`;
132
+
133
+ const clip = (text) => {
134
+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim();
135
+ return flat.length > CHARACTERIZATION_NOTE_MAX_CHARS ? `${flat.slice(0, CHARACTERIZATION_NOTE_MAX_CHARS - 1)}…` : flat;
136
+ };
137
+
138
+ // Grades are compared within the agent's own reads only; the questionnaire composite is a different scale.
139
+ function worsenedAfter(recent, anchored) {
140
+ const anchoredAt = Date.parse(anchored.performedAt);
141
+ const anchoredGrade = anchored.grade?.bestEstimate;
142
+ const later = recent
143
+ .filter((assessment) => Date.parse(assessment.performedAt) > anchoredAt)
144
+ .filter((assessment) => assessment.trajectory === 'worsening'
145
+ || (Number.isFinite(anchoredGrade) && Number(assessment.grade?.bestEstimate) > anchoredGrade));
146
+ return later.length ? mexicoDay(later[later.length - 1].performedAt) : null;
147
+ }
148
+
149
+ // The plan is otherwise blind to what the agent already characterized in chat and re-asks it every triage.
150
+ // A not_established anchor answers nothing, so the most recent established one inside the window wins.
151
+ function characterizationByTerm(openCases = [], now = Date.now()) {
152
+ const byTerm = new Map();
153
+ for (const { condition, latestAssessment, priorAssessments = [] } of openCases) {
154
+ const recent = [latestAssessment, ...priorAssessments]
155
+ .filter((assessment) => {
156
+ const age = assessment ? daysSince(assessment.performedAt, now) : null;
157
+ return age !== null && age <= CHARACTERIZATION_WINDOW_DAYS;
158
+ })
159
+ .sort((left, right) => Date.parse(right.performedAt) - Date.parse(left.performedAt));
160
+ const anchored = recent.find((assessment) => FUNCTIONAL_ANCHOR_ES[assessment.grade?.functionalAnchor]);
161
+ const notes = recent
162
+ .map((assessment) => ({ at: mexicoDay(assessment.performedAt), text: clip(assessment.reasoning || assessment.grade?.reasoning) }))
163
+ .filter((note) => note.text)
164
+ .slice(0, CHARACTERIZATION_NOTE_LIMIT);
165
+ if (!anchored && !notes.length) continue;
166
+ const key = termKey(condition.ctcaeTerm);
167
+ // Two open cases on one term: the one characterized most recently speaks for it.
168
+ const lastAt = Date.parse(recent[0].performedAt);
169
+ if (byTerm.has(key) && byTerm.get(key).lastAt >= lastAt) continue;
170
+ byTerm.set(key, {
171
+ lastAt,
172
+ functionalAnchor: anchored
173
+ ? {
174
+ at: mexicoDay(anchored.performedAt),
175
+ kind: anchored.grade.functionalAnchor,
176
+ label: FUNCTIONAL_ANCHOR_ES[anchored.grade.functionalAnchor],
177
+ worsenedAt: worsenedAfter(recent, anchored),
178
+ }
179
+ : null,
180
+ notes,
181
+ });
182
+ }
183
+ return byTerm;
184
+ }
185
+
186
+ function staleReason(anchor, todayGrade) {
187
+ if (anchor.worsenedAt) return `el caso empeoró después (${anchor.worsenedAt})`;
188
+ if (Number(todayGrade) >= ANCHOR_REOPEN_GRADE && anchor.kind !== 'self_care_adl_limited') {
189
+ return `hoy el cuestionario da grado ${todayGrade}`;
190
+ }
191
+ return null;
192
+ }
193
+
194
+ // An anchor that worsening has overtaken no longer describes the patient and must be asked again.
195
+ function withCurrentAnchor(entry, todayGrade = null) {
196
+ const anchor = entry?.functionalAnchor;
197
+ const reason = anchor ? staleReason(anchor, todayGrade) : null;
198
+ return reason ? { entry: { ...entry, functionalAnchor: null }, stale: { ...anchor, reason } } : { entry, stale: null };
199
+ }
200
+
201
+ const staleLine = (stale) => `El impacto funcional se caracterizó el ${stale.at} («${stale.label}»), pero ${stale.reason}: `
202
+ + 'ya no lo describe; vuelve a caracterizarlo.';
203
+
204
+ // Cases carry the CTCAE term ('anxiety') while the triage carries the PRO-CTCAE one ('anxious').
205
+ function knownFor(known, term, catalog, ladder) {
206
+ if (!known?.size) return null;
207
+ const ctcaeV5 = catalog?.symptoms ? getSymptom(catalog, term)?.ctcae_v5 : null;
208
+ const keys = [term, ladder?.ctcaeTerm, ctcaeV5 && String(ctcaeV5).split('\n')[0]].map(termKey).filter(Boolean);
209
+ const key = keys.find((candidate) => known.has(candidate));
210
+ return key ? known.get(key) : null;
211
+ }
212
+
213
+ function renderKnown(entry, indent, { noteLimit = CHARACTERIZATION_NOTE_LIMIT } = {}) {
214
+ const lines = [`${indent}${KNOWN_HEADER}`];
215
+ if (entry.functionalAnchor) {
216
+ lines.push(`${indent} impacto funcional (${entry.functionalAnchor.at}): ${entry.functionalAnchor.label}`);
217
+ }
218
+ for (const note of entry.notes.slice(0, noteLimit)) lines.push(`${indent} documentado el ${note.at}: «${note.text}»`);
219
+ return lines;
220
+ }
221
+
113
222
  const GRADE_BASIS_ES = {
114
223
  composite: 'la tabla compuesta del PRO-CTCAE resolvió el grado con las respuestas de arriba',
115
224
  presence: 'sólo se preguntó si el síntoma estaba presente; el grado no sale de una escala de severidad',
@@ -117,8 +226,10 @@ const GRADE_BASIS_ES = {
117
226
  partial: 'la tabla compuesta no resolvió la combinación completa; el grado es parcial',
118
227
  };
119
228
 
120
- function reportedSymptomEvidence(symptom, catalog) {
229
+ function reportedSymptomEvidence(symptom, catalog, known = null) {
121
230
  const lines = [`- ${symptom.term} (grado ${symptom.grade})`];
231
+ const ladder = catalog?.symptoms ? ladderFor(catalog, symptom.term) : null;
232
+ const { entry: knownEntry, stale } = withCurrentAnchor(knownFor(known, symptom.term, catalog, ladder), symptom.grade);
122
233
  const answers = symptom.dimensionAnswers || {};
123
234
  const answered = Object.keys(answers);
124
235
  if (answered.length) {
@@ -132,9 +243,18 @@ function reportedSymptomEvidence(symptom, catalog) {
132
243
  .map(([dimension, answer]) => `${DIMENSION_ES[dimension] || dimension}: ${answer}`)
133
244
  .join(' · ')}. Miden otra cosa que el ítem del PRO-CTCAE; no confirman ni descartan el síntoma.`);
134
245
  }
246
+ if (knownEntry && (knownEntry.functionalAnchor || knownEntry.notes.length)) lines.push(...renderKnown(knownEntry, ' '));
247
+ if (stale) lines.push(` ${staleLine(stale)}`);
135
248
  if (Array.isArray(catalog?.symptoms?.[symptom.term]?.dimensions)) {
136
- const missing = dimensionsFor(catalog, symptom.term)
249
+ const unasked = dimensionsFor(catalog, symptom.term)
137
250
  .filter((dimension) => isItemDimension(catalog, symptom.term, dimension) && !answered.includes(dimension));
251
+ // The ADL anchor is not the PRO-CTCAE interference scale, so it is named as what covers it, never dropped silently.
252
+ const interferenceCovered = Boolean(knownEntry?.functionalAnchor) && unasked.includes('interference');
253
+ const missing = interferenceCovered ? unasked.filter((dimension) => dimension !== 'interference') : unasked;
254
+ if (interferenceCovered) {
255
+ lines.push(' Interferencia: este ítem del PRO-CTCAE no la preguntó, pero el impacto funcional en actividades ya '
256
+ + 'se caracterizó en conversación (arriba); no la vuelvas a pedir por separado.');
257
+ }
138
258
  if (missing.length) {
139
259
  lines.push(` Atributos que este ítem del PRO-CTCAE no preguntó: ${missing
140
260
  .map((dimension) => DIMENSION_ES[dimension] || dimension).join(', ')}. No preguntado no es `
@@ -143,8 +263,7 @@ function reportedSymptomEvidence(symptom, catalog) {
143
263
  }
144
264
  const basis = GRADE_BASIS_ES[symptom.gradeBasis];
145
265
  if (basis) lines.push(` Base del grado (${symptom.gradeBasis}): ${basis}.`);
146
- const ladder = catalog?.symptoms ? ladderFor(catalog, symptom.term) : null;
147
- if (ladder) lines.push(...renderLadder(ladder, symptom.grade));
266
+ if (ladder) lines.push(...renderLadder(ladder, symptom.grade, { known: knownEntry }));
148
267
  return lines.join('\n');
149
268
  }
150
269
 
@@ -159,7 +278,10 @@ function buildSymptomsMetadata({
159
278
  nonIdentifiedSymptoms = null,
160
279
  stage = 'gate',
161
280
  catalog = null,
281
+ openCases = [],
282
+ now = Date.now(),
162
283
  }) {
284
+ const known = characterizationByTerm(openCases, now);
163
285
  const { reported, denied, unanswered } = splitByEpistemics({
164
286
  graded,
165
287
  askedTerms,
@@ -175,7 +297,7 @@ function buildSymptomsMetadata({
175
297
  + '.',
176
298
  );
177
299
  if (reported.length) {
178
- parts.push(reported.map((symptom) => reportedSymptomEvidence(symptom, catalog)).join('\n'));
300
+ parts.push(reported.map((symptom) => reportedSymptomEvidence(symptom, catalog, known)).join('\n'));
179
301
  }
180
302
  if (additionalSymptoms.length) {
181
303
  parts.push(
@@ -245,7 +367,8 @@ const OPEN_CASE_RULE = 'Son contexto de razonamiento, NO evidencia de hoy ni mat
245
367
  + 'recommendation.symptoms_patient_facing, symptoms ni targeted_ctcae_terms. \'improving\' o días sin '
246
368
  + 'evidencia no significan resuelto: si ya se escaló y no hay cierre documentado, anótalo como '
247
369
  + 'pendiente del equipo en el resumen interno (summary en el gate, summary_internal en el plan), nunca '
248
- + 'como tarjeta ni urgencia.';
370
+ + 'como tarjeta ni urgencia. Lo que un caso ya caracterizó en conversación (impacto funcional, carácter, '
371
+ + `patrón, momento del día, alivio) sí sigue vigente durante ${CHARACTERIZATION_WINDOW_DAYS} días: ${REASK_RULE}.`;
249
372
 
250
373
  const ESCALATION_RULE = 'Registran sólo lo que se ENVIÓ al equipo: nunca si respondió, qué indicó ni si se '
251
374
  + 'resolvió. Son contexto, no evidencia: una escalación pasada nunca crea, sostiene ni sube una urgencia '
@@ -255,8 +378,9 @@ const ESCALATION_RULE = 'Registran sólo lo que se ENVIÓ al equipo: nunca si re
255
378
  + 'tiempo transcurrido nunca justifica por sí solo una ruta mayor. En '
256
379
  + 'reason_for_escalation cita la evidencia de hoy y di si es nuevo, empeoramiento o persistencia.';
257
380
 
258
- function buildOpenCaseBlock(openCases = []) {
381
+ function buildOpenCaseBlock(openCases = [], now = Date.now()) {
259
382
  if (!openCases.length) return 'Sin casos clínicos abiertos.';
383
+ const known = characterizationByTerm(openCases, now);
260
384
  const lines = openCases.map((managedSymptom) => {
261
385
  const { condition, latestAssessment } = managedSymptom;
262
386
  const grade = latestAssessment.grade;
@@ -265,9 +389,13 @@ function buildOpenCaseBlock(openCases = []) {
265
389
  const parts = [condition.ctcaeTerm, condition.clinicalStatus, estimate];
266
390
  if (grade.confidence) parts.push(`confianza ${grade.confidence}`);
267
391
  if (latestAssessment.trajectory) parts.push(latestAssessment.trajectory);
268
- const quiet = daysSince(latestAssessment.performedAt, Date.now());
392
+ const quiet = daysSince(latestAssessment.performedAt, now);
269
393
  if (quiet !== null) parts.push(`${quiet} d sin evidencia nueva`);
270
- return `- ${parts.join(' · ')}`;
394
+ const { entry, stale } = withCurrentAnchor(known.get(termKey(condition.ctcaeTerm)));
395
+ const lines = [`- ${parts.join(' · ')}`];
396
+ if (entry && (entry.functionalAnchor || entry.notes.length)) lines.push(...renderKnown(entry, ' ', { noteLimit: 1 }));
397
+ if (stale) lines.push(` ${staleLine(stale)}`);
398
+ return lines.join('\n');
271
399
  });
272
400
  return `${lines.join('\n')}\n${OPEN_CASE_RULE}`;
273
401
  }
@@ -407,6 +535,7 @@ function buildCasoBase({
407
535
  stage = 'gate',
408
536
  catalog = null,
409
537
  symptomSignals = [],
538
+ now = Date.now(),
410
539
  }) {
411
540
  const cadenceLabel = CADENCE_LABEL[String(cadence || '').trim().toLowerCase()] || null;
412
541
  const suffix = `${authored ? ` (${authored})` : ''}${triageRecordId ? ` [id: ${triageRecordId}]` : ''}.`;
@@ -434,6 +563,8 @@ function buildCasoBase({
434
563
  nonIdentifiedSymptoms,
435
564
  stage,
436
565
  catalog,
566
+ openCases,
567
+ now,
437
568
  }),
438
569
  ];
439
570
  if (freeText) {
@@ -445,7 +576,7 @@ function buildCasoBase({
445
576
  buildSymptomChangeBlock(symptomsChange),
446
577
  '',
447
578
  '### Casos clínicos abiertos del paciente',
448
- buildOpenCaseBlock(openCases),
579
+ buildOpenCaseBlock(openCases, now),
449
580
  '',
450
581
  '### Escalaciones ya enviadas al equipo (últimos 14 días)',
451
582
  buildEscalationBlock(escalations),
@@ -467,6 +598,7 @@ function buildCasoBase({
467
598
  }
468
599
 
469
600
  module.exports = {
601
+ characterizationByTerm,
470
602
  buildExposureBlock,
471
603
  buildOpenCaseBlock,
472
604
  buildEscalationBlock,
@@ -40,7 +40,30 @@ function ladderFor(catalog, term) {
40
40
  return { ctcaeTerm: key, grades, criticalField: entry.criticalField || null };
41
41
  }
42
42
 
43
- function renderLadder(ladder, grade, { indent = ' ' } = {}) {
43
+ const KNOWN_FIELD_RULE = 'No lo vuelvas a pedir: úsalo para contrastar el grado. Pídelo de nuevo sólo si el '
44
+ + 'grado de hoy es mayor que el del caso o el paciente reporta un cambio.';
45
+
46
+ // known: what the conversation already characterized for this term (see characterizationByTerm).
47
+ function criticalFieldLine(ladder, known) {
48
+ const gap = CRITICAL_FIELD_GAPS[ladder.criticalField] || QUESTIONNAIRE_GAP;
49
+ if (ladder.criticalField === 'functional_impact' && known?.functionalAnchor) {
50
+ return `Dato que decide el grado de ${ladder.ctcaeTerm} (critical_field): functional_impact. `
51
+ + `El cuestionario no lo captura (${gap}), pero YA se caracterizó en conversación `
52
+ + `(${known.functionalAnchor.at}): ${known.functionalAnchor.label}. ${KNOWN_FIELD_RULE}`;
53
+ }
54
+ const base = `Dato que decide el grado de ${ladder.ctcaeTerm} (critical_field): ${ladder.criticalField}. `
55
+ + `No capturado por el cuestionario (${gap}): `;
56
+ if (known?.notes?.length) {
57
+ return `${base}antes de pedir caracterización, revisa lo ya caracterizado en conversación para este síntoma. `
58
+ + 'Si ya responde este dato, no lo vuelvas a pedir salvo que el grado de hoy sea mayor que el del caso o el '
59
+ + 'paciente reporte un cambio; si no lo responde, pide caracterización. En ambos casos el grado es una '
60
+ + 'aproximación del cuestionario; no lo presentes como grado CTCAE ni lo uses para confirmar un umbral.';
61
+ }
62
+ return `${base}pide caracterización en vez de asumirlo; el grado es una aproximación del cuestionario; no lo `
63
+ + 'presentes como grado CTCAE ni lo uses para confirmar un umbral.';
64
+ }
65
+
66
+ function renderLadder(ladder, grade, { indent = ' ', known = null } = {}) {
44
67
  const lines = [
45
68
  `${indent}Escala CTCAE de ${ladder.ctcaeTerm}. El grado de arriba es una APROXIMACIÓN calculada a partir `
46
69
  + 'del PRO-CTCAE, no una lectura de estas cláusulas: contrasta lo que el paciente describe contra '
@@ -52,14 +75,7 @@ function renderLadder(ladder, grade, { indent = ' ' } = {}) {
52
75
  const marker = Number(level) === Number(grade) ? ' <- grado calculado' : '';
53
76
  lines.push(`${indent} G${level}: ${description}${marker}`);
54
77
  }
55
- if (ladder.criticalField) {
56
- lines.push(
57
- `${indent}Dato que decide el grado de ${ladder.ctcaeTerm} (critical_field): ${ladder.criticalField}. `
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.',
61
- );
62
- }
78
+ if (ladder.criticalField) lines.push(`${indent}${criticalFieldLine(ladder, known)}`);
63
79
  return lines;
64
80
  }
65
81
 
@@ -5,7 +5,7 @@ const { getEscalationReview } = require('../models/escalationReviewModel');
5
5
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
6
6
  const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
7
7
 
8
- const { countMessages } = require('./messageService');
8
+ const { countMessages, getMessages } = require('./messageService');
9
9
  const { logPatientChange } = require('./patientService');
10
10
  const { getThreadInfo } = require('./threadService');
11
11
  const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES, PRE_DECISION_STATUSES, caseTakenReason, handOffToDoctor, teamAlertIdentity } = require('./escalationReviewService');
@@ -26,6 +26,7 @@ const GRAVE_REASONS = { unobtainable: 'no lo puede dar', unanswered: 'no contest
26
26
  const QUIET_REMINDER_TEXT = '¿Pudiste ver lo que te pregunté? Cuando puedas, respóndeme por aquí.';
27
27
  // A reminder this late (an outage, a deploy) is not sent.
28
28
  const QUIET_REMINDER_STALE_MS = 30 * 60 * 1000;
29
+ const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
29
30
  const getMessaging = () => require('../core/NexusMessaging');
30
31
 
31
32
  const noteOf = (text) => oneLineOf(text).slice(0, MAX_NOTE_LENGTH);
@@ -247,8 +248,14 @@ async function remindQuietPatient(review, clock, now) {
247
248
  // A short reply records no clinical update, so the patient's own messages decide whether she answered.
248
249
  if (await countMessages({ numero: review.patientCode, from_me: false, createdAt: { $gt: latest.createdAt } })) return;
249
250
 
251
+ // The draft's missing datum never reaches the bot, so the reminder needs a question of the bot's own still open in the chat.
252
+ // The reminder itself and a send that never arrived are no question of the bot's.
253
+ const [last] = await getMessages({
254
+ numero: review.patientCode, origin: { $nin: ['system', 'instruction'] }, body: { $ne: QUIET_REMINDER_TEXT }, 'statusInfo.status': { $nin: UNDELIVERED_STATUSES },
255
+ }, { sort: { createdAt: -1 }, limit: 1, select: 'from_me body' });
250
256
  let skippedReason = null;
251
257
  if (now.getTime() - dueAt.getTime() > QUIET_REMINDER_STALE_MS) skippedReason = 'stale';
258
+ else if (!last?.from_me || !String(last.body ?? '').includes('?')) skippedReason = 'no_open_question';
252
259
  else skippedReason = await takenOf(review, clock);
253
260
  if (!skippedReason && !await isWithin24HourWindow(review.patientCode)) skippedReason = 'outside_window';
254
261
  const entry = { draftAt: latest.createdAt, sentAt: now, skippedReason, delivered: null };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.7",
3
+ "version": "6.0.9",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",