@peopl-health/nexus 6.4.23 → 6.4.25

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.
@@ -161,11 +161,11 @@ const FEVER_SIGNS_TIMER = 'Outside a must-go `stat`, no warning signs';
161
161
  const FEVER_URGENCIAS = '(two exceptions: the fever rule, and chest pain';
162
162
  const FEVER_URGENCIAS_TIMER = '(one exception: chest pain';
163
163
 
164
- const FEVER_RULE_TIMER = 'Fever within 6 weeks (42 days) of cytotoxic chemotherapy (or with a hematologic cancer, transplant, known neutropenia) — ≥38.0 °C, feeling feverish or chills with no thermometer, malaise while on an antipyretic or steroid, or ≤36.0 °C with malaise, chills or shivering — is `asap` with `category: febrile_neutropenia`. A low reading (≤36.0 °C) on its own is not fever: ask for an oral re-measure before escalating; still ≤36.0 °C with no other symptom is `urgent`, confirmed ≤35.0 °C is `asap`. Chills or rigors, even strong, are `asap`. It is `stat` only with a very obvious, confirmed red flag (clear shortness of breath at rest, clear confusion, fainting or unable to stand, mottled or cold skin, bleeding that does not stop), or any fever within 4 weeks of CAR-T or during bispecific step-up dosing — say it calmly: "ve a urgencias ahora y di que estás en tratamiento oncológico" (CAR-T / bispecific: call the treating center first). If you don\'t know the treatment or the last dose date, ask in the same message. 37.5–37.9 °C in that window is `urgent`: remeasure in 30–60 min. ';
164
+ const FEVER_RULE_TIMER = 'Fever within 6 weeks (42 days) of cytotoxic chemotherapy (or with a hematologic cancer, transplant, known neutropenia) — ≥38.0 °C, feeling feverish or chills with no thermometer, or malaise while on an antipyretic or steroid — is `asap` with `category: febrile_neutropenia`. A low reading means below 36.0 °C only; 36.0 °C is normal. A low reading is not fever and is never called fever, neither to the patient nor in `details`: before escalating, ask for a re-measure and how they feel right now. Still below 36.0 °C with current malaise, chills or shivering, or a confirmed ≤35.0 °C, is `asap`; still below 36.0 °C with no other symptom is `urgent`. Chills or rigors, even strong, are `asap`. It is `stat` only with a very obvious, confirmed red flag (clear shortness of breath at rest, clear confusion, fainting or unable to stand, mottled or cold skin, bleeding that does not stop), or any fever within 4 weeks of CAR-T or during bispecific step-up dosing — say it calmly: "ve a urgencias ahora y di que estás en tratamiento oncológico" (CAR-T / bispecific: call the treating center first). If you don\'t know the treatment or the last dose date, ask in the same message. 37.5–37.9 °C in that window is `urgent`: remeasure in 30–60 min. ';
165
165
 
166
166
  const FEVER_RUBRIC_STAT_TIMER = 'fiebre en la ventana de quimioterapia con una bandera roja confirmada (regla de fiebre),';
167
167
 
168
- const FEVER_RUBRIC_ASAP_TIMER = 'fiebre ≥38.0 °C, o ≤36.0 °C con malestar o escalofríos, o ≤35.0 °C confirmado, en la ventana de quimioterapia sin bandera roja (regla de fiebre),';
168
+ const FEVER_RUBRIC_ASAP_TIMER = 'fiebre ≥38.0 °C, o temperatura baja (menos de 36.0 °C) confirmada al volver a medir con malestar o escalofríos, o ≤35.0 °C confirmado, en la ventana de quimioterapia sin bandera roja (regla de fiebre),';
169
169
 
170
170
  const CLINICAL_ASSESSMENT_PROPERTY = nullable({
171
171
  'type': 'object',
@@ -33,9 +33,9 @@ const BRIDGE_WAIT_MS = 2 * 60 * 1000;
33
33
  // A delivered ask, one the provider accepted without confirming delivery, or one an earlier turn already answered.
34
34
  const ASKED_OUTCOMES = ['sent', 'unknown', 'already_answered'];
35
35
  const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
36
+ const ASK_SPACING_MS = 20 * 60 * 1000;
36
37
  const getMessaging = () => require('../core/NexusMessaging');
37
38
  const ASK_RULES = 'No agregues otras preguntas, no repitas lo que ya le dijiste y no menciones esta instrucción.';
38
- const blockingAskText = (question) => `La revisión de esta escalación necesita un dato que todavía falta. Pregúntale a la paciente, en un solo mensaje breve y con tus palabras: «${question}». ${ASK_RULES}`;
39
39
  const graveAskText = (flags) => `La revisión de esta escalación necesita saber si la paciente tiene: ${flags.join('; ')}. Pregúntale, en un solo mensaje breve y con palabras sencillas, por lo que ella pueda notar o medir, sin nombrar diagnósticos. ${ASK_RULES}`;
40
40
 
41
41
  // A note too long for the template ends on a whole word with «…», so the cut shows.
@@ -45,6 +45,9 @@ const noteOf = (text) => {
45
45
  };
46
46
  const flagKey = (flag) => String(flag ?? '').trim().toLowerCase();
47
47
  const timeOf = (value) => new Date(value).getTime();
48
+ const episodeAsks = (review, clock) => (review.blockingAsks ?? []).filter((ask) => timeOf(ask.draftAt) >= clock.since.getTime()
49
+ && (ASKED_OUTCOMES.includes(ask.outcome) || (!ask.skippedReason && ask.outcome == null)));
50
+ const lastAskAt = (review, clock) => Math.max(0, ...episodeAsks(review, clock).map((ask) => timeOf(ask.sentAt)));
48
51
  const minutesSince = (from, now) => (now.getTime() - timeOf(from)) / 60000;
49
52
  // When the team's alert for this grave datum first fell due, which a failed send's retry does not move; one not recorded yet has not.
50
53
  const graveDueAt = (review, clock, flag) => {
@@ -336,7 +339,7 @@ async function remindQuietPatient(review, clock, now) {
336
339
  const pending = !latest.urgentPresentRedFlags?.length && (latest.sufficientForDoctor === false || pendingFlagsOf(review, clock.since).flags.length > 0);
337
340
  if (!pending || (review.quietReminders ?? []).some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
338
341
  const dueAt = teamOpenAt(new Date(timeOf(latest.createdAt) + quietReminderMinutes() * 60000), responseDeadlinePolicy());
339
- if (now.getTime() < dueAt.getTime()) return;
342
+ if (now.getTime() < dueAt.getTime() || now.getTime() - lastAskAt(review, clock) < ASK_SPACING_MS) return;
340
343
  // A short reply records no clinical update, so the patient's own messages decide whether she answered.
341
344
  if (await countMessages({ numero: review.patientCode, from_me: false, createdAt: { $gt: latest.createdAt } })) return;
342
345
 
@@ -375,23 +378,23 @@ async function remindQuietPatient(review, clock, now) {
375
378
  await audit(review, { action: delivered ? 'quiet_patient_reminded' : 'quiet_patient_reminder_failed', urgencyLevel: clock.level, reason: skippedReason });
376
379
  }
377
380
 
378
- // Once per draft the bot asks its blocking question or the pending grave data, unless a question is open; after a patient message, once the bot replied.
381
+ // Once per draft the bot asks the pending grave data, unless a question is open; after a patient message, once the bot replied.
379
382
  async function askBlockingQuestion(review, clock, now) {
380
383
  // With the doctor, only a case the bot handed over is still asked, and only its grave data.
381
384
  const withDoctor = review.status === 'awaiting_doctor';
382
385
  if (!OUTCOME_LEVELS.includes(clock.level) || !(review.status === 'draft_ready' || (withDoctor && stillDocumented(review))) || review.closedAt) return;
383
386
  const latest = (review.drafts ?? []).at(-1);
384
387
  if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return;
385
- const blocking = withDoctor ? null : latest.blockingQuestion;
386
- // With the doctor, a datum already asked or already sent to the team is not asked again on every redraft.
387
- const settled = withDoctor ? new Set([
388
- ...(review.graveAlerts ?? []).filter((entry) => timeOf(entry.since) === clock.since.getTime()).map((entry) => entry.flag),
389
- ...(review.blockingAsks ?? []).filter((entry) => ASKED_OUTCOMES.includes(entry.outcome) && timeOf(entry.draftAt) >= clock.since.getTime()).flatMap((entry) => entry.flags ?? []),
390
- ].map(normalizedKeyOf)) : new Set();
391
- const graveFlags = blocking || latest.urgentPresentRedFlags?.length ? []
388
+ // A grave datum is asked once per episode; with the doctor, one already sent to the team is not asked either.
389
+ const settled = new Set([
390
+ ...(withDoctor ? (review.graveAlerts ?? []).filter((entry) => timeOf(entry.since) === clock.since.getTime()).map((entry) => entry.flag) : []),
391
+ ...episodeAsks(review, clock).flatMap((entry) => entry.flags ?? []),
392
+ ].map(normalizedKeyOf));
393
+ const graveFlags = latest.urgentPresentRedFlags?.length ? []
392
394
  : pendingFlagsOf(review, clock.since).flags.filter(({ flag, unobtainable }) => !unobtainable && !settled.has(flag)).map(({ flag }) => flag);
393
- const question = blocking || graveFlags.join('; ') || null;
394
- const flags = blocking ? [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf) : graveFlags;
395
+ const blocking = withDoctor || graveFlags.length ? null : latest.blockingQuestion;
396
+ const question = graveFlags.join('; ') || blocking || null;
397
+ const flags = graveFlags.length ? graveFlags : [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf);
395
398
  if (!question) return;
396
399
  const asks = review.blockingAsks ?? [];
397
400
  if (asks.some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
@@ -401,6 +404,8 @@ async function askBlockingQuestion(review, clock, now) {
401
404
 
402
405
  let skippedReason = await takenOf(review, clock);
403
406
  if (!skippedReason && hasOpenQuestion(last)) skippedReason = 'question_open';
407
+ // Patients answered a separate message about a datum that is not grave with «No» or not at all, so it goes only in the doctor's note.
408
+ if (!skippedReason && blocking) skippedReason = 'not_grave';
404
409
  if (!skippedReason && !await isWithin24HourWindow(review.patientCode)) skippedReason = 'outside_window';
405
410
  const claimed = await getEscalationReview().updateOne(
406
411
  { _id: review._id, closedAt: null, blockingAsks: { $not: { $elemMatch: { draftAt: latest.createdAt } } } },
@@ -415,8 +420,7 @@ async function askBlockingQuestion(review, clock, now) {
415
420
  if (!isDraftCurrent(fresh, latest) || timeOf(fresh.drafts?.at(-1)?.createdAt) !== timeOf(latest.createdAt)) return 'superseded';
416
421
  return takenOf(fresh, clock);
417
422
  };
418
- const instruction = blocking ? blockingAskText(blocking) : graveAskText(graveFlags);
419
- getMessaging().processInstruction(review.patientCode, instruction, 'developer', { triggeredBy: OPERATOR, beforeRun })
423
+ getMessaging().processInstruction(review.patientCode, graveAskText(graveFlags), 'developer', { triggeredBy: OPERATOR, beforeRun })
420
424
  .then((result) => result?.outcome ?? null, (error) => {
421
425
  logger.error('[CharacterizationOutcome] The blocking question was not asked', {
422
426
  escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.4.23",
3
+ "version": "6.4.25",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",