@peopl-health/nexus 6.5.0-dev.20076 → 6.5.0

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.
@@ -201,7 +201,7 @@ const briefDrugs = (draft) => (draft?.symptoms ?? []).flatMap((entry) => entry.p
201
201
 
202
202
  const namedFlags = (list) => (Array.isArray(list) ? list.map(oneLineOf).filter(Boolean) : []);
203
203
 
204
- function briefKeyLine(draft, entry) {
204
+ function briefKeyLine(draft, entry, lead = null) {
205
205
  const grave = namedFlags(draft?.urgentPresentRedFlags);
206
206
  const present = namedFlags(entry?.presentRedFlags).filter((flag) => !grave.includes(flag));
207
207
  const unknown = (namedFlags(draft?.urgentUnassessedRedFlags).length ? namedFlags(draft.urgentUnassessedRedFlags) : namedFlags(entry?.unassessedRedFlags))
@@ -209,6 +209,7 @@ function briefKeyLine(draft, entry) {
209
209
  const absent = namedFlags(entry?.absentRedFlags);
210
210
  const drugs = briefDrugs(draft);
211
211
  const parts = [
212
+ lead,
212
213
  grave.length && `⚠️ ${capitalized(grave.join(', '))}`,
213
214
  present.length && `Presente: ${present.join(', ')}`,
214
215
  unknown.length && `Sin dato aún: ${unknown.join(', ')}`,
@@ -227,16 +228,16 @@ function briefCaseLine(identity, entry, alarmSymptom) {
227
228
  }
228
229
 
229
230
  // The four lines of the doctor's alert; each is a template variable, so none may be empty.
230
- function doctorBrief({ kind, level, identity, draft, alarmSymptom = null, deadline = null, now = new Date(), timeZone, link }) {
231
+ function doctorBrief({ kind, change = null, level, identity, draft, alarmSymptom = null, deadline = null, now = new Date(), timeZone, link }) {
231
232
  const entry = briefSymptomOf(draft, alarmSymptom);
232
233
  // A grave flag present asks for an assessment whoever sends the case, not only the bot's act_now.
233
234
  const actNow = kind === 'act_now' || namedFlags(draft?.urgentPresentRedFlags).length > 0;
234
235
  const verb = actNow ? BRIEF_VERBS.act_now : (briefDrugs(draft).length ? BRIEF_VERBS.proposal : BRIEF_VERBS.indication);
235
236
  const mark = actNow ? '🔴' : BRIEF_MARKS[level];
236
237
  return [
237
- [[mark, verb].filter(Boolean).join(' '), deadlineLabel(deadline, now, timeZone)].filter(Boolean).join(' · '),
238
+ [[mark, change ? `Cambió: ${verb}` : verb].filter(Boolean).join(' '), deadlineLabel(deadline, now, timeZone)].filter(Boolean).join(' · '),
238
239
  briefCaseLine(identity, entry, alarmSymptom),
239
- briefKeyLine(draft, entry),
240
+ briefKeyLine(draft, entry, change === 'level' ? `Subió a ${URGENCY_LABELS[level]}` : null),
240
241
  link,
241
242
  ];
242
243
  }
@@ -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,13 +33,16 @@ 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
  const noteOf = (text) => cutOnWord(text, MAX_NOTE_LENGTH);
42
42
  const timeOf = (value) => new Date(value).getTime();
43
+ const episodeAsks = (review, clock) => (review.blockingAsks ?? []).filter((ask) => timeOf(ask.draftAt) >= clock.since.getTime()
44
+ && (ASKED_OUTCOMES.includes(ask.outcome) || (!ask.skippedReason && ask.outcome == null)));
45
+ const lastAskAt = (review, clock) => Math.max(0, ...episodeAsks(review, clock).map((ask) => timeOf(ask.sentAt)));
43
46
  const minutesSince = (from, now) => (now.getTime() - timeOf(from)) / 60000;
44
47
  // 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.
45
48
  const graveDueAt = (review, clock, flag) => {
@@ -95,7 +98,9 @@ function outcomeOf(review, clock, now) {
95
98
  const raisedSince = (level) => (review.alarms ?? []).some((alarm) => alarm.urgencyLevel === level && timeOf(alarm.raisedAt) > timeOf(last.createdAt));
96
99
  const rangSince = update && (review.doctorAlerts ?? []).some((sent) => sent.kind === 'initial' && !sent.error
97
100
  && sent.transport && sent.transport !== 'airtable' && timeOf(sent.sentAt) > timeOf(last.createdAt) && raisedSince(sent.urgencyLevel));
98
- const notify = !update || (!rangSince && ((present.length > 0 && !handedGrave) || rose));
101
+ const firstGrave = present.length > 0 && !handedGrave;
102
+ const notify = !update || (!rangSince && (firstGrave || rose));
103
+ const change = update && notify ? (firstGrave ? 'grave' : 'level') : null;
99
104
  // A missing grave datum is the team's to get: a first handoff waits the level's wait after the team's alert falls due, unless a grave flag is present.
100
105
  const teamFirst = !update && !present.length && grave.length + waiting.length > 0;
101
106
  const held = teamFirst && (waiting.length > 0 || grave.some(({ flag }) => now.getTime() < graveDueAt(review, clock, flag) + wait * 60000));
@@ -104,11 +109,11 @@ function outcomeOf(review, clock, now) {
104
109
  // A grave datum still inside its wait goes in the note too, so the doctor knows it is still open.
105
110
  const pending = pendingFlagsOf(review, clock.since).flags.map(({ flag }) => flag).filter((flag) => !graveFlags.some((entry) => entry.flag === flag));
106
111
  const note = [present.length && `Bandera grave presente: ${present.join(', ')}`, lacking, pending.length && `Pendiente: ${pending.join(', ')}`];
107
- return { grave, update, notify, held, note: withUpdate(noteOf(note.filter(Boolean).join(' · '))) };
112
+ return { grave, update, notify, ...(change && { change }), held, note: withUpdate(noteOf(note.filter(Boolean).join(' · '))) };
108
113
  }
109
114
  // A grave question still inside its wait holds the case even when the rest is enough.
110
115
  if (pendingFlagsOf(review, clock.since).flags.length) return null;
111
- if (latest.sufficientForDoctor === true) return { grave: [], update, notify, note: withUpdate(null) };
116
+ if (latest.sufficientForDoctor === true) return { grave: [], update, notify, ...(change && { change }), note: withUpdate(null) };
112
117
  if (latest.sufficientForDoctor !== false) return null;
113
118
  // The wait runs from the bot's question to the patient, so «no contestó» is said only of a question she was asked.
114
119
  const ask = (review.blockingAsks ?? []).find((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt));
@@ -118,7 +123,7 @@ function outcomeOf(review, clock, now) {
118
123
  if (minutesSince(sent ? ask.sentAt : latest.createdAt, now) < wait) return null;
119
124
  const missing = latest.blockingQuestion ? `Falta: ${latest.blockingQuestion}` : 'Falta información';
120
125
  // An update's draft is never asked about, so it says only what is missing.
121
- if (update) return { grave: [], update, notify, note: withUpdate(noteOf(missing)) };
126
+ if (update) return { grave: [], update, notify, ...(change && { change }), note: withUpdate(noteOf(missing)) };
122
127
  const asked = (sent && ASKED_OUTCOMES.includes(ask.outcome)) || ask?.skippedReason === 'question_open';
123
128
  return { grave: [], update, notify, note: noteOf(`${missing} (${asked ? 'no contestó' : 'no se le preguntó'})`) };
124
129
  }
@@ -172,7 +177,7 @@ async function handOff(review, clock, outcome, now) {
172
177
  try {
173
178
  if (digest) await getEscalationReview().updateOne({ _id: review._id }, { $set: { digestQueuedAt: now, digestClaimedAt: null, digestSentAt: null } }, BOOKKEEPING);
174
179
  const kind = review.drafts.at(-1)?.urgentPresentRedFlags?.length ? 'act_now' : 'ready';
175
- await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, handoffs: (review.doctorHandoffs ?? []).length, note: outcome.note, notify: outcome.notify && !digest, kind, level: clock.level, symptom: clock.symptom });
180
+ await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, handoffs: (review.doctorHandoffs ?? []).length, note: outcome.note, notify: outcome.notify && !digest, kind, change: outcome.change, level: clock.level, symptom: clock.symptom });
176
181
  } catch (error) {
177
182
  // Someone handed the case off since the sweep read it: nothing failed, and the next sweep reads the new handoff.
178
183
  const next = `doctorHandoffs.${(review.doctorHandoffs ?? []).length}`;
@@ -341,7 +346,7 @@ async function remindQuietPatient(review, clock, now) {
341
346
  const pending = !latest.urgentPresentRedFlags?.length && (latest.sufficientForDoctor === false || pendingFlagsOf(review, clock.since).flags.length > 0);
342
347
  if (!pending || (review.quietReminders ?? []).some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
343
348
  const dueAt = teamOpenAt(new Date(timeOf(latest.createdAt) + quietReminderMinutes() * 60000), responseDeadlinePolicy());
344
- if (now.getTime() < dueAt.getTime()) return;
349
+ if (now.getTime() < dueAt.getTime() || now.getTime() - lastAskAt(review, clock) < ASK_SPACING_MS) return;
345
350
  // A short reply records no clinical update, so the patient's own messages decide whether she answered.
346
351
  if (await countMessages({ numero: review.patientCode, from_me: false, createdAt: { $gt: latest.createdAt } })) return;
347
352
 
@@ -380,23 +385,23 @@ async function remindQuietPatient(review, clock, now) {
380
385
  await audit(review, { action: delivered ? 'quiet_patient_reminded' : 'quiet_patient_reminder_failed', urgencyLevel: clock.level, reason: skippedReason });
381
386
  }
382
387
 
383
- // 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.
388
+ // Once per draft the bot asks the pending grave data, unless a question is open; after a patient message, once the bot replied.
384
389
  async function askBlockingQuestion(review, clock, now) {
385
390
  // With the doctor, only a case the bot handed over is still asked, and only its grave data.
386
391
  const withDoctor = review.status === 'awaiting_doctor';
387
392
  if (!OUTCOME_LEVELS.includes(clock.level) || !(review.status === 'draft_ready' || (withDoctor && stillDocumented(review))) || review.closedAt) return;
388
393
  const latest = (review.drafts ?? []).at(-1);
389
394
  if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return;
390
- const blocking = withDoctor ? null : latest.blockingQuestion;
391
- // With the doctor, a datum already asked or already sent to the team is not asked again on every redraft.
392
- const settled = withDoctor ? new Set([
393
- ...(review.graveAlerts ?? []).filter((entry) => timeOf(entry.since) === clock.since.getTime()).map((entry) => entry.flag),
394
- ...(review.blockingAsks ?? []).filter((entry) => ASKED_OUTCOMES.includes(entry.outcome) && timeOf(entry.draftAt) >= clock.since.getTime()).flatMap((entry) => entry.flags ?? []),
395
- ].map(normalizedKeyOf)) : new Set();
396
- const graveFlags = blocking || latest.urgentPresentRedFlags?.length ? []
395
+ // A grave datum is asked once per episode; with the doctor, one already sent to the team is not asked either.
396
+ const settled = new Set([
397
+ ...(withDoctor ? (review.graveAlerts ?? []).filter((entry) => timeOf(entry.since) === clock.since.getTime()).map((entry) => entry.flag) : []),
398
+ ...episodeAsks(review, clock).flatMap((entry) => entry.flags ?? []),
399
+ ].map(normalizedKeyOf));
400
+ const graveFlags = latest.urgentPresentRedFlags?.length ? []
397
401
  : pendingFlagsOf(review, clock.since).flags.filter(({ flag, unobtainable }) => !unobtainable && !settled.has(flag)).map(({ flag }) => flag);
398
- const question = blocking || graveFlags.join('; ') || null;
399
- const flags = blocking ? [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf) : graveFlags;
402
+ const blocking = withDoctor || graveFlags.length ? null : latest.blockingQuestion;
403
+ const question = graveFlags.join('; ') || blocking || null;
404
+ const flags = graveFlags.length ? graveFlags : [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf);
400
405
  if (!question) return;
401
406
  const asks = review.blockingAsks ?? [];
402
407
  if (asks.some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
@@ -406,6 +411,8 @@ async function askBlockingQuestion(review, clock, now) {
406
411
 
407
412
  let skippedReason = await takenOf(review, clock);
408
413
  if (!skippedReason && hasOpenQuestion(last)) skippedReason = 'question_open';
414
+ // 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.
415
+ if (!skippedReason && blocking) skippedReason = 'not_grave';
409
416
  if (!skippedReason && !await isWithin24HourWindow(review.patientCode)) skippedReason = 'outside_window';
410
417
  const claimed = await getEscalationReview().updateOne(
411
418
  { _id: review._id, closedAt: null, blockingAsks: { $not: { $elemMatch: { draftAt: latest.createdAt } } } },
@@ -420,8 +427,7 @@ async function askBlockingQuestion(review, clock, now) {
420
427
  if (!isDraftCurrent(fresh, latest) || timeOf(fresh.drafts?.at(-1)?.createdAt) !== timeOf(latest.createdAt)) return 'superseded';
421
428
  return takenOf(fresh, clock);
422
429
  };
423
- const instruction = blocking ? blockingAskText(blocking) : graveAskText(graveFlags);
424
- getMessaging().processInstruction(review.patientCode, instruction, 'developer', { triggeredBy: OPERATOR, beforeRun })
430
+ getMessaging().processInstruction(review.patientCode, graveAskText(graveFlags), 'developer', { triggeredBy: OPERATOR, beforeRun })
425
431
  .then((result) => result?.outcome ?? null, (error) => {
426
432
  logger.error('[CharacterizationOutcome] The blocking question was not asked', {
427
433
  escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
@@ -1794,7 +1794,7 @@ async function soleApprover() {
1794
1794
  return approvers[0];
1795
1795
  }
1796
1796
 
1797
- function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom }) {
1797
+ function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change }) {
1798
1798
  const briefSid = runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY);
1799
1799
  // A navigator's draft is free text with no symptoms or flags to summarize, so it keeps the full alert.
1800
1800
  if (briefSid && draft.symptoms?.length) {
@@ -1802,6 +1802,7 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
1802
1802
  const lead = effectiveUrgencyOf(review);
1803
1803
  const lines = doctorBrief({
1804
1804
  kind,
1805
+ change,
1805
1806
  level: level ?? lead?.urgency,
1806
1807
  identity,
1807
1808
  draft,
@@ -1824,7 +1825,7 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
1824
1825
  }
1825
1826
 
1826
1827
  // With notify false the case is handed over in the platform without a WhatsApp to the doctor; `kind` (act_now, ready) picks the alert the doctor gets.
1827
- async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handoffs = null, note = null, notify = true, kind = null, level = null, symptom = null, requestId = null } = {}) {
1828
+ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handoffs = null, note = null, notify = true, kind = null, change = null, level = null, symptom = null, requestId = null } = {}) {
1828
1829
  const reviewId = reviewIdOf(id);
1829
1830
  const operator = requiredText(sentBy, 'sentBy');
1830
1831
  if (!HANDOFF_MODES.includes(mode)) throw httpError(400, `mode must be one of: ${HANDOFF_MODES.join(', ')}`);
@@ -1850,7 +1851,7 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handof
1850
1851
  const identity = await readDoctorIdentity(review);
1851
1852
  if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
1852
1853
  const link = doctorLink(review);
1853
- const message = doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom });
1854
+ const message = doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change });
1854
1855
 
1855
1856
  const patientCaseRecordIds = await reviewCaseIds(review);
1856
1857
 
@@ -3,7 +3,7 @@ const { logger } = require('../utils/logger');
3
3
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
4
4
  const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
5
5
  const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
6
- const { escalationAutoHandoffLive, escalationPatientTimerLive, escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
6
+ const { escalationAutoHandoffLive, escalationPatientTimerLive, escalationUntakenAlertsLive, feverPatientTimerLive } = require('../clinical/flags/escalationFlags');
7
7
 
8
8
  const { logPatientChange } = require('./patientService');
9
9
  const { BUSINESS_HOURS_LEVELS, levelsOf, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
@@ -87,10 +87,11 @@ function pendingQuestionOf(review, clock) {
87
87
  return question ? question.slice(0, MAX_QUESTION_LENGTH) : null;
88
88
  }
89
89
 
90
- // The early asap alert says when the armed prompt gives the patient the numbers; a fever prompt keeps its own wording.
90
+ // The early asap alert says when the armed prompt, the fever one included, gives the patient the numbers.
91
91
  function patientPromptNote(review, stage, now) {
92
- if (stage.stage !== 'early' || !escalationPatientTimerLive()) return null;
93
- if (currentAlarms(review).some((alarm) => alarm.category === FEVER_CATEGORY)) return null;
92
+ if (stage.stage !== 'early') return null;
93
+ const fever = currentAlarms(review).some((alarm) => alarm.category === FEVER_CATEGORY);
94
+ if (!(fever ? feverPatientTimerLive() : escalationPatientTimerLive())) return null;
94
95
  // A leased or retried slot (attempts above 0) is already being sent.
95
96
  if (review.doctorAlertKind !== 'patient_prompt' || (review.doctorAlertAttempts ?? 0) !== 0 || !review.doctorAlertDueAt) return null;
96
97
  const lead = Math.round((new Date(review.doctorAlertDueAt).getTime() - now.getTime()) / 60000);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.5.0-dev.20076",
3
+ "version": "6.5.0",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",