@peopl-health/nexus 5.72.0-dev.12926 → 5.72.0-dev.13736

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.
Files changed (46) hide show
  1. package/lib/clinical/flags/escalationFlags.js +10 -0
  2. package/lib/clinical/helpers/chemoContextHelper.js +25 -9
  3. package/lib/clinical/helpers/clinicalContextHelper.js +4 -1
  4. package/lib/clinical/helpers/clinicalProfileHelper.js +18 -4
  5. package/lib/clinical/helpers/drugIdentityHelper.js +60 -0
  6. package/lib/clinical/helpers/gradeEstimateHelper.js +3 -3
  7. package/lib/clinical/helpers/triageCaseBaseHelper.js +16 -3
  8. package/lib/clinical/providers/BaseLLMProvider.js +27 -8
  9. package/lib/clinical/services/clinicalExtractionService.js +12 -5
  10. package/lib/clinical/services/clinicalPatternFloorService.js +3 -2
  11. package/lib/clinical/services/currentRegimenService.js +60 -0
  12. package/lib/clinical/services/dispatcherService.js +11 -6
  13. package/lib/clinical/services/escalationDraftService.js +10 -4
  14. package/lib/clinical/services/gradeAnchorService.js +40 -18
  15. package/lib/clinical/services/gradeClaimService.js +15 -15
  16. package/lib/clinical/services/recommendationRankService.js +1 -1
  17. package/lib/clinical/services/regimenCloserService.js +125 -0
  18. package/lib/clinical/services/supportInvitability.js +6 -1
  19. package/lib/clinical/services/triageGateFloorService.js +1 -1
  20. package/lib/clinical/tools/extractClinicalInfoTool.js +27 -1
  21. package/lib/clinical/tools/openConditionTool.js +4 -2
  22. package/lib/clinical/tools/recordClinicalImpressionTool.js +11 -3
  23. package/lib/clinical/tools/reportMedicalEscalationTool.js +30 -8
  24. package/lib/clinical/tools/setContingencyPlanTool.js +3 -3
  25. package/lib/config/airtableConfig.js +2 -0
  26. package/lib/controllers/escalationReviewController.js +19 -16
  27. package/lib/core/NexusMessaging.js +60 -9
  28. package/lib/fhir/constants/escalationCaseStatus.js +31 -0
  29. package/lib/fhir/constants/projectionSlugs.js +6 -0
  30. package/lib/fhir/index.js +2 -1
  31. package/lib/fhir/projections/contextFactProjection.js +1 -0
  32. package/lib/fhir/resources/CommunicationRequest.js +1 -1
  33. package/lib/fhir/resources/Task.js +42 -1
  34. package/lib/fhir/services/escalationService.js +13 -0
  35. package/lib/index.d.ts +72 -2
  36. package/lib/index.js +6 -0
  37. package/lib/models/escalationReviewModel.js +34 -2
  38. package/lib/services/escalationCaseTaskService.js +35 -0
  39. package/lib/services/escalationReviewService.js +284 -48
  40. package/lib/services/reviewAlertSweepService.js +7 -2
  41. package/lib/services/reviewBoardService.js +2 -0
  42. package/lib/services/threadService.js +2 -1
  43. package/lib/shared/dtos/DispatchedEscalation.js +1 -0
  44. package/lib/utils/dateUtils.js +4 -0
  45. package/lib/utils/retryUtils.js +1 -0
  46. package/package.json +1 -1
@@ -5,7 +5,7 @@ const { httpError, requiredText } = require('../utils/httpErrorUtils');
5
5
  const { inlineOf } = require('../utils/coercionUtils');
6
6
  const { logger } = require('../utils/logger');
7
7
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
8
- const { isoDay } = require('../utils/dateUtils');
8
+ const { isoDay, mexicoDay } = require('../utils/dateUtils');
9
9
  const {
10
10
  CALL_OUTCOMES,
11
11
  CANCELLABLE_AFTER_HANDOFF_STATUSES,
@@ -23,20 +23,32 @@ const {
23
23
  const { getPatientAuditLog } = require('../models/patientAuditLogModel');
24
24
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
25
25
  const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
26
+ const { DrainingError } = require('../core/BatchingManager');
26
27
  const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
27
- const { conversationLink, recordEmergency, writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
28
+ const { conversationLink, writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
28
29
  const { renderDoctorMessage, templateSummary, withIdentity } = require('../clinical/helpers/doctorReviewMessageHelper');
29
30
  const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
30
31
  const { drugsNamedIn } = require('../clinical/services/treatmentProposalService');
31
32
  const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
32
33
  const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
34
+ const { humanReplyFilter } = require('../clinical/config/safetyNetConfig');
35
+ const {
36
+ feverPatientTimerLive: feverTimerLive,
37
+ escalationPatientTimerLive: escalationTimerLive,
38
+ } = require('../clinical/flags/escalationFlags');
39
+ const { chemoContextLive } = require('../clinical/flags/clinicalContextFlags');
40
+ const { daysSinceLastCytotoxic } = require('../clinical/helpers/chemoContextHelper');
41
+ const { readRecordedChemo } = require('../clinical/helpers/clinicalProfileHelper');
42
+ const { composePrompt } = require('../clinical/services/promptComposerService');
33
43
  const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
34
44
 
35
45
  const { getPatientInformation, logPatientChange } = require('./patientService');
36
46
  const { MAX_NOTE_LENGTH, getPatientTasks, openCaseIds, updatePatientTask } = require('./patientTaskService');
47
+ const { countMessages } = require('./messageService');
37
48
  const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
38
- const { switchThreadStoppedStatus } = require('./threadService');
49
+ const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
39
50
  const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
51
+ require('./escalationCaseTaskService');
40
52
 
41
53
  const getMessaging = () => require('../core/NexusMessaging');
42
54
 
@@ -49,6 +61,7 @@ const DRAFT_OPERATOR = 'bot:escalationDraft';
49
61
  const DIRECT_CHAT_ATTEMPTS = 3;
50
62
  const RECHECK_DELAY_MS = 60 * 1000;
51
63
  const ALERT_RETRY_DELAY_MS = 2 * 60 * 1000;
64
+ const MAX_ALERT_ATTEMPTS = 3;
52
65
  const BOOKKEEPING = { timestamps: false };
53
66
  const PREVIOUS_REVIEW_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
54
67
  const DUPLICATE_KEY_ERROR = 11000;
@@ -63,7 +76,15 @@ const DRAFTLESS_DECISIONS = ['monitor', 'returned'];
63
76
  const SETTLED_TRAJECTORIES = ['improving', 'stable'];
64
77
  const ALERTED_URGENCIES = ['stat', 'asap'];
65
78
  const ALERT_MARKS = { stat: '🔴', asap: '🟠' };
66
- const DEFAULT_STAT_REALERT_MINUTES = 15;
79
+ const DEFAULT_FEVER_TIMER_MINUTES = 15;
80
+ const DEFAULT_FEVER_CHEMO_WINDOW_DAYS = 42;
81
+ const FEVER_TIMER_PROMPT_ID = 'fever_patient_timer';
82
+ const FEVER_TIMER_OPERATOR = 'fever_patient_timer';
83
+ const FEVER_CATEGORY = 'febrile_neutropenia';
84
+ const DEFAULT_PATIENT_TIMER_MINUTES = 15;
85
+ const PATIENT_TIMER_PROMPT_IDS = { stat: 'stat_patient_timer', asap: 'asap_patient_timer' };
86
+ const PATIENT_TIMER_OPERATOR = 'escalation_patient_timer';
87
+ const STAFF_ORIGINS = ['whatsapp_platform', 'instruction', 'system'];
67
88
  const PRE_DECISION_STATUSES = ['open', 'documenting', 'draft_ready', 'handing_off', 'awaiting_doctor'];
68
89
  const ALERT_OPERATOR = 'bot:escalationAlert';
69
90
  const RECLASSIFIABLE_STATUSES = [...DOCUMENTING_STATUSES, 'awaiting_doctor'];
@@ -541,6 +562,7 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
541
562
  const joined = await join();
542
563
  if (joined) {
543
564
  await scheduleDoctorAlert(joined, entry, now);
565
+ await armPatientTimerOnJoin(joined, entry, now);
544
566
  if (FOLLOWUP_STATUSES.includes(joined.status)) return await reopenFromFollowUp(joined, 'new_alarm');
545
567
  if (!DOCUMENTING_STATUSES.includes(joined.status)) {
546
568
  logger.error('[EscalationReview] An alarm arrived after the doctor already had the case', {
@@ -597,6 +619,20 @@ async function attachEmergencyRow({ reviewId, alarmId, emergencyRecordId, applie
597
619
  }
598
620
  }
599
621
 
622
+ async function setAlarmAppliedLevel({ reviewId, alarmId, appliedLevel }) {
623
+ try {
624
+ await getEscalationReview().updateOne(
625
+ { _id: reviewId, 'alarms.alarmId': alarmId },
626
+ { $set: { 'alarms.$.appliedLevel': appliedLevel } },
627
+ { timestamps: false },
628
+ );
629
+ } catch (error) {
630
+ logger.error('[EscalationReview] The applied level was not recorded on its alarm', {
631
+ error: error.message, stack: redactedStack(error),
632
+ });
633
+ }
634
+ }
635
+
600
636
  async function openEscalationReview({
601
637
  code,
602
638
  patientCaseRecordId = null,
@@ -892,19 +928,131 @@ async function scheduleDoctorAlert(review, alarm, now) {
892
928
  }
893
929
  }
894
930
 
895
- const statRealertMs = () => {
896
- const minutes = Number(runtimeConfig.get('ESCALATION_REVIEW_STAT_REALERT_MINUTES', DEFAULT_STAT_REALERT_MINUTES));
897
- return (Number.isFinite(minutes) && minutes > 0 ? minutes : DEFAULT_STAT_REALERT_MINUTES) * 60 * 1000;
931
+ const timerMs = (key, fallback) => {
932
+ const minutes = Number(runtimeConfig.get(key, fallback));
933
+ return (Number.isFinite(minutes) && minutes > 0 ? minutes : fallback) * 60 * 1000;
898
934
  };
899
935
 
900
- function answeredSince(review, since) {
901
- const sinceMs = new Date(since).getTime();
902
- if (!PRE_DECISION_STATUSES.includes(review.status)) return true;
903
- if (review.approverViewedAt && new Date(review.approverViewedAt).getTime() >= sinceMs) return true;
904
- return (review.decisions ?? []).some((decision) => decision.createdAt && new Date(decision.createdAt).getTime() >= sinceMs);
936
+ const feverChemoWindowDays = () => {
937
+ const days = Number(runtimeConfig.get('FEVER_CHEMO_WINDOW_DAYS', DEFAULT_FEVER_CHEMO_WINDOW_DAYS));
938
+ return Number.isFinite(days) && days > 0 ? days : DEFAULT_FEVER_CHEMO_WINDOW_DAYS;
939
+ };
940
+
941
+ const appliedLevelOf = (alarm) => alarm.appliedLevel || alarm.urgencyLevel;
942
+
943
+ const feverAlarmsOf = (review) => currentAlarms(review)
944
+ .filter((alarm) => appliedLevelOf(alarm) === 'asap' && alarm.category === FEVER_CATEGORY);
945
+
946
+ async function feverTimerGap(patientCode, now) {
947
+ if (!chemoContextLive()) return 'chemo_context_off';
948
+ const chemo = await readRecordedChemo(patientCode);
949
+ if (chemo === undefined) return 'chemo_record_unreadable';
950
+ if (!chemo?.ultimaCitotoxica) return 'no_recorded_cytotoxic';
951
+ const days = daysSinceLastCytotoxic(chemo, mexicoDay(now));
952
+ if (days < 0) return 'last_cycle_in_future';
953
+ return days > feverChemoWindowDays() ? 'outside_chemo_window' : null;
954
+ }
955
+
956
+ // The timer runs from the first alert of this episode at its level, so a retried alert never restarts it
957
+ // and a decision taken after it (which counts as taking the case) never moves it.
958
+ function timerSince(review, level) {
959
+ const alerts = (review.doctorAlerts ?? []).filter((sent) => sent.kind === 'initial' && sent.urgencyLevel === level);
960
+ if (!alerts.length) return null;
961
+ const lastMs = new Date(alerts.at(-1).sentAt).getTime();
962
+ const decidedMs = Math.max(-Infinity, ...(review.decisions ?? [])
963
+ .map((decision) => new Date(decision.createdAt).getTime())
964
+ .filter((ms) => ms < lastMs));
965
+ return new Date(alerts.find((sent) => new Date(sent.sentAt).getTime() > decidedMs).sentAt);
966
+ }
967
+
968
+ // The level whose timer is running: the highest alert sent since the last decision.
969
+ function timerLevelOf(review) {
970
+ const decidedMs = Math.max(-Infinity, ...(review.decisions ?? []).map((decision) => new Date(decision.createdAt).getTime()));
971
+ const alerted = (level) => (review.doctorAlerts ?? [])
972
+ .some((sent) => sent.kind === 'initial' && sent.urgencyLevel === level && new Date(sent.sentAt).getTime() > decidedMs);
973
+ return alerted('stat') ? 'stat' : 'asap';
974
+ }
975
+
976
+ // An asap fever on a recent cytotoxic cycle gets the fever prompt; any other stat or asap case gets its
977
+ // level's prompt while that timer is live. `gap` says why the fever prompt does not apply. Without the
978
+ // level timers, a prompt that fires was armed as the fever prompt and fires as armed.
979
+ async function patientTimerOf(review, level, now, { firing = false } = {}) {
980
+ const levelTimer = escalationTimerLive() && Boolean(PATIENT_TIMER_PROMPT_IDS[level]);
981
+ const armedAsFever = firing && !levelTimer && (review.alarms ?? []).some((alarm) => appliedLevelOf(alarm) === 'asap' && alarm.category === FEVER_CATEGORY);
982
+ const fever = level === 'asap' && feverTimerLive() && (armedAsFever || feverAlarmsOf(review).length > 0);
983
+ const gap = fever && !armedAsFever ? await feverTimerGap(review.patientCode, now) : null;
984
+ if (fever && !gap) {
985
+ return { timer: { level, fever: true, promptId: FEVER_TIMER_PROMPT_ID, operator: FEVER_TIMER_OPERATOR, ms: timerMs('FEVER_PATIENT_TIMER_MINUTES', DEFAULT_FEVER_TIMER_MINUTES) }, gap };
986
+ }
987
+ if (levelTimer) {
988
+ return { timer: { level, fever: false, promptId: PATIENT_TIMER_PROMPT_IDS[level], operator: PATIENT_TIMER_OPERATOR, ms: timerMs('ESCALATION_PATIENT_TIMER_MINUTES', DEFAULT_PATIENT_TIMER_MINUTES) }, gap };
989
+ }
990
+ return { timer: null, gap };
991
+ }
992
+
993
+ // One prompt per episode: a prompt delivered (or possibly delivered) since the episode began, or one whose
994
+ // turn is still running, blocks another; an errored or dropped attempt does not. `ownStart` is the
995
+ // marker of the run asking, so its own in-flight marker never blocks it.
996
+ function promptedSince(review, since, ownStart = null) {
997
+ const sinceMs = since.getTime();
998
+ const delivered = (review.doctorAlerts ?? [])
999
+ .some((sent) => sent.kind === 'patient_prompt' && (!sent.error || sent.possiblyDelivered) && new Date(sent.sentAt).getTime() >= sinceMs);
1000
+ const startedMs = review.feverPromptStartedAt ? new Date(review.feverPromptStartedAt).getTime() : null;
1001
+ return delivered || (startedMs != null && startedMs >= sinceMs && startedMs !== ownStart?.getTime());
1002
+ }
1003
+
1004
+ // An approver merely opening the review does not count: only an answer, a stat escalation of an asap
1005
+ // case, a paused thread or a staff member writing to the patient means someone took the case.
1006
+ async function takenReason(review, since, timer, ownStart = null) {
1007
+ // Staff acting before the case reached its timed level (on an earlier alarm of the same episode) did
1008
+ // not take it: those signals count only from the first alarm the timer is for.
1009
+ const atLevel = (alarm) => alarm.urgencyLevel === timer.level || appliedLevelOf(alarm) === timer.level;
1010
+ const first = (timer.fever ? feverAlarmsOf(review) : currentAlarms(review).filter(atLevel))[0];
1011
+ const from = new Date(Math.max(since.getTime(), first ? new Date(first.raisedAt).getTime() : -Infinity));
1012
+ const atOrAfter = (at) => at != null && new Date(at).getTime() >= from.getTime();
1013
+ if (review.closedAt || !PRE_DECISION_STATUSES.includes(review.status)) return 'review_moved_on';
1014
+ if (promptedSince(review, since, ownStart)) return 'already_prompted';
1015
+ if ((review.decisions ?? []).some((decision) => atOrAfter(decision.createdAt))) return 'decision';
1016
+ const stat = (alarm) => alarm.urgencyLevel === 'stat' || alarm.appliedLevel === 'stat';
1017
+ if (timer.level !== 'stat' && currentAlarms(review).some(stat)) return 'stat_alarm';
1018
+ if ((review.urgencyReclassifications ?? []).some((change) => atOrAfter(change.at))) return 'reclassified';
1019
+ if ((review.callLogs ?? []).some((call) => call.outcome === 'contacted' && atOrAfter(call.calledAt))) return 'call_contacted';
1020
+ // A read error goes back to the sweep to retry; only a thread that does not exist (no turn to run
1021
+ // anyway) skips the prompt.
1022
+ const thread = await getThreadInfo(review.patientCode, { rethrow: true });
1023
+ if (!thread) return 'thread_missing';
1024
+ if (thread.stopped === true) return 'thread_paused';
1025
+ // Staff write from the platform or act through add-instruction / add-msg, always under their email;
1026
+ // automations (the timer itself included) sign with a name and never count.
1027
+ const staffMessages = await countMessages({ ...humanReplyFilter(review.patientCode, from), origin: { $in: STAFF_ORIGINS }, $and: [{ triggeredBy: /@/ }] });
1028
+ return staffMessages ? 'staff_message' : null;
1029
+ }
1030
+
1031
+ async function armPatientTimerOnJoin(review, alarm, now) {
1032
+ try {
1033
+ const level = appliedLevelOf(alarm);
1034
+ if (!escalationTimerLive() && !(feverTimerLive() && level === 'asap' && alarm.category === FEVER_CATEGORY)) return;
1035
+ if (!ALERTED_URGENCIES.includes(level) || alertedRankOf(review) !== URGENCY_RANK[level]) return;
1036
+ const since = timerSince(review, level);
1037
+ if (!since || promptedSince(review, since)) return;
1038
+ if (review.doctorAlertDueAt) return;
1039
+ const { timer, gap } = await patientTimerOf(review, level, now);
1040
+ if (!timer) {
1041
+ if (gap) await audit(review, ALERT_OPERATOR, null, { action: 'patient_prompt_not_armed', reason: gap });
1042
+ return;
1043
+ }
1044
+ // The patient gets the full timer from when the case became eligible, not from the earlier alert.
1045
+ await getEscalationReview().updateOne(
1046
+ { _id: review._id, doctorAlertDueAt: null },
1047
+ { $set: { doctorAlertDueAt: new Date(now.getTime() + timer.ms), doctorAlertKind: 'patient_prompt', doctorAlertAttempts: 0 } },
1048
+ BOOKKEEPING,
1049
+ );
1050
+ } catch (error) {
1051
+ logger.error('[EscalationReview] The patient timer was not set for a joining alarm', { escalationReviewId: String(review?._id), error: redactedError(error) });
1052
+ }
905
1053
  }
906
1054
 
907
- async function prepareDoctorAlert(review, kind, urgencyLevel) {
1055
+ async function prepareDoctorAlert(review, urgencyLevel) {
908
1056
  const identity = await readDoctorIdentity(review);
909
1057
  if (identity.missing.length) throw new Error(`missing ${identity.missing.join(' and ')}`);
910
1058
  const approver = await soleApprover();
@@ -912,7 +1060,7 @@ async function prepareDoctorAlert(review, kind, urgencyLevel) {
912
1060
  if (!link) throw new Error('missing the interface URL for the chat link');
913
1061
  const alarm = (review.alarms ?? []).findLast((raised) => raised.urgencyLevel === urgencyLevel) ?? review.alarms?.at(-1);
914
1062
  const symptom = inlineOf(alarm?.symptom);
915
- const urgency = [kind === 'realert' && 'Sigue pendiente', urgencyLevel.toUpperCase()].filter(Boolean).join(' · ');
1063
+ const urgency = urgencyLevel.toUpperCase();
916
1064
  const patient = `${identity.patientName} (${identity.treatingDoctor})`;
917
1065
  const message = {
918
1066
  body: `${ALERT_MARKS[urgencyLevel]} ${[urgency, patient, symptom].filter(Boolean).join(' · ')}\n${link}`,
@@ -933,7 +1081,101 @@ const topUrgencyOf = (review) => {
933
1081
  .reduce((top, alarm) => (URGENCY_RANK[alarm.urgencyLevel] > (URGENCY_RANK[top] || 0) ? alarm.urgencyLevel : top), null);
934
1082
  };
935
1083
 
936
- const realertStillDue = (review, initial) => !review.closedAt && Boolean(initial) && !answeredSince(review, initial.sentAt);
1084
+ const SENT_OUTCOMES = ['sent', 'unknown', 'already_answered'];
1085
+
1086
+ async function sendPatientPrompt({ id, release, lease, now }) {
1087
+ const review = await loadReview(reviewIdOf(id));
1088
+ const skip = async (current, reason) => {
1089
+ await release();
1090
+ await audit(current, ALERT_OPERATOR, null, { action: 'patient_prompt_skipped', reason });
1091
+ return null;
1092
+ };
1093
+ if (!feverTimerLive() && !escalationTimerLive()) return skip(review, 'flag_off');
1094
+ const level = timerLevelOf(review);
1095
+ const since = timerSince(review, level);
1096
+ if (!since) return skip(review, `no_${level}_alert`);
1097
+ const { timer, gap } = await patientTimerOf(review, level, now, { firing: true });
1098
+ if (!timer) return skip(review, gap ?? 'flag_off');
1099
+ const taken = await takenReason(review, since, timer);
1100
+ if (taken) return skip(review, taken);
1101
+
1102
+ let directive;
1103
+ try {
1104
+ directive = String((await composePrompt({ promptId: timer.promptId }))?.resolvedPrompt ?? '').trim();
1105
+ } catch (composeError) {
1106
+ // A failed read may be transient: the same slot comes back shortly, and the sweep's attempt cap
1107
+ // drops it (with a ledger entry) if Airtable stays unreachable.
1108
+ logger.error('[EscalationReview] The patient prompt could not be read; trying again shortly', { escalationReviewId: String(review._id), error: redactedError(composeError) });
1109
+ await release({ doctorAlertDueAt: new Date(Date.now() + ALERT_RETRY_DELAY_MS), doctorAlertKind: 'patient_prompt' });
1110
+ return null;
1111
+ }
1112
+ let error = directive ? null : `the ${timer.promptId} prompt is empty or missing`;
1113
+ let outcome = null;
1114
+ let startedAt = null;
1115
+ const settle = () => getEscalationReview()
1116
+ .updateOne({ _id: review._id, feverPromptStartedAt: startedAt }, { $set: { feverPromptStartedAt: null } }, BOOKKEEPING);
1117
+ if (error) {
1118
+ logger.error('[EscalationReview] The patient prompt has no directive; nothing was sent', { escalationReviewId: String(review._id), error });
1119
+ await release();
1120
+ } else {
1121
+ const fresh = await loadReview(review._id);
1122
+ const takenNow = await takenReason(fresh, since, timer);
1123
+ if (takenNow) return skip(fresh, takenNow);
1124
+ // The instruction runs a whole agent turn, which can outlast the sweep's lease; letting go of the
1125
+ // slot first keeps a second sweep from prompting the patient twice.
1126
+ const released = await release();
1127
+ if (lease && !released?.modifiedCount) {
1128
+ await audit(fresh, ALERT_OPERATOR, null, { action: 'lease_lost' });
1129
+ return null;
1130
+ }
1131
+ // While the turn runs, this marker stops both arming paths from setting a second prompt; it is
1132
+ // cleared once the turn settles, after the ledger entry that takes over is written.
1133
+ startedAt = new Date();
1134
+ await getEscalationReview().updateOne({ _id: review._id }, { $set: { feverPromptStartedAt: startedAt } }, BOOKKEEPING);
1135
+ // No turn ran: the same prompt comes back shortly, under the sweep's attempt cap. A draining
1136
+ // instance refused it before doing anything, so that refusal does not use up an attempt.
1137
+ const rearm = async (why) => {
1138
+ logger.warn('[EscalationReview] The patient prompt ran no turn; trying again shortly', { escalationReviewId: String(review._id), why });
1139
+ const attempts = review.doctorAlertAttempts ?? 0;
1140
+ await settle();
1141
+ await getEscalationReview().updateOne(
1142
+ { _id: review._id, doctorAlertDueAt: null },
1143
+ { $set: { doctorAlertDueAt: new Date(Date.now() + ALERT_RETRY_DELAY_MS), doctorAlertKind: 'patient_prompt', doctorAlertAttempts: why === 'draining' ? Math.max(0, attempts - 1) : attempts } },
1144
+ BOOKKEEPING,
1145
+ );
1146
+ return null;
1147
+ };
1148
+ // The gate runs again under the chat lock, right before the turn: a patient turn queued ahead of
1149
+ // this one can raise the case to stat, pause the bot or bring staff in while the prompt waits.
1150
+ const beforeRun = async () => takenReason(await loadReview(review._id), since, timer, startedAt);
1151
+ try {
1152
+ const result = await getMessaging().processInstruction(review.patientCode, directive, 'developer', { triggeredBy: timer.operator, beforeRun });
1153
+ outcome = result?.outcome ?? null;
1154
+ if (outcome === 'gated') {
1155
+ await settle();
1156
+ await audit(fresh, ALERT_OPERATOR, null, { action: 'patient_prompt_skipped', reason: result.reason });
1157
+ return null;
1158
+ }
1159
+ if (outcome === 'gate_error') return rearm(result.error ?? 'gate_error');
1160
+ if (outcome === null) return rearm('no_turn');
1161
+ // A send that threw ('threw') may still have reached the patient: recorded as possibly delivered,
1162
+ // so it is never sent again this episode.
1163
+ if (!SENT_OUTCOMES.includes(outcome)) error = `the instruction turn was not sent (outcome: ${outcome})`;
1164
+ } catch (sendError) {
1165
+ // processInstruction swallows send errors (they come back as 'threw'), so a throw here means no
1166
+ // send happened: the same prompt comes back under the sweep's attempt cap.
1167
+ return rearm(sendError instanceof DrainingError ? 'draining' : redactedError(sendError));
1168
+ }
1169
+ if (error) logger.error('[EscalationReview] The patient prompt was not sent', { escalationReviewId: String(review._id), error });
1170
+ }
1171
+
1172
+ const sent = { kind: 'patient_prompt', urgencyLevel: level, error, ...(outcome === 'threw' ? { possiblyDelivered: true } : {}), sentAt: now };
1173
+ const updated = await getEscalationReview()
1174
+ .findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
1175
+ if (startedAt) await settle();
1176
+ await audit(updated ?? review, ALERT_OPERATOR, null, { action: 'patient_prompted', delivered: !error, outcome });
1177
+ return updated;
1178
+ }
937
1179
 
938
1180
  async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date() } = {}) {
939
1181
  const EscalationReview = getEscalationReview();
@@ -941,34 +1183,33 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
941
1183
  const release = (set = { doctorAlertDueAt: null, doctorAlertKind: null, doctorAlertAttempts: 0 }) => EscalationReview
942
1184
  .updateOne({ _id: id, ...ours }, { $set: set }, BOOKKEEPING);
943
1185
 
944
- const review = await loadReview(reviewIdOf(id));
945
- if (review.closedAt || !PRE_DECISION_STATUSES.includes(review.status)) {
1186
+ // Stat re-alerts were retired; a review that still holds one lets the slot go without sending.
1187
+ if (kind === 'realert') {
946
1188
  await release();
947
1189
  return null;
948
1190
  }
949
- const initial = (review.doctorAlerts ?? []).filter((sent) => sent.kind === 'initial').at(-1);
950
- if (kind === 'realert' && !realertStillDue(review, initial)) {
1191
+ if (kind === 'patient_prompt') return sendPatientPrompt({ id, release, lease, now });
1192
+
1193
+ const review = await loadReview(reviewIdOf(id));
1194
+ if (review.closedAt || !PRE_DECISION_STATUSES.includes(review.status)) {
951
1195
  await release();
952
1196
  return null;
953
1197
  }
954
- const urgencyLevel = kind === 'realert' ? initial.urgencyLevel : topUrgencyOf(review);
1198
+ const urgencyLevel = topUrgencyOf(review);
955
1199
  if (!ALERTED_URGENCIES.includes(urgencyLevel)) {
956
1200
  await release();
957
1201
  return null;
958
1202
  }
959
- if (kind === 'initial' && (URGENCY_RANK[urgencyLevel] || 0) <= alertedRankOf(review)) {
1203
+ if ((URGENCY_RANK[urgencyLevel] || 0) <= alertedRankOf(review)) {
960
1204
  await release();
961
1205
  return null;
962
1206
  }
963
1207
 
964
1208
  let delivery;
965
1209
  try {
966
- const { approver, message } = await prepareDoctorAlert(review, kind, urgencyLevel);
1210
+ const { approver, message } = await prepareDoctorAlert(review, urgencyLevel);
967
1211
  const fresh = await loadReview(review._id);
968
- const stillDue = kind === 'realert'
969
- ? realertStillDue(fresh, initial)
970
- : !fresh.closedAt && PRE_DECISION_STATUSES.includes(fresh.status);
971
- if (!stillDue) {
1212
+ if (fresh.closedAt || !PRE_DECISION_STATUSES.includes(fresh.status)) {
972
1213
  await release();
973
1214
  return null;
974
1215
  }
@@ -978,32 +1219,24 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
978
1219
  logger.error('[EscalationReview] The doctor alert was not sent', { escalationReviewId: String(review._id), kind, error: delivery.error });
979
1220
  }
980
1221
 
981
- let teamAlerted = false;
982
- if (kind === 'realert') {
983
- const lead = review.alarms?.findLast((alarm) => alarm.urgencyLevel === 'stat') ?? review.alarms?.at(-1);
984
- teamAlerted = Boolean(await recordEmergency({
985
- code: review.patientCode,
986
- trace: null,
987
- symptom: lead?.symptom || 'Revisión clínica STAT',
988
- urgencyFhir: 'stat',
989
- documentation: `Re-aviso: revisión clínica STAT sin respuesta del médico ${Math.round(statRealertMs() / 60000)} min después del aviso.`,
990
- mergeWithRecent: false,
991
- }).catch((error) => {
992
- logger.error('[EscalationReview] The team alert for an unanswered stat review was not filed', { escalationReviewId: String(review._id), error: redactedError(error) });
993
- return false;
994
- }));
995
- }
996
-
997
- const sent = { kind, urgencyLevel, transport: null, messageId: null, physicianEmail: null, error: null, ...delivery, teamAlerted, sentAt: now };
1222
+ const sent = { kind, urgencyLevel, transport: null, messageId: null, physicianEmail: null, error: null, ...delivery, sentAt: now };
998
1223
  const updated = await EscalationReview.findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
999
- if (kind === 'initial' && urgencyLevel === 'stat') {
1000
- await release({ doctorAlertDueAt: new Date(now.getTime() + statRealertMs()), doctorAlertKind: 'realert', doctorAlertAttempts: 0 });
1001
- } else if (kind === 'initial' && sent.error) {
1224
+ // A timed case gets the patient timer even when the doctor alert failed: the doctor is retried while
1225
+ // there is time before the prompt and attempts left, then the patient prompt is the safety net.
1226
+ const latestReview = updated ?? review;
1227
+ const since = timerSince(latestReview, urgencyLevel) ?? now;
1228
+ const { timer, gap } = promptedSince(latestReview, since) ? {} : await patientTimerOf(latestReview, urgencyLevel, now);
1229
+ const promptAt = timer ? since.getTime() + timer.ms : null;
1230
+ const retriesDoctor = sent.error
1231
+ && (promptAt == null || (now.getTime() + ALERT_RETRY_DELAY_MS < promptAt && (review.doctorAlertAttempts ?? 0) < MAX_ALERT_ATTEMPTS));
1232
+ if (promptAt != null && !retriesDoctor) {
1233
+ await release({ doctorAlertDueAt: new Date(promptAt), doctorAlertKind: 'patient_prompt', doctorAlertAttempts: 0 });
1234
+ } else if (sent.error) {
1002
1235
  await release({ doctorAlertDueAt: new Date(Date.now() + ALERT_RETRY_DELAY_MS), doctorAlertKind: 'initial' });
1003
1236
  } else {
1004
1237
  await release();
1005
1238
  }
1006
- if (kind === 'initial' && urgencyLevel !== 'stat' && !sent.error) {
1239
+ if (urgencyLevel !== 'stat' && !sent.error) {
1007
1240
  try {
1008
1241
  const latest = await loadReview(review._id);
1009
1242
  const topNow = topUrgencyOf(latest);
@@ -1018,8 +1251,9 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
1018
1251
  }
1019
1252
  }
1020
1253
  await audit(updated ?? review, ALERT_OPERATOR, null, {
1021
- action: kind === 'realert' ? 'doctor_realerted' : 'doctor_alerted', urgencyLevel, delivered: !sent.error, teamAlerted,
1254
+ action: 'doctor_alerted', urgencyLevel, delivered: !sent.error,
1022
1255
  });
1256
+ if (gap && !timer) await audit(updated ?? review, ALERT_OPERATOR, null, { action: 'patient_prompt_not_armed', reason: gap });
1023
1257
  return updated;
1024
1258
  }
1025
1259
 
@@ -1840,6 +2074,7 @@ async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {})
1840
2074
  module.exports = {
1841
2075
  BOOKKEEPING,
1842
2076
  DOCUMENTING_STATUSES,
2077
+ MAX_ALERT_ATTEMPTS,
1843
2078
  PRE_DECISION_STATUSES,
1844
2079
  _resetEscalationReviewIndexes,
1845
2080
  addCallLog,
@@ -1862,6 +2097,7 @@ module.exports = {
1862
2097
  recordReviewUpdate,
1863
2098
  requestBotDraft,
1864
2099
  sendApprovedIndications,
2100
+ setAlarmAppliedLevel,
1865
2101
  setReviewCases,
1866
2102
  suggestDraft,
1867
2103
  suggestKeyQuestions,
@@ -3,13 +3,12 @@ const { createIntervalSweeper } = require('../utils/intervalSweeper');
3
3
  const { withTimeout } = require('../utils/timeoutUtils');
4
4
  const { getEscalationReview } = require('../models/escalationReviewModel');
5
5
 
6
- const { BOOKKEEPING, PRE_DECISION_STATUSES, sendScheduledDoctorAlert } = require('./escalationReviewService');
6
+ const { BOOKKEEPING, MAX_ALERT_ATTEMPTS, PRE_DECISION_STATUSES, sendScheduledDoctorAlert } = require('./escalationReviewService');
7
7
 
8
8
  const SWEEP_LIMIT = 10;
9
9
  const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
10
10
  const LEASE_MS = 5 * 60 * 1000;
11
11
  const SEND_TIMEOUT_MS = 2 * 60 * 1000;
12
- const MAX_ALERT_ATTEMPTS = 3;
13
12
  const SELF_HEAL_WINDOW_MS = 60 * 60 * 1000;
14
13
  const ALERTED_URGENCIES = ['stat', 'asap'];
15
14
 
@@ -63,6 +62,12 @@ async function sweepDoctorAlerts({ now = new Date(), clock = () => new Date() }
63
62
  .lean();
64
63
  if (!claimed) continue;
65
64
  const alert = sendScheduledDoctorAlert({ id: String(reviewId), kind, lease, now: claimedAt });
65
+ if (kind === 'patient_prompt') {
66
+ // A patient prompt runs a whole agent turn; the pass moves on so doctor alerts for other reviews
67
+ // are not held behind it. Its ledger entry and audit are written when the turn settles.
68
+ alert.catch((error) => logger.error('[ReviewAlertSweep] The fever patient prompt failed', { escalationReviewId: String(reviewId), error: error.message }));
69
+ continue;
70
+ }
66
71
  if (await withTimeout(alert, SEND_TIMEOUT_MS, 'doctor alert')) sent += 1;
67
72
  } catch (error) {
68
73
  logger.error('[ReviewAlertSweep] Could not alert the doctor for a review', { escalationReviewId: String(reviewId), error: error.message });
@@ -1,6 +1,7 @@
1
1
  const { httpError } = require('../utils/httpErrorUtils');
2
2
  const { FOLLOWUP_STATUSES, URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
3
3
 
4
+ const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
4
5
  const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
5
6
 
6
7
  const DONE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
@@ -31,6 +32,7 @@ const boardRowOf = (review, bucket, deadlinePolicy) => {
31
32
  patientCode: review.patientCode,
32
33
  bucket,
33
34
  status: review.status,
35
+ caseStatus: CASE_STATUS_BY_REVIEW_STATUS[review.status] ?? null,
34
36
  urgency: lead?.urgency || null,
35
37
  symptom: lead?.symptom || null,
36
38
  alarmCount: alarms.length,
@@ -25,11 +25,12 @@ const getThread = async (code, message = null) => {
25
25
  }
26
26
  };
27
27
 
28
- const getThreadInfo = async (code) => {
28
+ const getThreadInfo = async (code, { rethrow = false } = {}) => {
29
29
  try {
30
30
  return await Thread.findOne({ code });
31
31
  } catch (error) {
32
32
  logger.error('[getThreadInfo] Error', { code, error: error.message });
33
+ if (rethrow) throw error;
33
34
  return null;
34
35
  }
35
36
  };
@@ -9,6 +9,7 @@ const baseFields = {
9
9
  eventId: z.string(),
10
10
  patientId: z.string(),
11
11
  severity: z.enum(['critical', 'high', 'medium', 'low']),
12
+ priority: z.enum(['stat', 'asap', 'urgent', 'routine']).nullable().default(null),
12
13
  createdAt: dateTime,
13
14
  status: z.enum(['queued', 'sent', 'acknowledged', 'failed']).default('queued'),
14
15
  reason: z.string().nullable().default(null),
@@ -54,6 +54,9 @@ const mexicoDay = (value) => {
54
54
  return at.isValid() ? at.format('YYYY-MM-DD') : null;
55
55
  };
56
56
 
57
+ // whole days from one YYYY-MM-DD day to another
58
+ const daysBetween = (from, to) => Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 86400000);
59
+
57
60
  const mexicoIsoWeek = (value) => {
58
61
  if (value === null || value === undefined || value === '') return null;
59
62
  const at = moment.tz(value instanceof Date ? value.toISOString() : value, moment.ISO_8601, MEXICO_TZ);
@@ -95,6 +98,7 @@ module.exports = {
95
98
  toIsoInstant,
96
99
  ageInYears,
97
100
  isoDay,
101
+ daysBetween,
98
102
  mexicoDay,
99
103
  mexicoIsoWeek,
100
104
  mexicoStamp,
@@ -53,6 +53,7 @@ function isAbortError(error) {
53
53
  function isRetryableError(error) {
54
54
  if (!error) return false;
55
55
  if (isAbortError(error)) return false;
56
+ if (error.code === 'insufficient_quota') return false;
56
57
 
57
58
  const status = error?.status;
58
59
  const code = error?.code;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.72.0-dev.12926",
3
+ "version": "5.72.0-dev.13736",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",