@peopl-health/nexus 5.61.0-dev.11236 → 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,12 +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
- // Only stat and asap alert the doctor; a review reopened by a milder alarm waits for the board.
888
863
  if (!ALERTED_URGENCIES.includes(urgencyLevel)) {
889
864
  await release();
890
865
  return null;
891
866
  }
892
- // The doctor already heard about this urgency (a recheck, or a retry whose record landed): nothing to send.
893
867
  if (kind === 'initial' && (URGENCY_RANK[urgencyLevel] || 0) <= alertedRankOf(review)) {
894
868
  await release();
895
869
  return null;
@@ -898,7 +872,6 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
898
872
  let delivery;
899
873
  try {
900
874
  const { approver, message } = await prepareDoctorAlert(review, kind, urgencyLevel);
901
- // Preparing takes lookups; a decision or close that landed meanwhile leaves nothing to alert about.
902
875
  const fresh = await loadReview(review._id);
903
876
  const stillDue = kind === 'realert'
904
877
  ? realertStillDue(fresh, initial)
@@ -931,8 +904,6 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
931
904
 
932
905
  const sent = { kind, urgencyLevel, transport: null, messageId: null, physicianEmail: null, error: null, ...delivery, teamAlerted, sentAt: now };
933
906
  const updated = await EscalationReview.findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
934
- // A failed stat alert still arms the re-alert, which also alerts the team. A failed asap alert has no
935
- // such backstop, so it is tried again; the sweep counts the attempts and drops it after the last.
936
907
  if (kind === 'initial' && urgencyLevel === 'stat') {
937
908
  await release({ doctorAlertDueAt: new Date(now.getTime() + statRealertMs()), doctorAlertKind: 'realert', doctorAlertAttempts: 0 });
938
909
  } else if (kind === 'initial' && sent.error) {
@@ -940,15 +911,12 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
940
911
  } else {
941
912
  await release();
942
913
  }
943
- // A more urgent alarm that landed while this alert was out could not take the lease. Read after the
944
- // release, so one landing later finds no lease and schedules itself.
945
914
  if (kind === 'initial' && urgencyLevel !== 'stat' && !sent.error) {
946
915
  try {
947
916
  const latest = await loadReview(review._id);
948
917
  const topNow = topUrgencyOf(latest);
949
918
  if (URGENCY_RANK[topNow] > (URGENCY_RANK[urgencyLevel] || 0)) await scheduleDoctorAlert(latest, { urgencyLevel: topNow }, new Date());
950
919
  } catch (error) {
951
- // Unread, so not known to be clear: the sweep checks again shortly, and a covered urgency sends nothing.
952
920
  logger.error('[EscalationReview] Could not check for a more urgent alarm after the alert', { escalationReviewId: String(review._id), error: redactedError(error) });
953
921
  await EscalationReview.updateOne(
954
922
  { _id: review._id, doctorAlertDueAt: null },
@@ -972,16 +940,11 @@ async function reopenFromFollowUp(review, reason) {
972
940
  return reopened;
973
941
  }
974
942
 
975
- // The agent's own trajectory for the cases of the review, read after the indication went out:
976
- // any of them worse sends the review back to the queue; all of them holding or better closes it.
977
- // A closed or resolved case is a settled one, whether or not the call carried a trajectory.
978
943
  const readingOf = (impression) => (['close', 'resolve_episode'].includes(impression.event) ? 'improving' : impression.trajectory);
979
944
 
980
945
  async function followUpCasesOf(review, sinceMs) {
981
946
  const decisionNumber = (review.decisions ?? []).length;
982
947
  if (review.followUpCases && review.followUpDecision === decisionNumber) return { review, known: new Set(review.followUpCases) };
983
- // Fixed once per indication, on its first follow-up reading, so later updates evicting old ones
984
- // cannot shrink it; a later indication keeps the cases already followed and adds the newer ones.
985
948
  const known = [...new Set([
986
949
  ...(review.followUpCases ?? []),
987
950
  ...(review.updates ?? [])
@@ -990,23 +953,17 @@ async function followUpCasesOf(review, sinceMs) {
990
953
  ])];
991
954
  const stored = await getEscalationReview()
992
955
  .findOneAndUpdate(
993
- // A decision added meanwhile starts its own follow-up; this one must not settle on its readings.
994
956
  { _id: review._id, followUpDecision: review.followUpDecision ?? null, decisions: { $size: decisionNumber } },
995
957
  { $set: { followUpCases: known, followUpDecision: decisionNumber } },
996
958
  { new: true },
997
959
  )
998
960
  .lean();
999
- // Lost to another writer: either a new decision, which starts its own follow-up, or a reply that
1000
- // already fixed this set and settles it.
1001
961
  if (!stored) return { review, known: new Set() };
1002
- // Settles on what the write returned: a reading that landed after the snapshot is in it, and its
1003
- // updatedAt is the one the close matches on.
1004
962
  return { review: stored, known: new Set(known) };
1005
963
  }
1006
964
 
1007
965
  async function closeSettled(review) {
1008
966
  try {
1009
- // Closes only the review that was evaluated: a new alarm or reading since then keeps it open for that.
1010
967
  const { review: closed } = await closeEscalationReview({
1011
968
  id: String(review._id),
1012
969
  closedBy: AGENT_OPERATOR,
@@ -1031,7 +988,6 @@ async function settleFollowUp(snapshot, { background = true } = {}) {
1031
988
  if (!known.size) return review;
1032
989
 
1033
990
  const latest = new Map();
1034
- // Clinical order is the turn time, not the order the writes landed in.
1035
991
  (review.updates ?? []).filter((entry) => new Date(entry.at).getTime() > sinceMs)
1036
992
  .sort((a, b) => new Date(a.at) - new Date(b.at))
1037
993
  .forEach((entry) => (entry.impressions ?? [])
@@ -1041,22 +997,17 @@ async function settleFollowUp(snapshot, { background = true } = {}) {
1041
997
  if ([...latest.values()].includes('worsening')) return reopenFromFollowUp(review, 'worsening');
1042
998
  const settled = [...known].every((caseId) => SETTLED_TRAJECTORIES.includes(latest.get(caseId)));
1043
999
  if (!settled || review.status !== 'indications_sent') {
1044
- // Still waiting on readings: the news is flagged for whoever looks at the review.
1045
1000
  await getEscalationReview().updateOne({ _id: review._id }, { $set: { updatedSinceSeen: true } });
1046
1001
  return review;
1047
1002
  }
1048
- // The close writes the episode and syncs cases; the patient's reply does not wait on it.
1049
1003
  if (!background) return closeSettled(review);
1050
1004
  void closeSettled(review);
1051
1005
  return review;
1052
1006
  }
1053
1007
 
1054
- // Writes the draft the doctor will see without anyone asking for it. Answers whether a failed
1055
- // generation is worth retrying; a review that cannot take a draft is not.
1056
1008
  async function generateBotDraft({ id, lease = null } = {}) {
1057
1009
  const review = await loadReview(reviewIdOf(id));
1058
1010
  if (review.closedAt || !DOCUMENTING_STATUSES.includes(review.status)) return { review: null, retry: false };
1059
- // A draft the navigator wrote is theirs to replace; the bot never writes over it.
1060
1011
  const latest = (review.drafts ?? []).at(-1);
1061
1012
  if (latest && latest.writtenBy !== DRAFT_OPERATOR) return { review: null, retry: false };
1062
1013
 
@@ -1094,9 +1045,6 @@ async function generateBotDraft({ id, lease = null } = {}) {
1094
1045
  ...(draft.suggestCall && { suggestCall: draft.suggestCall }),
1095
1046
  ...(draft.sectionsUnavailable?.length && { sectionsUnavailable: draft.sectionsUnavailable }),
1096
1047
  };
1097
- // Every alarm or agent update re-arms draftDueAt, so a draft is only kept while draftDueAt still
1098
- // holds the sweep's lease: a draft that missed newer material is dropped, and the next sweep writes
1099
- // one that has it. A draft saved by hand meanwhile also wins.
1100
1048
  const saved = await getEscalationReview().findOneAndUpdate(
1101
1049
  { _id: review._id, status: { $in: DOCUMENTING_STATUSES }, draftDueAt: lease, drafts: { $size: (review.drafts ?? []).length } },
1102
1050
  { $push: { drafts: entry }, $set: { status: 'draft_ready', draftDueAt: null }, $unset: { identityBlock: '' } },
@@ -1250,8 +1198,6 @@ async function suggestKeyQuestions({ id, requestedBy, requestId = null } = {}) {
1250
1198
  const review = await loadReview(reviewId);
1251
1199
  if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
1252
1200
 
1253
- // The draft already asks what the agent left open; the separate generator is only the fallback
1254
- // for drafts written before the preset emitted key questions.
1255
1201
  const latest = (review.drafts ?? []).at(-1);
1256
1202
  if (latest?.keyQuestions?.length) {
1257
1203
  return {
@@ -1345,7 +1291,6 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
1345
1291
  reviewId,
1346
1292
  [review.status],
1347
1293
  { $set: { status: 'handing_off', operationClaim: claim } },
1348
- // updatedAt moves with every write, so an agent update filed since the read fails the claim.
1349
1294
  { drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length }, updatedAt: review.updatedAt },
1350
1295
  );
1351
1296
  let delivery = {};
@@ -1392,7 +1337,6 @@ async function recordDoctorDecision({
1392
1337
  if (!sources.includes(source)) throw httpError(400, `source must be one of: ${sources.join(', ')}`);
1393
1338
  if (!decisions.includes(decision)) throw httpError(400, `decision must be one of: ${decisions.join(', ')}`);
1394
1339
 
1395
- // Anyone on the team decides in the platform for now; the decision records who did.
1396
1340
  let decidedBy = operator;
1397
1341
  let reply = null;
1398
1342
  if (source === 'registered_by_navigator') {
@@ -1407,12 +1351,10 @@ async function recordDoctorDecision({
1407
1351
 
1408
1352
  const review = await loadReview(reviewId);
1409
1353
  if (!DECIDABLE_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
1410
- // A handed-off review is decided on the draft the doctor received; otherwise on the latest one.
1411
1354
  const handoff = review.status === 'awaiting_doctor' ? review.doctorHandoffs.at(-1) : null;
1412
1355
  const draftNumber = handoff?.draftNumber ?? review.drafts.length;
1413
1356
  const draft = review.drafts[draftNumber - 1];
1414
1357
  if (!draft) throw httpError(409, STATUS_CONFLICT);
1415
- // The caller says which draft it showed; a newer one written meanwhile was never read.
1416
1358
  if (seenDraftNumber !== null && Number(seenDraftNumber) !== draftNumber) throw httpError(409, DRAFT_CHANGED);
1417
1359
 
1418
1360
  let approvedText = null;
@@ -1422,8 +1364,6 @@ async function recordDoctorDecision({
1422
1364
  if (decision === 'needs_intervention' && finalText) approvedText = requiredText(finalText, 'finalText');
1423
1365
 
1424
1366
  if (APPROVALS.includes(decision) && arrivedAfter(review, draft.createdAt)) {
1425
- // A handed-off review cannot take a new draft where it is, so it goes back to be re-drafted:
1426
- // by the bot when the overtaken draft was its own, by a person otherwise.
1427
1367
  if (review.status === 'awaiting_doctor') {
1428
1368
  const redraft = draft.writtenBy === DRAFT_OPERATOR ? { draftDueAt: new Date(), draftAttempts: 0 } : {};
1429
1369
  const returned = await updateReview(reviewId, ['awaiting_doctor'], { $set: { status: 'documenting', ...redraft } }, {
@@ -1454,11 +1394,9 @@ async function recordDoctorDecision({
1454
1394
  recordedBy: operator,
1455
1395
  },
1456
1396
  },
1457
- // No requiere closes the case in the same write, so it can never be left returned and half done.
1458
1397
  $set: returnReason === 'no_requiere'
1459
1398
  ? { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: `no_requiere${comment ? `: ${comment}` : ''}` }
1460
1399
  : { status: statusAfter(decision) },
1461
- // Nothing new since the draft was checked against: an update landing meanwhile refuses the decision.
1462
1400
  }, { drafts: { $size: review.drafts.length }, alarms: { $size: (review.alarms ?? []).length }, ...latestUpdateGuard(review) });
1463
1401
  await audit(updated, operator, requestId, {
1464
1402
  action: 'doctor_decision', decision, source, draftNumber, ...(returnReason && { returnReason }),
@@ -1471,9 +1409,6 @@ async function recordDoctorDecision({
1471
1409
  return updated;
1472
1410
  }
1473
1411
 
1474
- // An approver writing to the patient in the chat delivers the indication themselves: the open
1475
- // review is resolved with what they wrote and moves to follow-up. Anyone else's message is not.
1476
- // The case selection a write was built from; a review from before the list holds a single case id.
1477
1412
  const casesAsRead = (review) => (Array.isArray(review.patientCaseRecordIds)
1478
1413
  ? { patientCaseRecordIds: review.patientCaseRecordIds }
1479
1414
  : { patientCaseRecordIds: { $exists: false }, patientCaseRecordId: review.patientCaseRecordId ?? null });
@@ -1492,10 +1427,8 @@ async function recordDirectIndication({ code, triggeredBy, body, messageId = nul
1492
1427
  if (!review) return null;
1493
1428
  if (!await getEscalationApprover(operator)) return null;
1494
1429
 
1495
- // The write names the cases it mirrors to; a selection changed in between is read again.
1496
1430
  for (let attempt = 1; review && attempt <= DIRECT_CHAT_ATTEMPTS; attempt += 1) {
1497
1431
  const decisionNumber = (review.decisions ?? []).length + 1;
1498
- // The doctor's own words become the cases' recommendation, as an approved send would.
1499
1432
  const updated = await EscalationReview.findOneAndUpdate(
1500
1433
  { _id: review._id, status: review.status, closedAt: null, ...casesAsRead(review) },
1501
1434
  withCaseMirror(review, {
@@ -1509,7 +1442,6 @@ async function recordDirectIndication({ code, triggeredBy, body, messageId = nul
1509
1442
  recordedBy: operator,
1510
1443
  },
1511
1444
  },
1512
- // A send still waiting on the 24 h window is queued for template recovery, exactly as an approved send.
1513
1445
  $set: {
1514
1446
  status: deferred ? 'indications_queued' : 'indications_sent',
1515
1447
  patientDelivery: {
@@ -1529,7 +1461,6 @@ async function recordDirectIndication({ code, triggeredBy, body, messageId = nul
1529
1461
  const { review: synced } = await syncCase(updated, operator, null);
1530
1462
  return synced;
1531
1463
  }
1532
- // Only the review this message was meant for: one opened since then never saw it.
1533
1464
  if (attempt < DIRECT_CHAT_ATTEMPTS) review = await openReview({ _id: review._id });
1534
1465
  }
1535
1466
  return null;
@@ -1541,7 +1472,6 @@ async function recordDirectIndication({ code, triggeredBy, body, messageId = nul
1541
1472
  }
1542
1473
  }
1543
1474
 
1544
- // The updates history is capped, so once full its length stays put; the guard names the newest update.
1545
1475
  const latestUpdateGuard = (review) => {
1546
1476
  const updates = review.updates ?? [];
1547
1477
  if (!updates.length) return { 'updates.0': { $exists: false } };
@@ -1553,8 +1483,6 @@ const arrivedAfter = (review, since) => Boolean(since) && [
1553
1483
  ...(review.updates ?? []).map((update) => update.at),
1554
1484
  ].some((at) => at && new Date(at) > new Date(since));
1555
1485
 
1556
- // The edited text may name a drug the draft never proposed. The doctor decides; the warning only
1557
- // leaves a trace of it next to the decision.
1558
1486
  const draftlessDrugWarnings = (text, draft) => {
1559
1487
  const drafted = new Set(drugsNamedIn(`${draft.doctorText} ${draft.patientMessage}`));
1560
1488
  return drugsNamedIn(text).filter((drug) => !drafted.has(drug)).map((drug) => `el texto editado menciona ${drug}, que no estaba en el borrador`);
@@ -1584,7 +1512,6 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
1584
1512
 
1585
1513
  const decidedAt = claimed.decisions[decisionNumber - 1].createdAt;
1586
1514
  if (decidedAt && (claimed.updates ?? []).some((entry) => new Date(entry.at) > new Date(decidedAt))) {
1587
- // Back to documenting: the decision is spent, and a new draft and decision have to follow.
1588
1515
  await releaseReview(reviewId, 'sending', 'documenting', claim).catch((releaseError) => {
1589
1516
  logger.error('[EscalationReview] The claim was not released after a decision new information overtook', {
1590
1517
  escalationReviewId: String(claimed._id), error: releaseError.message,
@@ -1644,8 +1571,6 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
1644
1571
  }, { recommendation: finalText });
1645
1572
  const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status);
1646
1573
  await audit(review, operator, requestId, { action: status, decisionNumber, transport: delivery.transport });
1647
- // Delivered indications move the review to follow-up; it closes once the patient's answer shows
1648
- // the symptom holding or improving, or by hand.
1649
1574
  return syncCase(review, operator, requestId);
1650
1575
  }
1651
1576
 
@@ -1764,7 +1689,6 @@ async function cancelEscalationReview({ id, cancelledBy, reason = null, requestI
1764
1689
 
1765
1690
  let review;
1766
1691
  try {
1767
- // Once the doctor has seen or decided the review, cancelling it needs a reason whatever its status.
1768
1692
  review = await updateReview(reviewId, allowed, {
1769
1693
  $set: { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: notes },
1770
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.11236",
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",