@peopl-health/nexus 5.71.22 → 5.71.23

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.
@@ -14,8 +14,13 @@ function feverPatientTimerLive() {
14
14
  return flagOn('FEVER_PATIENT_TIMER_LIVE');
15
15
  }
16
16
 
17
+ function escalationPatientTimerLive() {
18
+ return flagOn('ESCALATION_PATIENT_TIMER_LIVE');
19
+ }
20
+
17
21
  module.exports = {
18
22
  escalationAssessmentLive,
23
+ escalationPatientTimerLive,
19
24
  escalationUpdateModeLive,
20
25
  feverPatientTimerLive,
21
26
  };
@@ -32,7 +32,10 @@ const { drugsNamedIn } = require('../clinical/services/treatmentProposalService'
32
32
  const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
33
33
  const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
34
34
  const { humanReplyFilter } = require('../clinical/config/safetyNetConfig');
35
- const { feverPatientTimerLive: feverTimerLive } = require('../clinical/flags/escalationFlags');
35
+ const {
36
+ feverPatientTimerLive: feverTimerLive,
37
+ escalationPatientTimerLive: escalationTimerLive,
38
+ } = require('../clinical/flags/escalationFlags');
36
39
  const { chemoContextLive } = require('../clinical/flags/clinicalContextFlags');
37
40
  const { daysSinceLastCytotoxic } = require('../clinical/helpers/chemoContextHelper');
38
41
  const { readRecordedChemo } = require('../clinical/helpers/clinicalProfileHelper');
@@ -77,6 +80,9 @@ const DEFAULT_FEVER_CHEMO_WINDOW_DAYS = 42;
77
80
  const FEVER_TIMER_PROMPT_ID = 'fever_patient_timer';
78
81
  const FEVER_TIMER_OPERATOR = 'fever_patient_timer';
79
82
  const FEVER_CATEGORY = 'febrile_neutropenia';
83
+ const DEFAULT_PATIENT_TIMER_MINUTES = 15;
84
+ const PATIENT_TIMER_PROMPT_IDS = { stat: 'stat_patient_timer', asap: 'asap_patient_timer' };
85
+ const PATIENT_TIMER_OPERATOR = 'escalation_patient_timer';
80
86
  const STAFF_ORIGINS = ['whatsapp_platform', 'instruction', 'system'];
81
87
  const PRE_DECISION_STATUSES = ['open', 'documenting', 'draft_ready', 'handing_off', 'awaiting_doctor'];
82
88
  const ALERT_OPERATOR = 'bot:escalationAlert';
@@ -555,7 +561,7 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
555
561
  const joined = await join();
556
562
  if (joined) {
557
563
  await scheduleDoctorAlert(joined, entry, now);
558
- await armFeverTimerOnJoin(joined, entry, now);
564
+ await armPatientTimerOnJoin(joined, entry, now);
559
565
  if (FOLLOWUP_STATUSES.includes(joined.status)) return await reopenFromFollowUp(joined, 'new_alarm');
560
566
  if (!DOCUMENTING_STATUSES.includes(joined.status)) {
561
567
  logger.error('[EscalationReview] An alarm arrived after the doctor already had the case', {
@@ -921,9 +927,9 @@ async function scheduleDoctorAlert(review, alarm, now) {
921
927
  }
922
928
  }
923
929
 
924
- const feverTimerMs = () => {
925
- const minutes = Number(runtimeConfig.get('FEVER_PATIENT_TIMER_MINUTES', DEFAULT_FEVER_TIMER_MINUTES));
926
- return (Number.isFinite(minutes) && minutes > 0 ? minutes : DEFAULT_FEVER_TIMER_MINUTES) * 60 * 1000;
930
+ const timerMs = (key, fallback) => {
931
+ const minutes = Number(runtimeConfig.get(key, fallback));
932
+ return (Number.isFinite(minutes) && minutes > 0 ? minutes : fallback) * 60 * 1000;
927
933
  };
928
934
 
929
935
  const feverChemoWindowDays = () => {
@@ -946,16 +952,41 @@ async function feverTimerGap(patientCode, now) {
946
952
  return days > feverChemoWindowDays() ? 'outside_chemo_window' : null;
947
953
  }
948
954
 
949
- // The timer runs from the first asap alert of this episode, so a retried alert never restarts it and a
950
- // decision taken after it (which counts as taking the case) never moves it.
951
- function feverTimerSince(review) {
952
- const asapAlerts = (review.doctorAlerts ?? []).filter((sent) => sent.kind === 'initial' && sent.urgencyLevel === 'asap');
953
- if (!asapAlerts.length) return null;
954
- const lastMs = new Date(asapAlerts.at(-1).sentAt).getTime();
955
+ // The timer runs from the first alert of this episode at its level, so a retried alert never restarts it
956
+ // and a decision taken after it (which counts as taking the case) never moves it.
957
+ function timerSince(review, level) {
958
+ const alerts = (review.doctorAlerts ?? []).filter((sent) => sent.kind === 'initial' && sent.urgencyLevel === level);
959
+ if (!alerts.length) return null;
960
+ const lastMs = new Date(alerts.at(-1).sentAt).getTime();
955
961
  const decidedMs = Math.max(-Infinity, ...(review.decisions ?? [])
956
962
  .map((decision) => new Date(decision.createdAt).getTime())
957
963
  .filter((ms) => ms < lastMs));
958
- return new Date(asapAlerts.find((sent) => new Date(sent.sentAt).getTime() > decidedMs).sentAt);
964
+ return new Date(alerts.find((sent) => new Date(sent.sentAt).getTime() > decidedMs).sentAt);
965
+ }
966
+
967
+ // The level whose timer is running: the highest alert sent since the last decision.
968
+ function timerLevelOf(review) {
969
+ const decidedMs = Math.max(-Infinity, ...(review.decisions ?? []).map((decision) => new Date(decision.createdAt).getTime()));
970
+ const alerted = (level) => (review.doctorAlerts ?? [])
971
+ .some((sent) => sent.kind === 'initial' && sent.urgencyLevel === level && new Date(sent.sentAt).getTime() > decidedMs);
972
+ return alerted('stat') ? 'stat' : 'asap';
973
+ }
974
+
975
+ // An asap fever on a recent cytotoxic cycle gets the fever prompt; any other stat or asap case gets its
976
+ // level's prompt while that timer is live. `gap` says why the fever prompt does not apply. Without the
977
+ // level timers, a prompt that fires was armed as the fever prompt and fires as armed.
978
+ async function patientTimerOf(review, level, now, { firing = false } = {}) {
979
+ const levelTimer = escalationTimerLive() && Boolean(PATIENT_TIMER_PROMPT_IDS[level]);
980
+ const armedAsFever = firing && !levelTimer && (review.alarms ?? []).some((alarm) => appliedLevelOf(alarm) === 'asap' && alarm.category === FEVER_CATEGORY);
981
+ const fever = level === 'asap' && feverTimerLive() && (armedAsFever || feverAlarmsOf(review).length > 0);
982
+ const gap = fever && !armedAsFever ? await feverTimerGap(review.patientCode, now) : null;
983
+ if (fever && !gap) {
984
+ 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 };
985
+ }
986
+ if (levelTimer) {
987
+ 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 };
988
+ }
989
+ return { timer: null, gap };
959
990
  }
960
991
 
961
992
  // One prompt per episode: a prompt delivered (or possibly delivered) since the episode began, or one whose
@@ -969,19 +1000,20 @@ function promptedSince(review, since, ownStart = null) {
969
1000
  return delivered || (startedMs != null && startedMs >= sinceMs && startedMs !== ownStart?.getTime());
970
1001
  }
971
1002
 
972
- // An approver merely opening the review does not count: only an answer, a stat escalation, a paused
973
- // thread or a staff member writing to the patient means someone took the case.
974
- async function feverTakenReason(review, since, ownStart = null) {
975
- // Staff acting before the fever reached the review (on an earlier asap of the same episode) did not
976
- // take the fever case: those signals count only from the first asap fever alarm onwards.
977
- const firstFever = feverAlarmsOf(review)[0];
978
- const from = new Date(Math.max(since.getTime(), firstFever ? new Date(firstFever.raisedAt).getTime() : -Infinity));
1003
+ // An approver merely opening the review does not count: only an answer, a stat escalation of an asap
1004
+ // case, a paused thread or a staff member writing to the patient means someone took the case.
1005
+ async function takenReason(review, since, timer, ownStart = null) {
1006
+ // Staff acting before the case reached its timed level (on an earlier alarm of the same episode) did
1007
+ // not take it: those signals count only from the first alarm the timer is for.
1008
+ const atLevel = (alarm) => alarm.urgencyLevel === timer.level || appliedLevelOf(alarm) === timer.level;
1009
+ const first = (timer.fever ? feverAlarmsOf(review) : currentAlarms(review).filter(atLevel))[0];
1010
+ const from = new Date(Math.max(since.getTime(), first ? new Date(first.raisedAt).getTime() : -Infinity));
979
1011
  const atOrAfter = (at) => at != null && new Date(at).getTime() >= from.getTime();
980
1012
  if (review.closedAt || !PRE_DECISION_STATUSES.includes(review.status)) return 'review_moved_on';
981
1013
  if (promptedSince(review, since, ownStart)) return 'already_prompted';
982
1014
  if ((review.decisions ?? []).some((decision) => atOrAfter(decision.createdAt))) return 'decision';
983
1015
  const stat = (alarm) => alarm.urgencyLevel === 'stat' || alarm.appliedLevel === 'stat';
984
- if (currentAlarms(review).some(stat)) return 'stat_alarm';
1016
+ if (timer.level !== 'stat' && currentAlarms(review).some(stat)) return 'stat_alarm';
985
1017
  if ((review.urgencyReclassifications ?? []).some((change) => atOrAfter(change.at))) return 'reclassified';
986
1018
  if ((review.callLogs ?? []).some((call) => call.outcome === 'contacted' && atOrAfter(call.calledAt))) return 'call_contacted';
987
1019
  // A read error goes back to the sweep to retry; only a thread that does not exist (no turn to run
@@ -995,26 +1027,27 @@ async function feverTakenReason(review, since, ownStart = null) {
995
1027
  return staffMessages ? 'staff_message' : null;
996
1028
  }
997
1029
 
998
- async function armFeverTimerOnJoin(review, alarm, now) {
1030
+ async function armPatientTimerOnJoin(review, alarm, now) {
999
1031
  try {
1000
- if (!feverTimerLive() || appliedLevelOf(alarm) !== 'asap' || alarm.category !== FEVER_CATEGORY) return;
1001
- if (alertedRankOf(review) !== URGENCY_RANK.asap) return;
1002
- const since = feverTimerSince(review);
1032
+ const level = appliedLevelOf(alarm);
1033
+ if (!escalationTimerLive() && !(feverTimerLive() && level === 'asap' && alarm.category === FEVER_CATEGORY)) return;
1034
+ if (!ALERTED_URGENCIES.includes(level) || alertedRankOf(review) !== URGENCY_RANK[level]) return;
1035
+ const since = timerSince(review, level);
1003
1036
  if (!since || promptedSince(review, since)) return;
1004
1037
  if (review.doctorAlertDueAt) return;
1005
- const gap = await feverTimerGap(review.patientCode, now);
1006
- if (gap) {
1007
- await audit(review, ALERT_OPERATOR, null, { action: 'patient_prompt_not_armed', reason: gap });
1038
+ const { timer, gap } = await patientTimerOf(review, level, now);
1039
+ if (!timer) {
1040
+ if (gap) await audit(review, ALERT_OPERATOR, null, { action: 'patient_prompt_not_armed', reason: gap });
1008
1041
  return;
1009
1042
  }
1010
1043
  // The patient gets the full timer from when the case became eligible, not from the earlier alert.
1011
1044
  await getEscalationReview().updateOne(
1012
1045
  { _id: review._id, doctorAlertDueAt: null },
1013
- { $set: { doctorAlertDueAt: new Date(now.getTime() + feverTimerMs()), doctorAlertKind: 'patient_prompt', doctorAlertAttempts: 0 } },
1046
+ { $set: { doctorAlertDueAt: new Date(now.getTime() + timer.ms), doctorAlertKind: 'patient_prompt', doctorAlertAttempts: 0 } },
1014
1047
  BOOKKEEPING,
1015
1048
  );
1016
1049
  } catch (error) {
1017
- logger.error('[EscalationReview] The fever patient timer was not set for a joining alarm', { escalationReviewId: String(review?._id), error: redactedError(error) });
1050
+ logger.error('[EscalationReview] The patient timer was not set for a joining alarm', { escalationReviewId: String(review?._id), error: redactedError(error) });
1018
1051
  }
1019
1052
  }
1020
1053
 
@@ -1056,33 +1089,36 @@ async function sendPatientPrompt({ id, release, lease, now }) {
1056
1089
  await audit(current, ALERT_OPERATOR, null, { action: 'patient_prompt_skipped', reason });
1057
1090
  return null;
1058
1091
  };
1059
- if (!feverTimerLive()) return skip(review, 'flag_off');
1060
- const since = feverTimerSince(review);
1061
- if (!since) return skip(review, 'no_asap_alert');
1062
- const taken = await feverTakenReason(review, since);
1092
+ if (!feverTimerLive() && !escalationTimerLive()) return skip(review, 'flag_off');
1093
+ const level = timerLevelOf(review);
1094
+ const since = timerSince(review, level);
1095
+ if (!since) return skip(review, `no_${level}_alert`);
1096
+ const { timer, gap } = await patientTimerOf(review, level, now, { firing: true });
1097
+ if (!timer) return skip(review, gap ?? 'flag_off');
1098
+ const taken = await takenReason(review, since, timer);
1063
1099
  if (taken) return skip(review, taken);
1064
1100
 
1065
1101
  let directive;
1066
1102
  try {
1067
- directive = String((await composePrompt({ promptId: FEVER_TIMER_PROMPT_ID }))?.resolvedPrompt ?? '').trim();
1103
+ directive = String((await composePrompt({ promptId: timer.promptId }))?.resolvedPrompt ?? '').trim();
1068
1104
  } catch (composeError) {
1069
1105
  // A failed read may be transient: the same slot comes back shortly, and the sweep's attempt cap
1070
1106
  // drops it (with a ledger entry) if Airtable stays unreachable.
1071
- logger.error('[EscalationReview] The fever patient prompt could not be read; trying again shortly', { escalationReviewId: String(review._id), error: redactedError(composeError) });
1107
+ logger.error('[EscalationReview] The patient prompt could not be read; trying again shortly', { escalationReviewId: String(review._id), error: redactedError(composeError) });
1072
1108
  await release({ doctorAlertDueAt: new Date(Date.now() + ALERT_RETRY_DELAY_MS), doctorAlertKind: 'patient_prompt' });
1073
1109
  return null;
1074
1110
  }
1075
- let error = directive ? null : `the ${FEVER_TIMER_PROMPT_ID} prompt is empty or missing`;
1111
+ let error = directive ? null : `the ${timer.promptId} prompt is empty or missing`;
1076
1112
  let outcome = null;
1077
1113
  let startedAt = null;
1078
1114
  const settle = () => getEscalationReview()
1079
1115
  .updateOne({ _id: review._id, feverPromptStartedAt: startedAt }, { $set: { feverPromptStartedAt: null } }, BOOKKEEPING);
1080
1116
  if (error) {
1081
- logger.error('[EscalationReview] The fever patient prompt has no directive; nothing was sent', { escalationReviewId: String(review._id), error });
1117
+ logger.error('[EscalationReview] The patient prompt has no directive; nothing was sent', { escalationReviewId: String(review._id), error });
1082
1118
  await release();
1083
1119
  } else {
1084
1120
  const fresh = await loadReview(review._id);
1085
- const takenNow = await feverTakenReason(fresh, since);
1121
+ const takenNow = await takenReason(fresh, since, timer);
1086
1122
  if (takenNow) return skip(fresh, takenNow);
1087
1123
  // The instruction runs a whole agent turn, which can outlast the sweep's lease; letting go of the
1088
1124
  // slot first keeps a second sweep from prompting the patient twice.
@@ -1098,7 +1134,7 @@ async function sendPatientPrompt({ id, release, lease, now }) {
1098
1134
  // No turn ran: the same prompt comes back shortly, under the sweep's attempt cap. A draining
1099
1135
  // instance refused it before doing anything, so that refusal does not use up an attempt.
1100
1136
  const rearm = async (why) => {
1101
- logger.warn('[EscalationReview] The fever patient prompt ran no turn; trying again shortly', { escalationReviewId: String(review._id), why });
1137
+ logger.warn('[EscalationReview] The patient prompt ran no turn; trying again shortly', { escalationReviewId: String(review._id), why });
1102
1138
  const attempts = review.doctorAlertAttempts ?? 0;
1103
1139
  await settle();
1104
1140
  await getEscalationReview().updateOne(
@@ -1110,9 +1146,9 @@ async function sendPatientPrompt({ id, release, lease, now }) {
1110
1146
  };
1111
1147
  // The gate runs again under the chat lock, right before the turn: a patient turn queued ahead of
1112
1148
  // this one can raise the case to stat, pause the bot or bring staff in while the prompt waits.
1113
- const beforeRun = async () => feverTakenReason(await loadReview(review._id), since, startedAt);
1149
+ const beforeRun = async () => takenReason(await loadReview(review._id), since, timer, startedAt);
1114
1150
  try {
1115
- const result = await getMessaging().processInstruction(review.patientCode, directive, 'developer', { triggeredBy: FEVER_TIMER_OPERATOR, beforeRun });
1151
+ const result = await getMessaging().processInstruction(review.patientCode, directive, 'developer', { triggeredBy: timer.operator, beforeRun });
1116
1152
  outcome = result?.outcome ?? null;
1117
1153
  if (outcome === 'gated') {
1118
1154
  await settle();
@@ -1129,10 +1165,10 @@ async function sendPatientPrompt({ id, release, lease, now }) {
1129
1165
  // send happened: the same prompt comes back under the sweep's attempt cap.
1130
1166
  return rearm(sendError instanceof DrainingError ? 'draining' : redactedError(sendError));
1131
1167
  }
1132
- if (error) logger.error('[EscalationReview] The fever patient prompt was not sent', { escalationReviewId: String(review._id), error });
1168
+ if (error) logger.error('[EscalationReview] The patient prompt was not sent', { escalationReviewId: String(review._id), error });
1133
1169
  }
1134
1170
 
1135
- const sent = { kind: 'patient_prompt', urgencyLevel: 'asap', error, ...(outcome === 'threw' ? { possiblyDelivered: true } : {}), sentAt: now };
1171
+ const sent = { kind: 'patient_prompt', urgencyLevel: level, error, ...(outcome === 'threw' ? { possiblyDelivered: true } : {}), sentAt: now };
1136
1172
  const updated = await getEscalationReview()
1137
1173
  .findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
1138
1174
  if (startedAt) await settle();
@@ -1184,14 +1220,12 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
1184
1220
 
1185
1221
  const sent = { kind, urgencyLevel, transport: null, messageId: null, physicianEmail: null, error: null, ...delivery, sentAt: now };
1186
1222
  const updated = await EscalationReview.findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
1187
- // A fever asap case gets the patient timer even when the doctor alert failed: the doctor is retried
1188
- // while there is time before the prompt and attempts left, then the patient prompt is the safety net.
1189
- // Stat already sends the patient to the ED.
1223
+ // A timed case gets the patient timer even when the doctor alert failed: the doctor is retried while
1224
+ // there is time before the prompt and attempts left, then the patient prompt is the safety net.
1190
1225
  const latestReview = updated ?? review;
1191
- const since = feverTimerSince(latestReview) ?? now;
1192
- const feverCase = urgencyLevel === 'asap' && feverTimerLive() && feverAlarmsOf(latestReview).length > 0 && !promptedSince(latestReview, since);
1193
- const feverGap = feverCase ? await feverTimerGap(review.patientCode, now) : null;
1194
- const promptAt = feverCase && !feverGap ? since.getTime() + feverTimerMs() : null;
1226
+ const since = timerSince(latestReview, urgencyLevel) ?? now;
1227
+ const { timer, gap } = promptedSince(latestReview, since) ? {} : await patientTimerOf(latestReview, urgencyLevel, now);
1228
+ const promptAt = timer ? since.getTime() + timer.ms : null;
1195
1229
  const retriesDoctor = sent.error
1196
1230
  && (promptAt == null || (now.getTime() + ALERT_RETRY_DELAY_MS < promptAt && (review.doctorAlertAttempts ?? 0) < MAX_ALERT_ATTEMPTS));
1197
1231
  if (promptAt != null && !retriesDoctor) {
@@ -1218,7 +1252,7 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
1218
1252
  await audit(updated ?? review, ALERT_OPERATOR, null, {
1219
1253
  action: 'doctor_alerted', urgencyLevel, delivered: !sent.error,
1220
1254
  });
1221
- if (feverGap) await audit(updated ?? review, ALERT_OPERATOR, null, { action: 'patient_prompt_not_armed', reason: feverGap });
1255
+ if (gap && !timer) await audit(updated ?? review, ALERT_OPERATOR, null, { action: 'patient_prompt_not_armed', reason: gap });
1222
1256
  return updated;
1223
1257
  }
1224
1258
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.71.22",
3
+ "version": "5.71.23",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",