@peopl-health/nexus 5.61.0-dev.11235 → 5.61.0-dev.11237

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.
@@ -265,9 +265,7 @@ class AssistantProcessor {
265
265
  patientText: ctx.patientInput?.text,
266
266
  });
267
267
  if (update) {
268
- // Required here: escalationReviewService reaches this module through NexusMessaging.
269
268
  const { recordReviewUpdate } = require('../services/escalationReviewService');
270
- // Awaited so it lands before the turn returns; it never throws and never fails the reply.
271
269
  await recordReviewUpdate({ code: thread.code, update });
272
270
  }
273
271
  }
@@ -22,7 +22,6 @@ const impressionOf = (call) => {
22
22
  caseId: textOf(args.case_id) || textOf(result?.case_id),
23
23
  ctcaeTerm: textOf(args.ctcae_term),
24
24
  event: call.tool_name === 'openCondition' ? 'opened' : textOf(args.event),
25
- // A carried-forward grade is resolved by the tool, so its result holds the grade the call omitted.
26
25
  grade: gradeOf(args.grade_estimate) ?? gradeOf(result?.grade_estimate),
27
26
  trajectory: textOf(args.trajectory_direction),
28
27
  missingForHigherGrade: textOf(args.missing_for_higher_grade),
@@ -32,8 +31,6 @@ const impressionOf = (call) => {
32
31
 
33
32
  const flagNameOf = (flag) => textOf(typeof flag === 'string' ? flag : flag?.flag);
34
33
 
35
- // What the agent characterized this turn, or null when it did not characterize anything:
36
- // a courtesy reply runs the extractor too, but leaves no mention, impression or escalation behind.
37
34
  function reviewUpdateOf({ turnId, toolHistory = [], signals = {}, patientText = null, at = new Date() } = {}) {
38
35
  const calls = toolHistory.filter((call) => CHARACTERIZATION_TOOLS.includes(call?.tool_name) && !isToolFailure(call.tool_output));
39
36
  const mentionCount = Array.isArray(signals?.clinicalMentions) ? signals.clinicalMentions.length : 0;
@@ -51,11 +48,8 @@ function reviewUpdateOf({ turnId, toolHistory = [], signals = {}, patientText =
51
48
  };
52
49
  }
53
50
 
54
- // The agent's own reading of each case since the escalation, handed to the draft so it builds on it
55
- // instead of re-deriving it: the latest impression per case, the safety flags and what the patient said.
56
51
  function characterizationSeedOf(updates = []) {
57
52
  if (!Array.isArray(updates) || !updates.length) return null;
58
- // Clinical order is the turn time, not the order the writes landed in.
59
53
  const byTime = [...updates].sort((a, b) => new Date(a.at) - new Date(b.at));
60
54
  const latestByCase = new Map();
61
55
  byTime.forEach((update) => (update.impressions || []).forEach((impression) => {
@@ -105,10 +105,7 @@ const sendMessageController = async (req, res) => {
105
105
  variables: finalVariables, code: formattedCode,
106
106
  frontendId, triggeredBy, idempotencyKey, ...contact
107
107
  });
108
- // Only a message the approver explicitly sent as the indication resolves the clinical review.
109
108
  if (asIndication === true && result?.success && triggeredBy && message && !contentSid && !contact.contactCode) {
110
- // Awaited so the review is usually settled before the reply returns, but never for long: the
111
- // message already went out, and a slow lookup finishes in the background. It never throws.
112
109
  await withTimeout(recordDirectIndication({
113
110
  code: formattedCode,
114
111
  triggeredBy,
package/lib/index.d.ts CHANGED
@@ -365,13 +365,11 @@ declare module '@peopl-health/nexus' {
365
365
  }
366
366
 
367
367
  export interface ReviewDraftsOptions {
368
- /** Writes the clinical review draft automatically after each alarm or agent update. */
369
368
  enabled?: boolean;
370
369
  intervalMs?: number;
371
370
  }
372
371
 
373
372
  export interface ReviewAlertsOptions {
374
- /** WhatsApps the approver on stat/asap reviews and re-alerts an unanswered stat review. */
375
373
  enabled?: boolean;
376
374
  intervalMs?: number;
377
375
  }
@@ -6,7 +6,6 @@ const { logger } = require('../utils/logger');
6
6
 
7
7
  const CALL_OUTCOMES = ['contacted', 'no_answer', 'voicemail'];
8
8
  const URGENCY_LEVELS = ['stat', 'asap', 'urgent', 'routine'];
9
- // One ranking for the board's order and the doctor alerts' urgency gate.
10
9
  const URGENCY_RANK = { routine: 1, urgent: 2, asap: 3, stat: 4 };
11
10
  const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
12
11
  const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
@@ -177,7 +176,6 @@ const escalationReviewSchema = new mongoose.Schema({
177
176
  updates: { type: [reviewUpdateSchema], default: [] },
178
177
  updatedSinceSeen: { type: Boolean, default: false },
179
178
  followUpCases: { type: [String], default: undefined },
180
- // The decision the follow-up cases were fixed for; a later indication extends them.
181
179
  followUpDecision: { type: Number, default: null },
182
180
  draftDueAt: { type: Date, default: null },
183
181
  draftAttempts: { type: Number, default: 0 },
@@ -53,7 +53,6 @@ const fetchFilteredThreads = async (threadFilter, skip, limit) => {
53
53
  return { threads, total, reviewMap: null };
54
54
  };
55
55
 
56
- // The board decides the order; only the requested page's threads are read in full.
57
56
  const fetchBoardThreads = async (bucket, skip, limit) => {
58
57
  const rows = await listReviewBoard({ bucket });
59
58
  const reviewMap = new Map(rows.map(({ patientCode, ...row }) => [patientCode, row]));
@@ -66,7 +65,6 @@ const fetchBoardThreads = async (bucket, skip, limit) => {
66
65
  const threads = page.length
67
66
  ? await Thread.find({ code: { $in: page }, lastMessageAt: { $ne: null } }).sort({ lastMessageAt: -1 }).lean()
68
67
  : [];
69
- // A patient can hold more than one thread; the most recently active one represents them.
70
68
  const threadByCode = new Map();
71
69
  threads.forEach((thread) => { if (!threadByCode.has(thread.code)) threadByCode.set(thread.code, thread); });
72
70
  return { threads: page.map((code) => threadByCode.get(code)).filter(Boolean), total: ordered.length, reviewMap };
@@ -45,8 +45,6 @@ const DRAFT_OPERATOR = 'bot:escalationDraft';
45
45
  const DIRECT_CHAT_ATTEMPTS = 3;
46
46
  const RECHECK_DELAY_MS = 60 * 1000;
47
47
  const ALERT_RETRY_DELAY_MS = 2 * 60 * 1000;
48
- // Scheduling bookkeeping is not a change to the review: it leaves updatedAt alone, so the handoff and
49
- // close checks that match on updatedAt are not tripped by a sweep.
50
48
  const BOOKKEEPING = { timestamps: false };
51
49
  const PREVIOUS_REVIEW_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
52
50
  const DUPLICATE_KEY_ERROR = 11000;
@@ -455,8 +453,6 @@ async function previousReviewIdOf(EscalationReview, patientCode, now) {
455
453
  }
456
454
  }
457
455
 
458
- // Files what the agent characterized after the escalation on the patient's open review, and sends a
459
- // returned review back to the queue. Never opens a review: only an escalation does.
460
456
  async function recordReviewUpdate({ code, update, now = new Date(), settleInBackground = true } = {}) {
461
457
  if (!update) return null;
462
458
  try {
@@ -477,7 +473,6 @@ async function recordReviewUpdate({ code, update, now = new Date(), settleInBack
477
473
  return await settleFollowUp(pushed, { background: settleInBackground });
478
474
  }
479
475
 
480
- // The turn that opened the review seeds its draft, but it is not news to whoever opens it.
481
476
  const openingTurn = pushed.alarms?.[0]?.turnId === update.turnId;
482
477
  const updated = openingTurn ? pushed : (await EscalationReview
483
478
  .findOneAndUpdate({ _id: pushed._id }, { $set: { updatedSinceSeen: true } }, { new: true })
@@ -612,7 +607,6 @@ async function getEscalationReviewById({ id, requestedBy } = {}) {
612
607
  const reviewId = reviewIdOf(id);
613
608
  const operator = requiredText(requestedBy, 'requestedBy');
614
609
  const review = await loadReview(reviewId);
615
- // The view happened once the review was read, not when the mark is written after the approver lookup.
616
610
  const readAt = new Date();
617
611
  const isApprover = await isEscalationApprover(operator);
618
612
  const EscalationReview = getEscalationReview();
@@ -620,15 +614,12 @@ async function getEscalationReviewById({ id, requestedBy } = {}) {
620
614
  escalationReviewId: String(review._id), error: redactedError(error),
621
615
  });
622
616
  if (review.updatedSinceSeen) {
623
- // Only clears what this read returned: an update that lands meanwhile changes updatedAt and stays unread.
624
- // A read is not a change: neither mark touches updatedAt, so handoff claims and grace periods hold.
625
617
  await EscalationReview
626
618
  .updateOne({ _id: review._id, updatedAt: review.updatedAt }, { $set: { updatedSinceSeen: false } }, { timestamps: false })
627
619
  .catch(warnUnmarked);
628
620
  }
629
621
  if (isApprover) {
630
622
  await EscalationReview
631
- // $max: a slow read finishing late never moves the last view back.
632
623
  .updateOne({ _id: review._id }, { $max: { approverViewedAt: readAt } }, { timestamps: false })
633
624
  .catch(warnUnmarked);
634
625
  }
@@ -637,7 +628,6 @@ async function getEscalationReviewById({ id, requestedBy } = {}) {
637
628
 
638
629
  async function getReviewTimeline({ id } = {}) {
639
630
  const review = await loadReview(reviewIdOf(id));
640
- // Newest first, so a busy review keeps its latest steps under the limit.
641
631
  const rows = await getPatientAuditLog()
642
632
  .find({ code: review.patientCode, source: AUDIT_SOURCE, 'changes.escalationReviewId': String(review._id) })
643
633
  .sort({ createdAt: -1 })
@@ -663,8 +653,6 @@ async function listEscalationReviews({ code } = {}) {
663
653
  return getEscalationReview().find({ patientCode }).sort({ createdAt: -1 }).limit(RECENT_REVIEW_LIMIT).lean();
664
654
  }
665
655
 
666
- // A call note is new material for the automatic draft: it re-arms it, and a draft generated without
667
- // the note is no longer saved.
668
656
  const redraftAfterCall = () => ({ draftDueAt: new Date(Date.now() + DRAFT_DEBOUNCE_MS), draftAttempts: 0 });
669
657
 
670
658
  async function appendKeepingDraft(id, entry) {
@@ -796,9 +784,6 @@ async function suggestDraft({ id, requestedBy, requestId = null } = {}) {
796
784
  return { ...draft, doctorText: withIdentity({ identity, review, doctorText: draft.doctorText }) };
797
785
  }
798
786
 
799
- // The most urgent level the doctor was actually alerted about since the last decision: a failed attempt
800
- // told them nothing, and a review reopened after a decision is a new question for them.
801
- // Scheduling and sending gate on the same one.
802
787
  const alertedRankOf = (review) => {
803
788
  const decidedAt = (review.decisions ?? []).at(-1)?.createdAt;
804
789
  const sinceMs = decidedAt ? new Date(decidedAt).getTime() : -Infinity;
@@ -807,12 +792,10 @@ const alertedRankOf = (review) => {
807
792
  .map((sent) => URGENCY_RANK[sent.urgencyLevel] || 0));
808
793
  };
809
794
 
810
- // A stat or asap alarm more urgent than anything the doctor was already told about is due now.
811
795
  async function scheduleDoctorAlert(review, alarm, now) {
812
796
  try {
813
797
  if (!ALERTED_URGENCIES.includes(alarm?.urgencyLevel)) return;
814
798
  if (URGENCY_RANK[alarm.urgencyLevel] <= alertedRankOf(review)) return;
815
- // An initial alert in flight holds its lease; its sender schedules this urgency once it is done.
816
799
  const scheduled = await getEscalationReview().updateOne(
817
800
  { _id: review._id, $nor: [{ doctorAlertKind: 'initial', doctorAlertDueAt: { $gt: now } }] },
818
801
  { $set: { doctorAlertDueAt: now, doctorAlertKind: 'initial', doctorAlertAttempts: 0 } },
@@ -829,7 +812,6 @@ const statRealertMs = () => {
829
812
  return (Number.isFinite(minutes) && minutes > 0 ? minutes : DEFAULT_STAT_REALERT_MINUTES) * 60 * 1000;
830
813
  };
831
814
 
832
- // The doctor answered once they opened the review or anything was decided after the alert.
833
815
  function answeredSince(review, since) {
834
816
  const sinceMs = new Date(since).getTime();
835
817
  if (!PRE_DECISION_STATUSES.includes(review.status)) return true;
@@ -851,8 +833,6 @@ async function prepareDoctorAlert(review, kind, urgencyLevel) {
851
833
  return { approver, message };
852
834
  }
853
835
 
854
- // The urgency the doctor is asked about now: alarms a decision already answered do not raise it, so a
855
- // review reopened by an asap alarm after a decided stat is an asap alert.
856
836
  const topUrgencyOf = (review) => {
857
837
  const alarms = review.alarms ?? [];
858
838
  const decidedAt = (review.decisions ?? []).at(-1)?.createdAt;
@@ -863,9 +843,6 @@ const topUrgencyOf = (review) => {
863
843
 
864
844
  const realertStillDue = (review, initial) => !review.closedAt && Boolean(initial) && !answeredSince(review, initial.sentAt);
865
845
 
866
- // Sends the alert the sweep claimed under `lease`. A stat alert arms the re-alert; the re-alert goes
867
- // out only if the doctor has not answered, checked again right before sending, and also files a new
868
- // emergency row so the team is alerted. The schedule is only touched while the lease is still ours.
869
846
  async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date() } = {}) {
870
847
  const EscalationReview = getEscalationReview();
871
848
  const ours = lease ? { doctorAlertDueAt: lease } : {};
@@ -873,7 +850,6 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
873
850
  .updateOne({ _id: id, ...ours }, { $set: set }, BOOKKEEPING);
874
851
 
875
852
  const review = await loadReview(reviewIdOf(id));
876
- // Once anything was decided, the doctor has nothing left to be alerted about.
877
853
  if (review.closedAt || !PRE_DECISION_STATUSES.includes(review.status)) {
878
854
  await release();
879
855
  return null;
@@ -884,7 +860,10 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
884
860
  return null;
885
861
  }
886
862
  const urgencyLevel = kind === 'realert' ? initial.urgencyLevel : topUrgencyOf(review);
887
- // The doctor already heard about this urgency (a recheck, or a retry whose record landed): nothing to send.
863
+ if (!ALERTED_URGENCIES.includes(urgencyLevel)) {
864
+ await release();
865
+ return null;
866
+ }
888
867
  if (kind === 'initial' && (URGENCY_RANK[urgencyLevel] || 0) <= alertedRankOf(review)) {
889
868
  await release();
890
869
  return null;
@@ -893,7 +872,6 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
893
872
  let delivery;
894
873
  try {
895
874
  const { approver, message } = await prepareDoctorAlert(review, kind, urgencyLevel);
896
- // Preparing takes lookups; a decision or close that landed meanwhile leaves nothing to alert about.
897
875
  const fresh = await loadReview(review._id);
898
876
  const stillDue = kind === 'realert'
899
877
  ? realertStillDue(fresh, initial)
@@ -926,8 +904,6 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
926
904
 
927
905
  const sent = { kind, urgencyLevel, transport: null, messageId: null, physicianEmail: null, error: null, ...delivery, teamAlerted, sentAt: now };
928
906
  const updated = await EscalationReview.findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
929
- // A failed stat alert still arms the re-alert, which also alerts the team. A failed asap alert has no
930
- // such backstop, so it is tried again; the sweep counts the attempts and drops it after the last.
931
907
  if (kind === 'initial' && urgencyLevel === 'stat') {
932
908
  await release({ doctorAlertDueAt: new Date(now.getTime() + statRealertMs()), doctorAlertKind: 'realert', doctorAlertAttempts: 0 });
933
909
  } else if (kind === 'initial' && sent.error) {
@@ -935,15 +911,12 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
935
911
  } else {
936
912
  await release();
937
913
  }
938
- // A more urgent alarm that landed while this alert was out could not take the lease. Read after the
939
- // release, so one landing later finds no lease and schedules itself.
940
914
  if (kind === 'initial' && urgencyLevel !== 'stat' && !sent.error) {
941
915
  try {
942
916
  const latest = await loadReview(review._id);
943
917
  const topNow = topUrgencyOf(latest);
944
918
  if (URGENCY_RANK[topNow] > (URGENCY_RANK[urgencyLevel] || 0)) await scheduleDoctorAlert(latest, { urgencyLevel: topNow }, new Date());
945
919
  } catch (error) {
946
- // Unread, so not known to be clear: the sweep checks again shortly, and a covered urgency sends nothing.
947
920
  logger.error('[EscalationReview] Could not check for a more urgent alarm after the alert', { escalationReviewId: String(review._id), error: redactedError(error) });
948
921
  await EscalationReview.updateOne(
949
922
  { _id: review._id, doctorAlertDueAt: null },
@@ -967,16 +940,11 @@ async function reopenFromFollowUp(review, reason) {
967
940
  return reopened;
968
941
  }
969
942
 
970
- // The agent's own trajectory for the cases of the review, read after the indication went out:
971
- // any of them worse sends the review back to the queue; all of them holding or better closes it.
972
- // A closed or resolved case is a settled one, whether or not the call carried a trajectory.
973
943
  const readingOf = (impression) => (['close', 'resolve_episode'].includes(impression.event) ? 'improving' : impression.trajectory);
974
944
 
975
945
  async function followUpCasesOf(review, sinceMs) {
976
946
  const decisionNumber = (review.decisions ?? []).length;
977
947
  if (review.followUpCases && review.followUpDecision === decisionNumber) return { review, known: new Set(review.followUpCases) };
978
- // Fixed once per indication, on its first follow-up reading, so later updates evicting old ones
979
- // cannot shrink it; a later indication keeps the cases already followed and adds the newer ones.
980
948
  const known = [...new Set([
981
949
  ...(review.followUpCases ?? []),
982
950
  ...(review.updates ?? [])
@@ -985,23 +953,17 @@ async function followUpCasesOf(review, sinceMs) {
985
953
  ])];
986
954
  const stored = await getEscalationReview()
987
955
  .findOneAndUpdate(
988
- // A decision added meanwhile starts its own follow-up; this one must not settle on its readings.
989
956
  { _id: review._id, followUpDecision: review.followUpDecision ?? null, decisions: { $size: decisionNumber } },
990
957
  { $set: { followUpCases: known, followUpDecision: decisionNumber } },
991
958
  { new: true },
992
959
  )
993
960
  .lean();
994
- // Lost to another writer: either a new decision, which starts its own follow-up, or a reply that
995
- // already fixed this set and settles it.
996
961
  if (!stored) return { review, known: new Set() };
997
- // Settles on what the write returned: a reading that landed after the snapshot is in it, and its
998
- // updatedAt is the one the close matches on.
999
962
  return { review: stored, known: new Set(known) };
1000
963
  }
1001
964
 
1002
965
  async function closeSettled(review) {
1003
966
  try {
1004
- // Closes only the review that was evaluated: a new alarm or reading since then keeps it open for that.
1005
967
  const { review: closed } = await closeEscalationReview({
1006
968
  id: String(review._id),
1007
969
  closedBy: AGENT_OPERATOR,
@@ -1026,7 +988,6 @@ async function settleFollowUp(snapshot, { background = true } = {}) {
1026
988
  if (!known.size) return review;
1027
989
 
1028
990
  const latest = new Map();
1029
- // Clinical order is the turn time, not the order the writes landed in.
1030
991
  (review.updates ?? []).filter((entry) => new Date(entry.at).getTime() > sinceMs)
1031
992
  .sort((a, b) => new Date(a.at) - new Date(b.at))
1032
993
  .forEach((entry) => (entry.impressions ?? [])
@@ -1036,22 +997,17 @@ async function settleFollowUp(snapshot, { background = true } = {}) {
1036
997
  if ([...latest.values()].includes('worsening')) return reopenFromFollowUp(review, 'worsening');
1037
998
  const settled = [...known].every((caseId) => SETTLED_TRAJECTORIES.includes(latest.get(caseId)));
1038
999
  if (!settled || review.status !== 'indications_sent') {
1039
- // Still waiting on readings: the news is flagged for whoever looks at the review.
1040
1000
  await getEscalationReview().updateOne({ _id: review._id }, { $set: { updatedSinceSeen: true } });
1041
1001
  return review;
1042
1002
  }
1043
- // The close writes the episode and syncs cases; the patient's reply does not wait on it.
1044
1003
  if (!background) return closeSettled(review);
1045
1004
  void closeSettled(review);
1046
1005
  return review;
1047
1006
  }
1048
1007
 
1049
- // Writes the draft the doctor will see without anyone asking for it. Answers whether a failed
1050
- // generation is worth retrying; a review that cannot take a draft is not.
1051
1008
  async function generateBotDraft({ id, lease = null } = {}) {
1052
1009
  const review = await loadReview(reviewIdOf(id));
1053
1010
  if (review.closedAt || !DOCUMENTING_STATUSES.includes(review.status)) return { review: null, retry: false };
1054
- // A draft the navigator wrote is theirs to replace; the bot never writes over it.
1055
1011
  const latest = (review.drafts ?? []).at(-1);
1056
1012
  if (latest && latest.writtenBy !== DRAFT_OPERATOR) return { review: null, retry: false };
1057
1013
 
@@ -1089,9 +1045,6 @@ async function generateBotDraft({ id, lease = null } = {}) {
1089
1045
  ...(draft.suggestCall && { suggestCall: draft.suggestCall }),
1090
1046
  ...(draft.sectionsUnavailable?.length && { sectionsUnavailable: draft.sectionsUnavailable }),
1091
1047
  };
1092
- // Every alarm or agent update re-arms draftDueAt, so a draft is only kept while draftDueAt still
1093
- // holds the sweep's lease: a draft that missed newer material is dropped, and the next sweep writes
1094
- // one that has it. A draft saved by hand meanwhile also wins.
1095
1048
  const saved = await getEscalationReview().findOneAndUpdate(
1096
1049
  { _id: review._id, status: { $in: DOCUMENTING_STATUSES }, draftDueAt: lease, drafts: { $size: (review.drafts ?? []).length } },
1097
1050
  { $push: { drafts: entry }, $set: { status: 'draft_ready', draftDueAt: null }, $unset: { identityBlock: '' } },
@@ -1245,8 +1198,6 @@ async function suggestKeyQuestions({ id, requestedBy, requestId = null } = {}) {
1245
1198
  const review = await loadReview(reviewId);
1246
1199
  if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
1247
1200
 
1248
- // The draft already asks what the agent left open; the separate generator is only the fallback
1249
- // for drafts written before the preset emitted key questions.
1250
1201
  const latest = (review.drafts ?? []).at(-1);
1251
1202
  if (latest?.keyQuestions?.length) {
1252
1203
  return {
@@ -1340,7 +1291,6 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
1340
1291
  reviewId,
1341
1292
  [review.status],
1342
1293
  { $set: { status: 'handing_off', operationClaim: claim } },
1343
- // updatedAt moves with every write, so an agent update filed since the read fails the claim.
1344
1294
  { drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length }, updatedAt: review.updatedAt },
1345
1295
  );
1346
1296
  let delivery = {};
@@ -1387,7 +1337,6 @@ async function recordDoctorDecision({
1387
1337
  if (!sources.includes(source)) throw httpError(400, `source must be one of: ${sources.join(', ')}`);
1388
1338
  if (!decisions.includes(decision)) throw httpError(400, `decision must be one of: ${decisions.join(', ')}`);
1389
1339
 
1390
- // Anyone on the team decides in the platform for now; the decision records who did.
1391
1340
  let decidedBy = operator;
1392
1341
  let reply = null;
1393
1342
  if (source === 'registered_by_navigator') {
@@ -1402,12 +1351,10 @@ async function recordDoctorDecision({
1402
1351
 
1403
1352
  const review = await loadReview(reviewId);
1404
1353
  if (!DECIDABLE_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
1405
- // A handed-off review is decided on the draft the doctor received; otherwise on the latest one.
1406
1354
  const handoff = review.status === 'awaiting_doctor' ? review.doctorHandoffs.at(-1) : null;
1407
1355
  const draftNumber = handoff?.draftNumber ?? review.drafts.length;
1408
1356
  const draft = review.drafts[draftNumber - 1];
1409
1357
  if (!draft) throw httpError(409, STATUS_CONFLICT);
1410
- // The caller says which draft it showed; a newer one written meanwhile was never read.
1411
1358
  if (seenDraftNumber !== null && Number(seenDraftNumber) !== draftNumber) throw httpError(409, DRAFT_CHANGED);
1412
1359
 
1413
1360
  let approvedText = null;
@@ -1417,8 +1364,6 @@ async function recordDoctorDecision({
1417
1364
  if (decision === 'needs_intervention' && finalText) approvedText = requiredText(finalText, 'finalText');
1418
1365
 
1419
1366
  if (APPROVALS.includes(decision) && arrivedAfter(review, draft.createdAt)) {
1420
- // A handed-off review cannot take a new draft where it is, so it goes back to be re-drafted:
1421
- // by the bot when the overtaken draft was its own, by a person otherwise.
1422
1367
  if (review.status === 'awaiting_doctor') {
1423
1368
  const redraft = draft.writtenBy === DRAFT_OPERATOR ? { draftDueAt: new Date(), draftAttempts: 0 } : {};
1424
1369
  const returned = await updateReview(reviewId, ['awaiting_doctor'], { $set: { status: 'documenting', ...redraft } }, {
@@ -1449,11 +1394,9 @@ async function recordDoctorDecision({
1449
1394
  recordedBy: operator,
1450
1395
  },
1451
1396
  },
1452
- // No requiere closes the case in the same write, so it can never be left returned and half done.
1453
1397
  $set: returnReason === 'no_requiere'
1454
1398
  ? { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: `no_requiere${comment ? `: ${comment}` : ''}` }
1455
1399
  : { status: statusAfter(decision) },
1456
- // Nothing new since the draft was checked against: an update landing meanwhile refuses the decision.
1457
1400
  }, { drafts: { $size: review.drafts.length }, alarms: { $size: (review.alarms ?? []).length }, ...latestUpdateGuard(review) });
1458
1401
  await audit(updated, operator, requestId, {
1459
1402
  action: 'doctor_decision', decision, source, draftNumber, ...(returnReason && { returnReason }),
@@ -1466,9 +1409,6 @@ async function recordDoctorDecision({
1466
1409
  return updated;
1467
1410
  }
1468
1411
 
1469
- // An approver writing to the patient in the chat delivers the indication themselves: the open
1470
- // review is resolved with what they wrote and moves to follow-up. Anyone else's message is not.
1471
- // The case selection a write was built from; a review from before the list holds a single case id.
1472
1412
  const casesAsRead = (review) => (Array.isArray(review.patientCaseRecordIds)
1473
1413
  ? { patientCaseRecordIds: review.patientCaseRecordIds }
1474
1414
  : { patientCaseRecordIds: { $exists: false }, patientCaseRecordId: review.patientCaseRecordId ?? null });
@@ -1487,10 +1427,8 @@ async function recordDirectIndication({ code, triggeredBy, body, messageId = nul
1487
1427
  if (!review) return null;
1488
1428
  if (!await getEscalationApprover(operator)) return null;
1489
1429
 
1490
- // The write names the cases it mirrors to; a selection changed in between is read again.
1491
1430
  for (let attempt = 1; review && attempt <= DIRECT_CHAT_ATTEMPTS; attempt += 1) {
1492
1431
  const decisionNumber = (review.decisions ?? []).length + 1;
1493
- // The doctor's own words become the cases' recommendation, as an approved send would.
1494
1432
  const updated = await EscalationReview.findOneAndUpdate(
1495
1433
  { _id: review._id, status: review.status, closedAt: null, ...casesAsRead(review) },
1496
1434
  withCaseMirror(review, {
@@ -1504,7 +1442,6 @@ async function recordDirectIndication({ code, triggeredBy, body, messageId = nul
1504
1442
  recordedBy: operator,
1505
1443
  },
1506
1444
  },
1507
- // A send still waiting on the 24 h window is queued for template recovery, exactly as an approved send.
1508
1445
  $set: {
1509
1446
  status: deferred ? 'indications_queued' : 'indications_sent',
1510
1447
  patientDelivery: {
@@ -1524,7 +1461,6 @@ async function recordDirectIndication({ code, triggeredBy, body, messageId = nul
1524
1461
  const { review: synced } = await syncCase(updated, operator, null);
1525
1462
  return synced;
1526
1463
  }
1527
- // Only the review this message was meant for: one opened since then never saw it.
1528
1464
  if (attempt < DIRECT_CHAT_ATTEMPTS) review = await openReview({ _id: review._id });
1529
1465
  }
1530
1466
  return null;
@@ -1536,7 +1472,6 @@ async function recordDirectIndication({ code, triggeredBy, body, messageId = nul
1536
1472
  }
1537
1473
  }
1538
1474
 
1539
- // The updates history is capped, so once full its length stays put; the guard names the newest update.
1540
1475
  const latestUpdateGuard = (review) => {
1541
1476
  const updates = review.updates ?? [];
1542
1477
  if (!updates.length) return { 'updates.0': { $exists: false } };
@@ -1548,8 +1483,6 @@ const arrivedAfter = (review, since) => Boolean(since) && [
1548
1483
  ...(review.updates ?? []).map((update) => update.at),
1549
1484
  ].some((at) => at && new Date(at) > new Date(since));
1550
1485
 
1551
- // The edited text may name a drug the draft never proposed. The doctor decides; the warning only
1552
- // leaves a trace of it next to the decision.
1553
1486
  const draftlessDrugWarnings = (text, draft) => {
1554
1487
  const drafted = new Set(drugsNamedIn(`${draft.doctorText} ${draft.patientMessage}`));
1555
1488
  return drugsNamedIn(text).filter((drug) => !drafted.has(drug)).map((drug) => `el texto editado menciona ${drug}, que no estaba en el borrador`);
@@ -1579,7 +1512,6 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
1579
1512
 
1580
1513
  const decidedAt = claimed.decisions[decisionNumber - 1].createdAt;
1581
1514
  if (decidedAt && (claimed.updates ?? []).some((entry) => new Date(entry.at) > new Date(decidedAt))) {
1582
- // Back to documenting: the decision is spent, and a new draft and decision have to follow.
1583
1515
  await releaseReview(reviewId, 'sending', 'documenting', claim).catch((releaseError) => {
1584
1516
  logger.error('[EscalationReview] The claim was not released after a decision new information overtook', {
1585
1517
  escalationReviewId: String(claimed._id), error: releaseError.message,
@@ -1639,8 +1571,6 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
1639
1571
  }, { recommendation: finalText });
1640
1572
  const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status);
1641
1573
  await audit(review, operator, requestId, { action: status, decisionNumber, transport: delivery.transport });
1642
- // Delivered indications move the review to follow-up; it closes once the patient's answer shows
1643
- // the symptom holding or improving, or by hand.
1644
1574
  return syncCase(review, operator, requestId);
1645
1575
  }
1646
1576
 
@@ -1759,7 +1689,6 @@ async function cancelEscalationReview({ id, cancelledBy, reason = null, requestI
1759
1689
 
1760
1690
  let review;
1761
1691
  try {
1762
- // Once the doctor has seen or decided the review, cancelling it needs a reason whatever its status.
1763
1692
  review = await updateReview(reviewId, allowed, {
1764
1693
  $set: { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: notes },
1765
1694
  }, notes ? {} : { 'doctorHandoffs.0': { $exists: false }, 'decisions.0': { $exists: false } });
@@ -8,14 +8,11 @@ const { BOOKKEEPING, PRE_DECISION_STATUSES, sendScheduledDoctorAlert } = require
8
8
  const SWEEP_LIMIT = 10;
9
9
  const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
10
10
  const LEASE_MS = 5 * 60 * 1000;
11
- // Well inside the lease: an alert never outlives its claim, so two sweeps never send the same one.
12
11
  const SEND_TIMEOUT_MS = 2 * 60 * 1000;
13
12
  const MAX_ALERT_ATTEMPTS = 3;
14
13
  const SELF_HEAL_WINDOW_MS = 60 * 60 * 1000;
15
14
  const ALERTED_URGENCIES = ['stat', 'asap'];
16
15
 
17
- // Due alerts, plus a recent stat/asap review still waiting on a decision that never got its first
18
- // alert because scheduling it failed after the alarm was written.
19
16
  const dueQuery = (now) => ({
20
17
  closedAt: null,
21
18
  $or: [
@@ -40,14 +37,12 @@ async function sweepDoctorAlerts({ now = new Date(), clock = () => new Date() }
40
37
  let sent = 0;
41
38
  for (const { _id: reviewId, doctorAlertDueAt = null, doctorAlertKind, doctorAlertAttempts = 0 } of due) {
42
39
  const kind = doctorAlertKind || 'initial';
43
- // Each claim starts its own clock: a slow alert earlier in the pass must not shorten the next lease.
44
40
  const claimedAt = clock();
45
41
  try {
46
42
  if (doctorAlertAttempts >= MAX_ALERT_ATTEMPTS) {
47
43
  logger.error('[ReviewAlertSweep] The doctor alert failed on every attempt; it is dropped', {
48
44
  escalationReviewId: String(reviewId), kind, attempts: doctorAlertAttempts,
49
45
  });
50
- // The drop is on the record, so the recovery of never-sent first alerts does not pick it up again.
51
46
  await EscalationReview.updateOne(
52
47
  { _id: reviewId, doctorAlertDueAt },
53
48
  {
@@ -58,8 +53,6 @@ async function sweepDoctorAlerts({ now = new Date(), clock = () => new Date() }
58
53
  );
59
54
  continue;
60
55
  }
61
- // Claiming turns the due time into a short lease: a pass that dies or throws leaves the alert
62
- // due again once it expires, and the sender only touches the schedule while the lease is its own.
63
56
  const lease = new Date(claimedAt.getTime() + LEASE_MS);
64
57
  const claimed = await EscalationReview
65
58
  .findOneAndUpdate(
@@ -5,18 +5,14 @@ const { getEscalationReview } = require('../models/escalationReviewModel');
5
5
 
6
6
  const { BOOKKEEPING, generateBotDraft } = require('./escalationReviewService');
7
7
 
8
- // One review per pass keeps a pass inside the sweeper's pass timeout, so shutdown always waits for it.
9
8
  const SWEEP_LIMIT = 1;
10
9
  const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
11
10
  const RETRY_DELAY_MS = 5 * 60 * 1000;
12
11
  const MAX_DRAFT_ATTEMPTS = 3;
13
12
  const LEASE_MS = 10 * 60 * 1000;
14
- // Well inside the lease: a run never outlives its claim, so two runs never draft the same review.
15
13
  const GENERATION_TIMEOUT_MS = 4 * 60 * 1000;
16
14
 
17
15
  async function draftReview(EscalationReview, { _id, draftDueAt, draftAttempts = 0 }, now) {
18
- // Claiming moves draftDueAt to a lease deadline: a worker that dies mid-draft leaves the review due
19
- // again once the lease expires, and an alarm or update that lands meanwhile replaces the lease.
20
16
  const lease = new Date(now.getTime() + LEASE_MS);
21
17
  const claimed = await EscalationReview
22
18
  .findOneAndUpdate({ _id, draftDueAt }, { $set: { draftDueAt: lease } }, { ...BOOKKEEPING, new: true, projection: { _id: 1 } })
@@ -38,7 +34,6 @@ async function draftReview(EscalationReview, { _id, draftDueAt, draftAttempts =
38
34
  escalationReviewId: String(_id), attempts: draftAttempts + 1,
39
35
  });
40
36
  }
41
- // Releases the lease, unless new material replaced it meanwhile.
42
37
  await EscalationReview.updateOne(
43
38
  { _id, draftDueAt: lease },
44
39
  willRetry
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.61.0-dev.11235",
3
+ "version": "5.61.0-dev.11237",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",