@peopl-health/nexus 5.61.0-dev.11231 → 5.61.0-dev.11233

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,31 +14,59 @@ const {
14
14
  DOCTOR_DECISIONS,
15
15
  HANDOFF_MODES,
16
16
  INTERRUPTED_STATUSES,
17
+ RETURN_REASONS,
18
+ URGENCY_RANK,
17
19
  getEscalationReview,
18
20
  } = require('../models/escalationReviewModel');
21
+ const { getPatientAuditLog } = require('../models/patientAuditLogModel');
19
22
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
20
23
  const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
21
24
  const { sendMessage } = require('../core/NexusMessaging');
22
25
  const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
23
- const { writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
26
+ const { recordEmergency, writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
24
27
  const { renderDoctorMessage, templateSummary, withIdentity } = require('../clinical/helpers/doctorReviewMessageHelper');
25
28
  const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
29
+ const { drugsNamedIn } = require('../clinical/services/treatmentProposalService');
30
+ const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
26
31
  const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
27
32
  const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
28
33
 
29
34
  const { getPatientInformation, logPatientChange } = require('./patientService');
30
- const { getPatientTasks, openCaseIds, updatePatientTask } = require('./patientTaskService');
35
+ const { MAX_NOTE_LENGTH, getPatientTasks, openCaseIds, updatePatientTask } = require('./patientTaskService');
31
36
  const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
32
37
  const { switchThreadStoppedStatus } = require('./threadService');
33
38
 
34
39
  const AUDIT_SOURCE = 'escalation_review';
35
40
  const RECENT_REVIEW_LIMIT = 20;
41
+ const TIMELINE_LIMIT = 500;
42
+ const MAX_REVIEW_UPDATES = 50;
43
+ const DRAFT_DEBOUNCE_MS = 60 * 1000;
44
+ const DRAFT_OPERATOR = 'bot:escalationDraft';
45
+ const DIRECT_CHAT_ATTEMPTS = 3;
46
+ const RECHECK_DELAY_MS = 60 * 1000;
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
+ const BOOKKEEPING = { timestamps: false };
51
+ const PREVIOUS_REVIEW_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
36
52
  const DUPLICATE_KEY_ERROR = 11000;
37
53
  const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
38
54
  const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
39
55
  const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
40
56
  const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'needs_intervention'];
41
57
  const SENDABLE_STATUSES = ['approved', 'needs_intervention'];
58
+ const DECIDABLE_STATUSES = ['draft_ready', 'awaiting_doctor'];
59
+ const FOLLOWUP_STATUSES = ['indications_sent', 'indications_queued'];
60
+ const SETTLED_TRAJECTORIES = ['improving', 'stable'];
61
+ const ALERTED_URGENCIES = ['stat', 'asap'];
62
+ const DEFAULT_STAT_REALERT_MINUTES = 15;
63
+ const PRE_DECISION_STATUSES = ['open', 'documenting', 'draft_ready', 'handing_off', 'awaiting_doctor'];
64
+ const ALERT_OPERATOR = 'bot:escalationAlert';
65
+ const DIRECT_CHAT_STATUSES = ['open', 'documenting', 'draft_ready', 'returned', 'awaiting_doctor', 'approved', 'needs_intervention'];
66
+ const APPROVALS = ['approved', 'edited_approved'];
67
+ const STALE_DRAFT = 'New information reached the review after this draft; wait for the updated draft before approving';
68
+ const STALE_HANDOFF = 'New information reached the review after the draft the doctor received; it went back to documenting for a new draft';
69
+ const DRAFT_CHANGED = 'A newer draft was written after the one you saw; read it before deciding';
42
70
  const OUTSIDE_WINDOW_ROUTES = ['template_recovery', 'predefined_template'];
43
71
  const MAX_TEMPLATE_TEXT_LENGTH = 800;
44
72
  const STATUS_CONFLICT = 'The escalation review does not allow this action in its current status';
@@ -412,19 +440,83 @@ async function requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseR
412
440
  }
413
441
 
414
442
  const BOT_OPERATOR = 'bot:reportMedicalEscalation';
443
+ const AGENT_OPERATOR = 'bot:clinicalAgent';
444
+
445
+ async function previousReviewIdOf(EscalationReview, patientCode, now) {
446
+ try {
447
+ const previous = await EscalationReview
448
+ .findOne({ patientCode, closedAt: { $gte: new Date(now.getTime() - PREVIOUS_REVIEW_WINDOW_MS) } }, { _id: 1 })
449
+ .sort({ closedAt: -1 })
450
+ .lean();
451
+ return previous ? String(previous._id) : null;
452
+ } catch (error) {
453
+ logger.warn('[EscalationReview] The previous review lookup failed; opening the review unlinked', { error: redactedError(error) });
454
+ return null;
455
+ }
456
+ }
457
+
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
+ async function recordReviewUpdate({ code, update, now = new Date(), settleInBackground = true } = {}) {
461
+ if (!update) return null;
462
+ try {
463
+ const patientCode = patientCodeOf(code);
464
+ const EscalationReview = getEscalationReview();
465
+ const pushed = await EscalationReview.findOneAndUpdate(
466
+ { patientCode, closedAt: null },
467
+ {
468
+ $push: { updates: { $each: [update], $slice: -MAX_REVIEW_UPDATES } },
469
+ $set: { draftDueAt: new Date(now.getTime() + DRAFT_DEBOUNCE_MS), draftAttempts: 0 },
470
+ },
471
+ { new: true },
472
+ ).lean();
473
+ if (!pushed) return null;
474
+
475
+ if (FOLLOWUP_STATUSES.includes(pushed.status)) {
476
+ await audit(pushed, AGENT_OPERATOR, null, { action: 'case_updated', turnId: update.turnId, tools: update.tools });
477
+ return await settleFollowUp(pushed, { background: settleInBackground });
478
+ }
479
+
480
+ // The turn that opened the review seeds its draft, but it is not news to whoever opens it.
481
+ const openingTurn = pushed.alarms?.[0]?.turnId === update.turnId;
482
+ const updated = openingTurn ? pushed : (await EscalationReview
483
+ .findOneAndUpdate({ _id: pushed._id }, { $set: { updatedSinceSeen: true } }, { new: true })
484
+ .lean()) ?? pushed;
485
+ const requeued = updated.status === 'returned'
486
+ ? await EscalationReview
487
+ .findOneAndUpdate({ _id: updated._id, status: 'returned' }, { $set: { status: 'documenting' } }, { new: true })
488
+ .lean()
489
+ : null;
490
+ await audit(updated, AGENT_OPERATOR, null, {
491
+ action: 'case_updated',
492
+ turnId: update.turnId,
493
+ tools: update.tools,
494
+ ...(requeued && { statusFrom: 'returned', statusTo: 'documenting' }),
495
+ });
496
+ return requeued || updated;
497
+ } catch (error) {
498
+ logger.error('[EscalationReview] The agent update was not recorded against the review', {
499
+ error: redactedError(error), stack: redactedStack(error),
500
+ });
501
+ return null;
502
+ }
503
+ }
415
504
 
416
505
  async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
417
506
  try {
418
507
  const patientCode = patientCodeOf(code);
419
508
  const entry = { ...alarm, raisedAt: alarm?.raisedAt ?? now };
420
509
  const EscalationReview = getEscalationReview();
510
+ const draftDueAt = new Date(now.getTime() + DRAFT_DEBOUNCE_MS);
421
511
  const join = () => EscalationReview
422
- .findOneAndUpdate({ patientCode, closedAt: null }, { $push: { alarms: entry } }, { new: true })
512
+ .findOneAndUpdate({ patientCode, closedAt: null }, { $push: { alarms: entry }, $set: { draftDueAt, draftAttempts: 0 } }, { new: true })
423
513
  .lean();
424
514
 
425
515
  await ensureActiveReviewIndex(EscalationReview);
426
516
  const joined = await join();
427
517
  if (joined) {
518
+ await scheduleDoctorAlert(joined, entry, now);
519
+ if (FOLLOWUP_STATUSES.includes(joined.status)) return await reopenFromFollowUp(joined, 'new_alarm');
428
520
  if (!DOCUMENTING_STATUSES.includes(joined.status)) {
429
521
  logger.error('[EscalationReview] An alarm arrived after the doctor already had the case', {
430
522
  escalationReviewId: String(joined._id), status: joined.status, urgencyLevel: entry.urgencyLevel,
@@ -433,9 +525,16 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
433
525
  return joined;
434
526
  }
435
527
  try {
436
- return (await EscalationReview.create({
437
- patientCode, openedBy: BOT_OPERATOR, alarms: [entry], assistantPausedByReview: false,
528
+ const created = (await EscalationReview.create({
529
+ patientCode,
530
+ openedBy: BOT_OPERATOR,
531
+ alarms: [entry],
532
+ assistantPausedByReview: false,
533
+ previousReviewId: await previousReviewIdOf(EscalationReview, patientCode, now),
534
+ draftDueAt,
438
535
  })).toObject();
536
+ await scheduleDoctorAlert(created, entry, now);
537
+ return created;
439
538
  } catch (error) {
440
539
  if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
441
540
  return await join();
@@ -513,7 +612,50 @@ async function getEscalationReviewById({ id, requestedBy } = {}) {
513
612
  const reviewId = reviewIdOf(id);
514
613
  const operator = requiredText(requestedBy, 'requestedBy');
515
614
  const review = await loadReview(reviewId);
516
- return { review, isApprover: await isEscalationApprover(operator) };
615
+ // The view happened once the review was read, not when the mark is written after the approver lookup.
616
+ const readAt = new Date();
617
+ const isApprover = await isEscalationApprover(operator);
618
+ const EscalationReview = getEscalationReview();
619
+ const warnUnmarked = (error) => logger.warn('[EscalationReview] The review read was not marked', {
620
+ escalationReviewId: String(review._id), error: redactedError(error),
621
+ });
622
+ 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
+ await EscalationReview
626
+ .updateOne({ _id: review._id, updatedAt: review.updatedAt }, { $set: { updatedSinceSeen: false } }, { timestamps: false })
627
+ .catch(warnUnmarked);
628
+ }
629
+ if (isApprover) {
630
+ await EscalationReview
631
+ // $max: a slow read finishing late never moves the last view back.
632
+ .updateOne({ _id: review._id }, { $max: { approverViewedAt: readAt } }, { timestamps: false })
633
+ .catch(warnUnmarked);
634
+ }
635
+ return { review, isApprover };
636
+ }
637
+
638
+ async function getReviewTimeline({ id } = {}) {
639
+ const review = await loadReview(reviewIdOf(id));
640
+ // Newest first, so a busy review keeps its latest steps under the limit.
641
+ const rows = await getPatientAuditLog()
642
+ .find({ code: review.patientCode, source: AUDIT_SOURCE, 'changes.escalationReviewId': String(review._id) })
643
+ .sort({ createdAt: -1 })
644
+ .limit(TIMELINE_LIMIT)
645
+ .lean();
646
+ const alarms = (review.alarms ?? []).map((alarm) => ({
647
+ at: alarm.raisedAt,
648
+ action: 'alarm',
649
+ by: BOT_OPERATOR,
650
+ details: { urgencyLevel: alarm.urgencyLevel, symptom: alarm.symptom ?? null },
651
+ }));
652
+ const steps = rows.map(({ createdAt, updatedBy, changes }) => {
653
+ const details = { ...changes };
654
+ delete details.escalationReviewId;
655
+ delete details.action;
656
+ return { at: createdAt, action: changes?.action ?? null, by: updatedBy, details };
657
+ });
658
+ return [...alarms, ...steps].sort((a, b) => new Date(a.at) - new Date(b.at)).slice(-TIMELINE_LIMIT);
517
659
  }
518
660
 
519
661
  async function listEscalationReviews({ code } = {}) {
@@ -521,18 +663,22 @@ async function listEscalationReviews({ code } = {}) {
521
663
  return getEscalationReview().find({ patientCode }).sort({ createdAt: -1 }).limit(RECENT_REVIEW_LIMIT).lean();
522
664
  }
523
665
 
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
+ const redraftAfterCall = () => ({ draftDueAt: new Date(Date.now() + DRAFT_DEBOUNCE_MS), draftAttempts: 0 });
669
+
524
670
  async function appendKeepingDraft(id, entry) {
525
671
  const EscalationReview = getEscalationReview();
526
672
  for (let attempt = 0; attempt < 2; attempt += 1) {
527
673
  const kept = await EscalationReview
528
- .findOneAndUpdate({ _id: id, status: 'draft_ready' }, { $push: { callLogs: entry } }, { new: true })
674
+ .findOneAndUpdate({ _id: id, status: 'draft_ready' }, { $push: { callLogs: entry }, $set: redraftAfterCall() }, { new: true })
529
675
  .lean();
530
676
  if (kept) return kept;
531
677
 
532
678
  const moved = await EscalationReview
533
679
  .findOneAndUpdate(
534
680
  { _id: id, status: { $in: UNDRAFTED_STATUSES } },
535
- { $push: { callLogs: entry }, $set: { status: 'documenting' } },
681
+ { $push: { callLogs: entry }, $set: { status: 'documenting', ...redraftAfterCall() } },
536
682
  { new: true },
537
683
  )
538
684
  .lean();
@@ -600,7 +746,7 @@ async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy
600
746
 
601
747
  const entry = { outcome, notes: optionalText(notes), calledAt: callTime, loggedBy: operator };
602
748
  const review = outcome === 'contacted'
603
- ? await updateReview(reviewId, DOCUMENTING_STATUSES, { $push: { callLogs: entry }, $set: { status: 'documenting' } })
749
+ ? await updateReview(reviewId, DOCUMENTING_STATUSES, { $push: { callLogs: entry }, $set: { status: 'documenting', ...redraftAfterCall() } })
604
750
  : await appendKeepingDraft(reviewId, entry);
605
751
  await audit(review, operator, requestId, { action: 'call_logged', outcome });
606
752
  if (outcome !== 'contacted') return review;
@@ -650,6 +796,299 @@ async function suggestDraft({ id, requestedBy, requestId = null } = {}) {
650
796
  return { ...draft, doctorText: withIdentity({ identity, review, doctorText: draft.doctorText }) };
651
797
  }
652
798
 
799
+ // The most urgent level the doctor was actually alerted about; a failed attempt told them nothing.
800
+ // Scheduling and sending gate on the same one.
801
+ const alertedRankOf = (review) => Math.max(0, ...(review.doctorAlerts ?? [])
802
+ .filter((sent) => sent.kind === 'initial' && !sent.error)
803
+ .map((sent) => URGENCY_RANK[sent.urgencyLevel] || 0));
804
+
805
+ // A stat or asap alarm more urgent than anything the doctor was already told about is due now.
806
+ async function scheduleDoctorAlert(review, alarm, now) {
807
+ try {
808
+ if (!ALERTED_URGENCIES.includes(alarm?.urgencyLevel)) return;
809
+ if (URGENCY_RANK[alarm.urgencyLevel] <= alertedRankOf(review)) return;
810
+ // An initial alert in flight holds its lease; its sender schedules this urgency once it is done.
811
+ const scheduled = await getEscalationReview().updateOne(
812
+ { _id: review._id, $nor: [{ doctorAlertKind: 'initial', doctorAlertDueAt: { $gt: now } }] },
813
+ { $set: { doctorAlertDueAt: now, doctorAlertKind: 'initial', doctorAlertAttempts: 0 } },
814
+ BOOKKEEPING,
815
+ );
816
+ if (scheduled.matchedCount) Object.assign(review, { doctorAlertDueAt: now, doctorAlertKind: 'initial' });
817
+ } catch (error) {
818
+ logger.error('[EscalationReview] The doctor alert was not scheduled', { escalationReviewId: String(review?._id), error: redactedError(error) });
819
+ }
820
+ }
821
+
822
+ const statRealertMs = () => {
823
+ const minutes = Number(runtimeConfig.get('ESCALATION_REVIEW_STAT_REALERT_MINUTES', DEFAULT_STAT_REALERT_MINUTES));
824
+ return (Number.isFinite(minutes) && minutes > 0 ? minutes : DEFAULT_STAT_REALERT_MINUTES) * 60 * 1000;
825
+ };
826
+
827
+ // The doctor answered once they opened the review or anything was decided after the alert.
828
+ function answeredSince(review, since) {
829
+ const sinceMs = new Date(since).getTime();
830
+ if (!PRE_DECISION_STATUSES.includes(review.status)) return true;
831
+ if (review.approverViewedAt && new Date(review.approverViewedAt).getTime() >= sinceMs) return true;
832
+ return (review.decisions ?? []).some((decision) => decision.createdAt && new Date(decision.createdAt).getTime() >= sinceMs);
833
+ }
834
+
835
+ async function prepareDoctorAlert(review, kind, urgencyLevel) {
836
+ const identity = await readDoctorIdentity(review);
837
+ if (identity.missing.length) throw new Error(`missing ${identity.missing.join(' and ')}`);
838
+ const approver = await soleApprover();
839
+ const link = doctorLink(review);
840
+ const label = urgencyLevel === 'stat' ? 'STAT' : 'ASAP';
841
+ const lead = kind === 'realert' ? `Sigue pendiente · revisión clínica ${label}` : `Revisión clínica ${label}`;
842
+ const message = {
843
+ body: `${lead}: ${identity.patientName} (médico tratante: ${identity.treatingDoctor}). ${templateSummary(review)}.\n${link}`,
844
+ template: { 1: identity.patientName, 2: identity.treatingDoctor, 3: templateSummary(review), 4: link },
845
+ };
846
+ return { approver, message };
847
+ }
848
+
849
+ const topUrgencyOf = (review) => (review.alarms ?? [])
850
+ .reduce((top, alarm) => (URGENCY_RANK[alarm.urgencyLevel] > (URGENCY_RANK[top] || 0) ? alarm.urgencyLevel : top), null);
851
+
852
+ const realertStillDue = (review, initial) => !review.closedAt && Boolean(initial) && !answeredSince(review, initial.sentAt);
853
+
854
+ // Sends the alert the sweep claimed under `lease`. A stat alert arms the re-alert; the re-alert goes
855
+ // out only if the doctor has not answered, checked again right before sending, and also files a new
856
+ // emergency row so the team is alerted. The schedule is only touched while the lease is still ours.
857
+ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date() } = {}) {
858
+ const EscalationReview = getEscalationReview();
859
+ const ours = lease ? { doctorAlertDueAt: lease } : {};
860
+ const release = (set = { doctorAlertDueAt: null, doctorAlertKind: null, doctorAlertAttempts: 0 }) => EscalationReview
861
+ .updateOne({ _id: id, ...ours }, { $set: set }, BOOKKEEPING);
862
+
863
+ const review = await loadReview(reviewIdOf(id));
864
+ // Once anything was decided, the doctor has nothing left to be alerted about.
865
+ if (review.closedAt || !PRE_DECISION_STATUSES.includes(review.status)) {
866
+ await release();
867
+ return null;
868
+ }
869
+ const initial = (review.doctorAlerts ?? []).filter((sent) => sent.kind === 'initial').at(-1);
870
+ if (kind === 'realert' && !realertStillDue(review, initial)) {
871
+ await release();
872
+ return null;
873
+ }
874
+ const urgencyLevel = kind === 'realert' ? initial.urgencyLevel : topUrgencyOf(review);
875
+ // The doctor already heard about this urgency (a recheck, or a retry whose record landed): nothing to send.
876
+ if (kind === 'initial' && (URGENCY_RANK[urgencyLevel] || 0) <= alertedRankOf(review)) {
877
+ await release();
878
+ return null;
879
+ }
880
+
881
+ let delivery;
882
+ try {
883
+ const { approver, message } = await prepareDoctorAlert(review, kind, urgencyLevel);
884
+ // Preparing takes lookups; a decision or close that landed meanwhile leaves nothing to alert about.
885
+ const fresh = await loadReview(review._id);
886
+ const stillDue = kind === 'realert'
887
+ ? realertStillDue(fresh, initial)
888
+ : !fresh.closedAt && PRE_DECISION_STATUSES.includes(fresh.status);
889
+ if (!stillDue) {
890
+ await release();
891
+ return null;
892
+ }
893
+ delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator: ALERT_OPERATOR })) };
894
+ } catch (error) {
895
+ delivery = { error: redactedError(error) };
896
+ logger.error('[EscalationReview] The doctor alert was not sent', { escalationReviewId: String(review._id), kind, error: delivery.error });
897
+ }
898
+
899
+ let teamAlerted = false;
900
+ if (kind === 'realert') {
901
+ const lead = review.alarms?.findLast((alarm) => alarm.urgencyLevel === 'stat') ?? review.alarms?.at(-1);
902
+ teamAlerted = Boolean(await recordEmergency({
903
+ code: review.patientCode,
904
+ trace: null,
905
+ symptom: lead?.symptom || 'Revisión clínica STAT',
906
+ urgencyFhir: 'stat',
907
+ documentation: `Re-aviso: revisión clínica STAT sin respuesta del médico ${Math.round(statRealertMs() / 60000)} min después del aviso.`,
908
+ mergeWithRecent: false,
909
+ }).catch((error) => {
910
+ logger.error('[EscalationReview] The team alert for an unanswered stat review was not filed', { escalationReviewId: String(review._id), error: redactedError(error) });
911
+ return false;
912
+ }));
913
+ }
914
+
915
+ const sent = { kind, urgencyLevel, transport: null, messageId: null, physicianEmail: null, error: null, ...delivery, teamAlerted, sentAt: now };
916
+ const updated = await EscalationReview.findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
917
+ // A failed stat alert still arms the re-alert, which also alerts the team. A failed asap alert has no
918
+ // such backstop, so it is tried again; the sweep counts the attempts and drops it after the last.
919
+ if (kind === 'initial' && urgencyLevel === 'stat') {
920
+ await release({ doctorAlertDueAt: new Date(now.getTime() + statRealertMs()), doctorAlertKind: 'realert', doctorAlertAttempts: 0 });
921
+ } else if (kind === 'initial' && sent.error) {
922
+ await release({ doctorAlertDueAt: new Date(Date.now() + ALERT_RETRY_DELAY_MS), doctorAlertKind: 'initial' });
923
+ } else {
924
+ await release();
925
+ }
926
+ // A more urgent alarm that landed while this alert was out could not take the lease. Read after the
927
+ // release, so one landing later finds no lease and schedules itself.
928
+ if (kind === 'initial' && urgencyLevel !== 'stat' && !sent.error) {
929
+ try {
930
+ const latest = await loadReview(review._id);
931
+ const topNow = topUrgencyOf(latest);
932
+ if (URGENCY_RANK[topNow] > (URGENCY_RANK[urgencyLevel] || 0)) await scheduleDoctorAlert(latest, { urgencyLevel: topNow }, new Date());
933
+ } catch (error) {
934
+ // Unread, so not known to be clear: the sweep checks again shortly, and a covered urgency sends nothing.
935
+ logger.error('[EscalationReview] Could not check for a more urgent alarm after the alert', { escalationReviewId: String(review._id), error: redactedError(error) });
936
+ await EscalationReview.updateOne(
937
+ { _id: review._id, doctorAlertDueAt: null },
938
+ { $set: { doctorAlertDueAt: new Date(Date.now() + RECHECK_DELAY_MS), doctorAlertKind: 'initial', doctorAlertAttempts: 0 } },
939
+ BOOKKEEPING,
940
+ ).catch(() => {});
941
+ }
942
+ }
943
+ await audit(updated ?? review, ALERT_OPERATOR, null, {
944
+ action: kind === 'realert' ? 'doctor_realerted' : 'doctor_alerted', urgencyLevel, delivered: !sent.error, teamAlerted,
945
+ });
946
+ return updated;
947
+ }
948
+
949
+ async function reopenFromFollowUp(review, reason) {
950
+ const reopened = await getEscalationReview()
951
+ .findOneAndUpdate({ _id: review._id, status: review.status }, { $set: { status: 'documenting', updatedSinceSeen: true } }, { new: true })
952
+ .lean();
953
+ if (!reopened) return review;
954
+ await audit(reopened, AGENT_OPERATOR, null, { action: 'followup_result', result: reason, statusFrom: review.status });
955
+ return reopened;
956
+ }
957
+
958
+ // The agent's own trajectory for the cases of the review, read after the indication went out:
959
+ // any of them worse sends the review back to the queue; all of them holding or better closes it.
960
+ // A closed or resolved case is a settled one, whether or not the call carried a trajectory.
961
+ const readingOf = (impression) => (['close', 'resolve_episode'].includes(impression.event) ? 'improving' : impression.trajectory);
962
+
963
+ async function followUpCasesOf(review, sinceMs) {
964
+ const decisionNumber = (review.decisions ?? []).length;
965
+ if (review.followUpCases && review.followUpDecision === decisionNumber) return { review, known: new Set(review.followUpCases) };
966
+ // Fixed once per indication, on its first follow-up reading, so later updates evicting old ones
967
+ // cannot shrink it; a later indication keeps the cases already followed and adds the newer ones.
968
+ const known = [...new Set([
969
+ ...(review.followUpCases ?? []),
970
+ ...(review.updates ?? [])
971
+ .filter((entry) => new Date(entry.at).getTime() <= sinceMs)
972
+ .flatMap((entry) => (entry.impressions ?? []).map((impression) => impression.caseId).filter(Boolean)),
973
+ ])];
974
+ const stored = await getEscalationReview()
975
+ .findOneAndUpdate(
976
+ // A decision added meanwhile starts its own follow-up; this one must not settle on its readings.
977
+ { _id: review._id, followUpDecision: review.followUpDecision ?? null, decisions: { $size: decisionNumber } },
978
+ { $set: { followUpCases: known, followUpDecision: decisionNumber } },
979
+ { new: true },
980
+ )
981
+ .lean();
982
+ // Lost to another writer: either a new decision, which starts its own follow-up, or a reply that
983
+ // already fixed this set and settles it.
984
+ if (!stored) return { review, known: new Set() };
985
+ // Settles on what the write returned: a reading that landed after the snapshot is in it, and its
986
+ // updatedAt is the one the close matches on.
987
+ return { review: stored, known: new Set(known) };
988
+ }
989
+
990
+ async function closeSettled(review) {
991
+ try {
992
+ // Closes only the review that was evaluated: a new alarm or reading since then keeps it open for that.
993
+ const { review: closed } = await closeEscalationReview({
994
+ id: String(review._id),
995
+ closedBy: AGENT_OPERATOR,
996
+ expectedAlarmCount: (review.alarms ?? []).length,
997
+ expectedUpdatedAt: review.updatedAt,
998
+ });
999
+ await audit(closed, AGENT_OPERATOR, null, { action: 'followup_result', result: 'settled' });
1000
+ return closed;
1001
+ } catch (error) {
1002
+ logger.warn('[EscalationReview] The follow-up settled the case but the review did not close', {
1003
+ escalationReviewId: String(review._id), error: redactedError(error),
1004
+ });
1005
+ return review;
1006
+ }
1007
+ }
1008
+
1009
+ async function settleFollowUp(snapshot, { background = true } = {}) {
1010
+ const since = (snapshot.decisions ?? []).at(-1)?.createdAt;
1011
+ if (!since) return snapshot;
1012
+ const sinceMs = new Date(since).getTime();
1013
+ const { review, known } = await followUpCasesOf(snapshot, sinceMs);
1014
+ if (!known.size) return review;
1015
+
1016
+ const latest = new Map();
1017
+ // Clinical order is the turn time, not the order the writes landed in.
1018
+ (review.updates ?? []).filter((entry) => new Date(entry.at).getTime() > sinceMs)
1019
+ .sort((a, b) => new Date(a.at) - new Date(b.at))
1020
+ .forEach((entry) => (entry.impressions ?? [])
1021
+ .filter((impression) => known.has(impression.caseId) && readingOf(impression))
1022
+ .forEach((impression) => latest.set(impression.caseId, readingOf(impression))));
1023
+
1024
+ if ([...latest.values()].includes('worsening')) return reopenFromFollowUp(review, 'worsening');
1025
+ const settled = [...known].every((caseId) => SETTLED_TRAJECTORIES.includes(latest.get(caseId)));
1026
+ if (!settled || review.status !== 'indications_sent') {
1027
+ // Still waiting on readings: the news is flagged for whoever looks at the review.
1028
+ await getEscalationReview().updateOne({ _id: review._id }, { $set: { updatedSinceSeen: true } });
1029
+ return review;
1030
+ }
1031
+ // The close writes the episode and syncs cases; the patient's reply does not wait on it.
1032
+ if (!background) return closeSettled(review);
1033
+ void closeSettled(review);
1034
+ return review;
1035
+ }
1036
+
1037
+ // Writes the draft the doctor will see without anyone asking for it. Answers whether a failed
1038
+ // generation is worth retrying; a review that cannot take a draft is not.
1039
+ async function generateBotDraft({ id, lease = null } = {}) {
1040
+ const review = await loadReview(reviewIdOf(id));
1041
+ if (review.closedAt || !DOCUMENTING_STATUSES.includes(review.status)) return { review: null, retry: false };
1042
+ // A draft the navigator wrote is theirs to replace; the bot never writes over it.
1043
+ const latest = (review.drafts ?? []).at(-1);
1044
+ if (latest && latest.writtenBy !== DRAFT_OPERATOR) return { review: null, retry: false };
1045
+
1046
+ const identity = await readDoctorIdentity(review);
1047
+ if (identity.missing.length) {
1048
+ if (!review.identityBlock) await blockForMissingIdentity({ review, missing: identity.missing, operator: DRAFT_OPERATOR });
1049
+ return { review: null, retry: false };
1050
+ }
1051
+
1052
+ const draft = await generateEscalationDraft({
1053
+ code: review.patientCode,
1054
+ callLogs: review.callLogs ?? [],
1055
+ alarms: review.alarms ?? [],
1056
+ agentCharacterization: characterizationSeedOf(review.updates),
1057
+ reviewId: String(review._id),
1058
+ });
1059
+ if (draft.attempted) {
1060
+ await audit(review, DRAFT_OPERATOR, null, draft.completed
1061
+ ? { action: 'draft_generated', protocolVersion: draft.protocolVersion }
1062
+ : { action: 'draft_generation_failed', reason: redactedError({ message: draft.reason }) });
1063
+ }
1064
+ if (!draft.completed) {
1065
+ logger.warn('[EscalationReview] The automatic draft was not written', { escalationReviewId: String(review._id), reason: draft.reason });
1066
+ return { review: null, retry: draft.configured !== false };
1067
+ }
1068
+
1069
+ const entry = {
1070
+ doctorText: withIdentity({ identity, review, doctorText: draft.doctorText }),
1071
+ patientMessage: draft.patientMessage,
1072
+ writtenBy: DRAFT_OPERATOR,
1073
+ protocolVersion: draft.protocolVersion,
1074
+ keyQuestions: draft.keyQuestions,
1075
+ unassessedRedFlags: draft.unassessedRedFlags,
1076
+ missingCharacterization: draft.missingCharacterization,
1077
+ ...(draft.suggestCall && { suggestCall: draft.suggestCall }),
1078
+ ...(draft.sectionsUnavailable?.length && { sectionsUnavailable: draft.sectionsUnavailable }),
1079
+ };
1080
+ // Every alarm or agent update re-arms draftDueAt, so a draft is only kept while draftDueAt still
1081
+ // holds the sweep's lease: a draft that missed newer material is dropped, and the next sweep writes
1082
+ // one that has it. A draft saved by hand meanwhile also wins.
1083
+ const saved = await getEscalationReview().findOneAndUpdate(
1084
+ { _id: review._id, status: { $in: DOCUMENTING_STATUSES }, draftDueAt: lease, drafts: { $size: (review.drafts ?? []).length } },
1085
+ { $push: { drafts: entry }, $set: { status: 'draft_ready', draftDueAt: null }, $unset: { identityBlock: '' } },
1086
+ { new: true },
1087
+ ).lean();
1088
+ if (saved) await audit(saved, DRAFT_OPERATOR, null, { action: 'draft_saved', draftNumber: saved.drafts.length });
1089
+ return { review: saved, retry: false };
1090
+ }
1091
+
653
1092
  async function noteFactsContext(review) {
654
1093
  try {
655
1094
  return await readContextFacts({ patientId: review.patientCode });
@@ -794,6 +1233,20 @@ async function suggestKeyQuestions({ id, requestedBy, requestId = null } = {}) {
794
1233
  const review = await loadReview(reviewId);
795
1234
  if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
796
1235
 
1236
+ // The draft already asks what the agent left open; the separate generator is only the fallback
1237
+ // for drafts written before the preset emitted key questions.
1238
+ const latest = (review.drafts ?? []).at(-1);
1239
+ if (latest?.keyQuestions?.length) {
1240
+ return {
1241
+ completed: true,
1242
+ source: 'draft',
1243
+ questions: latest.keyQuestions,
1244
+ redFlags: latest.unassessedRedFlags ?? [],
1245
+ missingCharacterization: latest.missingCharacterization ?? [],
1246
+ suggestCall: latest.suggestCall ?? null,
1247
+ };
1248
+ }
1249
+
797
1250
  const generated = await generateKeyQuestions({
798
1251
  code: review.patientCode,
799
1252
  callLogs: review.callLogs ?? [],
@@ -857,6 +1310,9 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
857
1310
  if (draftedAt && (review.alarms ?? []).some((alarm) => new Date(alarm.raisedAt).getTime() > draftedAt)) {
858
1311
  throw httpError(409, 'A new alarm arrived after this draft was written; review it and save a new draft before sending it to the doctor');
859
1312
  }
1313
+ if (draftedAt && (review.updates ?? []).some((entry) => new Date(entry.at).getTime() > draftedAt)) {
1314
+ throw httpError(409, 'The agent characterized the case after this draft was written; review it and save a new draft before sending it to the doctor');
1315
+ }
860
1316
  const identity = await readDoctorIdentity(review);
861
1317
  if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
862
1318
  const link = doctorLink(review);
@@ -872,7 +1328,8 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
872
1328
  reviewId,
873
1329
  [review.status],
874
1330
  { $set: { status: 'handing_off', operationClaim: claim } },
875
- { drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length } },
1331
+ // updatedAt moves with every write, so an agent update filed since the read fails the claim.
1332
+ { drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length }, updatedAt: review.updatedAt },
876
1333
  );
877
1334
  let delivery = {};
878
1335
  let updated;
@@ -906,35 +1363,66 @@ async function recordDoctorDecision({
906
1363
  comment = null,
907
1364
  doctorName = null,
908
1365
  doctorReply = null,
1366
+ reason = null,
1367
+ draftNumber: seenDraftNumber = null,
909
1368
  recordedBy,
910
1369
  requestId = null,
911
1370
  } = {}) {
912
1371
  const reviewId = reviewIdOf(id);
913
1372
  const operator = requiredText(recordedBy, 'recordedBy');
914
- if (!DECISION_SOURCES.includes(source)) throw httpError(400, `source must be one of: ${DECISION_SOURCES.join(', ')}`);
915
- if (!DOCTOR_DECISIONS.includes(decision)) throw httpError(400, `decision must be one of: ${DOCTOR_DECISIONS.join(', ')}`);
1373
+ const sources = DECISION_SOURCES.filter((entry) => entry !== 'chat');
1374
+ const decisions = DOCTOR_DECISIONS.filter((entry) => entry !== 'direct_chat');
1375
+ if (!sources.includes(source)) throw httpError(400, `source must be one of: ${sources.join(', ')}`);
1376
+ if (!decisions.includes(decision)) throw httpError(400, `decision must be one of: ${decisions.join(', ')}`);
916
1377
 
1378
+ // Anyone on the team decides in the platform for now; the decision records who did.
917
1379
  let decidedBy = operator;
918
1380
  let reply = null;
919
- if (source === 'platform') {
920
- const approver = await getEscalationApprover(operator);
921
- if (!approver) throw httpError(403, 'Only an escalation review approver can decide in the platform');
922
- } else {
1381
+ if (source === 'registered_by_navigator') {
923
1382
  decidedBy = requiredText(doctorName, 'doctorName');
924
1383
  reply = requiredText(doctorReply, 'doctorReply');
925
1384
  }
1385
+ let returnReason = null;
1386
+ if (decision === 'returned') {
1387
+ if (!RETURN_REASONS.includes(reason)) throw httpError(400, `reason must be one of: ${RETURN_REASONS.join(', ')}`);
1388
+ returnReason = reason;
1389
+ }
926
1390
 
927
1391
  const review = await loadReview(reviewId);
928
- if (review.status !== 'awaiting_doctor') throw httpError(409, STATUS_CONFLICT);
929
- const { draftNumber } = review.doctorHandoffs[review.doctorHandoffs.length - 1];
1392
+ if (!DECIDABLE_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
1393
+ // A handed-off review is decided on the draft the doctor received; otherwise on the latest one.
1394
+ const handoff = review.status === 'awaiting_doctor' ? review.doctorHandoffs.at(-1) : null;
1395
+ const draftNumber = handoff?.draftNumber ?? review.drafts.length;
930
1396
  const draft = review.drafts[draftNumber - 1];
1397
+ if (!draft) throw httpError(409, STATUS_CONFLICT);
1398
+ // The caller says which draft it showed; a newer one written meanwhile was never read.
1399
+ if (seenDraftNumber !== null && Number(seenDraftNumber) !== draftNumber) throw httpError(409, DRAFT_CHANGED);
1400
+
931
1401
  let approvedText = null;
932
1402
  if (decision === 'approved') approvedText = draft.patientMessage;
933
1403
  if (decision === 'edited_approved') approvedText = requiredText(finalText, 'finalText');
934
1404
  // Truthiness, not != null: an empty textarea is a decline with nothing to say.
935
1405
  if (decision === 'needs_intervention' && finalText) approvedText = requiredText(finalText, 'finalText');
936
1406
 
937
- const updated = await updateReview(reviewId, ['awaiting_doctor'], {
1407
+ if (APPROVALS.includes(decision) && arrivedAfter(review, draft.createdAt)) {
1408
+ // A handed-off review cannot take a new draft where it is, so it goes back to be re-drafted:
1409
+ // by the bot when the overtaken draft was its own, by a person otherwise.
1410
+ if (review.status === 'awaiting_doctor') {
1411
+ const redraft = draft.writtenBy === DRAFT_OPERATOR ? { draftDueAt: new Date(), draftAttempts: 0 } : {};
1412
+ const returned = await updateReview(reviewId, ['awaiting_doctor'], { $set: { status: 'documenting', ...redraft } }, {
1413
+ doctorHandoffs: { $size: review.doctorHandoffs.length },
1414
+ drafts: { $size: review.drafts.length },
1415
+ });
1416
+ await audit(returned, operator, requestId, {
1417
+ action: 'handoff_overtaken', decision, source, draftNumber, ...(reply && { decidedBy, doctorReply: reply }),
1418
+ });
1419
+ throw httpError(409, STALE_HANDOFF);
1420
+ }
1421
+ throw httpError(409, STALE_DRAFT);
1422
+ }
1423
+ const warnings = decision === 'edited_approved' ? draftlessDrugWarnings(approvedText, draft) : [];
1424
+
1425
+ const updated = await updateReview(reviewId, DECIDABLE_STATUSES, {
938
1426
  $push: {
939
1427
  decisions: {
940
1428
  decision,
@@ -943,16 +1431,118 @@ async function recordDoctorDecision({
943
1431
  finalText: approvedText,
944
1432
  comment: optionalText(comment),
945
1433
  doctorReply: reply,
1434
+ ...(returnReason && { returnReason }),
1435
+ ...(warnings.length && { warnings }),
946
1436
  decidedBy,
947
1437
  recordedBy: operator,
948
1438
  },
949
1439
  },
950
- $set: { status: statusAfter(decision) },
1440
+ // No requiere closes the case in the same write, so it can never be left returned and half done.
1441
+ $set: returnReason === 'no_requiere'
1442
+ ? { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: `no_requiere${comment ? `: ${comment}` : ''}` }
1443
+ : { status: statusAfter(decision) },
1444
+ // Nothing new since the draft was checked against: an update landing meanwhile refuses the decision.
1445
+ }, { drafts: { $size: review.drafts.length }, alarms: { $size: (review.alarms ?? []).length }, ...latestUpdateGuard(review) });
1446
+ await audit(updated, operator, requestId, {
1447
+ action: 'doctor_decision', decision, source, draftNumber, ...(returnReason && { returnReason }),
951
1448
  });
952
- await audit(updated, operator, requestId, { action: 'doctor_decision', decision, source, draftNumber });
1449
+ if (returnReason === 'no_requiere') {
1450
+ await audit(updated, operator, requestId, { action: 'cancelled', reason: updated.cancellationReason });
1451
+ const { review: cancelled } = await syncCase(await resumeAssistant(updated, operator, requestId), operator, requestId);
1452
+ return cancelled;
1453
+ }
953
1454
  return updated;
954
1455
  }
955
1456
 
1457
+ // An approver writing to the patient in the chat delivers the indication themselves: the open
1458
+ // review is resolved with what they wrote and moves to follow-up. Anyone else's message is not.
1459
+ // The case selection a write was built from; a review from before the list holds a single case id.
1460
+ const casesAsRead = (review) => (Array.isArray(review.patientCaseRecordIds)
1461
+ ? { patientCaseRecordIds: review.patientCaseRecordIds }
1462
+ : { patientCaseRecordIds: { $exists: false }, patientCaseRecordId: review.patientCaseRecordId ?? null });
1463
+
1464
+ async function recordDirectIndication({ code, triggeredBy, body, messageId = null, status = null, deferred = false } = {}) {
1465
+ try {
1466
+ const text = String(body ?? '').trim();
1467
+ const operator = String(triggeredBy ?? '').trim();
1468
+ if (!text || !operator) return null;
1469
+ const patientCode = patientCodeOf(code);
1470
+ const EscalationReview = getEscalationReview();
1471
+ const openReview = (only = {}) => EscalationReview
1472
+ .findOne({ patientCode, closedAt: null, status: { $in: DIRECT_CHAT_STATUSES }, ...only })
1473
+ .lean();
1474
+ let review = await openReview();
1475
+ if (!review) return null;
1476
+ if (!await getEscalationApprover(operator)) return null;
1477
+
1478
+ // The write names the cases it mirrors to; a selection changed in between is read again.
1479
+ for (let attempt = 1; review && attempt <= DIRECT_CHAT_ATTEMPTS; attempt += 1) {
1480
+ const decisionNumber = (review.decisions ?? []).length + 1;
1481
+ // The doctor's own words become the cases' recommendation, as an approved send would.
1482
+ const updated = await EscalationReview.findOneAndUpdate(
1483
+ { _id: review._id, status: review.status, closedAt: null, ...casesAsRead(review) },
1484
+ withCaseMirror(review, {
1485
+ $push: {
1486
+ decisions: {
1487
+ decision: 'direct_chat',
1488
+ source: 'chat',
1489
+ draftNumber: (review.drafts ?? []).length,
1490
+ finalText: text,
1491
+ decidedBy: operator,
1492
+ recordedBy: operator,
1493
+ },
1494
+ },
1495
+ // A send still waiting on the 24 h window is queued for template recovery, exactly as an approved send.
1496
+ $set: {
1497
+ status: deferred ? 'indications_queued' : 'indications_sent',
1498
+ patientDelivery: {
1499
+ decisionNumber,
1500
+ messageId,
1501
+ status: optionalText(status),
1502
+ transport: deferred ? 'template_recovery' : 'text',
1503
+ deferred: Boolean(deferred),
1504
+ sentBy: operator,
1505
+ },
1506
+ },
1507
+ }, { recommendation: text.slice(0, MAX_NOTE_LENGTH) }),
1508
+ { new: true },
1509
+ ).lean();
1510
+ if (updated) {
1511
+ await audit(updated, operator, null, { action: 'direct_chat_resolved', decisionNumber, statusFrom: review.status });
1512
+ const { review: synced } = await syncCase(updated, operator, null);
1513
+ return synced;
1514
+ }
1515
+ // Only the review this message was meant for: one opened since then never saw it.
1516
+ if (attempt < DIRECT_CHAT_ATTEMPTS) review = await openReview({ _id: review._id });
1517
+ }
1518
+ return null;
1519
+ } catch (error) {
1520
+ logger.error('[EscalationReview] An approver message could not resolve the open review', {
1521
+ error: redactedError(error), stack: redactedStack(error),
1522
+ });
1523
+ return null;
1524
+ }
1525
+ }
1526
+
1527
+ // The updates history is capped, so once full its length stays put; the guard names the newest update.
1528
+ const latestUpdateGuard = (review) => {
1529
+ const updates = review.updates ?? [];
1530
+ if (!updates.length) return { 'updates.0': { $exists: false } };
1531
+ return { updates: { $size: updates.length }, [`updates.${updates.length - 1}.turnId`]: updates.at(-1).turnId };
1532
+ };
1533
+
1534
+ const arrivedAfter = (review, since) => Boolean(since) && [
1535
+ ...(review.alarms ?? []).map((alarm) => alarm.raisedAt),
1536
+ ...(review.updates ?? []).map((update) => update.at),
1537
+ ].some((at) => at && new Date(at) > new Date(since));
1538
+
1539
+ // The edited text may name a drug the draft never proposed. The doctor decides; the warning only
1540
+ // leaves a trace of it next to the decision.
1541
+ const draftlessDrugWarnings = (text, draft) => {
1542
+ const drafted = new Set(drugsNamedIn(`${draft.doctorText} ${draft.patientMessage}`));
1543
+ return drugsNamedIn(text).filter((drug) => !drafted.has(drug)).map((drug) => `el texto editado menciona ${drug}, que no estaba en el borrador`);
1544
+ };
1545
+
956
1546
  async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy, requestId = null } = {}) {
957
1547
  const reviewId = reviewIdOf(id);
958
1548
  const operator = requiredText(sentBy, 'sentBy');
@@ -975,6 +1565,17 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
975
1565
  throw httpError(409, 'This decision carries no approved text to send to the patient');
976
1566
  }
977
1567
 
1568
+ const decidedAt = claimed.decisions[decisionNumber - 1].createdAt;
1569
+ if (decidedAt && (claimed.updates ?? []).some((entry) => new Date(entry.at) > new Date(decidedAt))) {
1570
+ // Back to documenting: the decision is spent, and a new draft and decision have to follow.
1571
+ await releaseReview(reviewId, 'sending', 'documenting', claim).catch((releaseError) => {
1572
+ logger.error('[EscalationReview] The claim was not released after a decision new information overtook', {
1573
+ escalationReviewId: String(claimed._id), error: releaseError.message,
1574
+ });
1575
+ });
1576
+ throw httpError(409, 'The agent characterized the case after this decision; it went back to documenting for a new draft and decision');
1577
+ }
1578
+
978
1579
  // Built outside the try: composing reads Mongo and Airtable, and failing there never sent.
979
1580
  let message;
980
1581
  try {
@@ -1026,27 +1627,9 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
1026
1627
  }, { recommendation: finalText });
1027
1628
  const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status);
1028
1629
  await audit(review, operator, requestId, { action: status, decisionNumber, transport: delivery.transport });
1029
- const sent = await syncCase(review, operator, requestId);
1030
- if (review.status !== 'indications_sent' || decision === 'needs_intervention') return sent;
1031
- const decidedDraft = review.decisions[decisionNumber - 1]?.draftNumber;
1032
- const handoff = (review.doctorHandoffs ?? []).findLast((entry) => entry.draftNumber === decidedDraft);
1033
- if (handoff?.alarmCount == null || (review.alarms ?? []).length > handoff.alarmCount) {
1034
- logger.warn('[EscalationReview] The doctor did not see every alarm on this review; it stays open for them', {
1035
- escalationReviewId: String(review._id),
1036
- });
1037
- return sent;
1038
- }
1039
- try {
1040
- const closed = await closeEscalationReview({ id: reviewId, closedBy: operator, requestId, expectedAlarmCount: (review.alarms ?? []).length });
1041
- return closed;
1042
- } catch (error) {
1043
- const stored = await loadReview(reviewId).catch(() => sent.review);
1044
- let note = 'The indications were delivered but the review did not close; close it by hand';
1045
- if (stored.status === 'closed') note = 'The review closed, but a step after closing failed';
1046
- else if (error.statusCode === 409) note = 'An alarm joined while the review was closing; it stays open for it';
1047
- logger.error(`[EscalationReview] ${note}`, { escalationReviewId: String(review._id), error: redactedError(error) });
1048
- return { ...sent, review: stored };
1049
- }
1630
+ // Delivered indications move the review to follow-up; it closes once the patient's answer shows
1631
+ // the symptom holding or improving, or by hand.
1632
+ return syncCase(review, operator, requestId);
1050
1633
  }
1051
1634
 
1052
1635
  const EPISODE_TRUST = 0.7;
@@ -1105,7 +1688,9 @@ async function recordEpisode(review, now = new Date()) {
1105
1688
  }
1106
1689
  }
1107
1690
 
1108
- async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false, interruptionNotes = null, requestId = null, expectedAlarmCount = null } = {}) {
1691
+ async function closeEscalationReview({
1692
+ id, closedBy, deliveryConfirmed = false, interruptionNotes = null, requestId = null, expectedAlarmCount = null, expectedUpdatedAt = null,
1693
+ } = {}) {
1109
1694
  const reviewId = reviewIdOf(id);
1110
1695
  const operator = requiredText(closedBy, 'closedBy');
1111
1696
 
@@ -1133,6 +1718,7 @@ async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false,
1133
1718
  {
1134
1719
  ...(interrupted ? { operationClaim: current.operationClaim ?? null } : {}),
1135
1720
  ...(expectedAlarmCount === null ? {} : { alarms: { $size: expectedAlarmCount } }),
1721
+ ...(expectedUpdatedAt === null ? {} : { updatedAt: expectedUpdatedAt }),
1136
1722
  },
1137
1723
  );
1138
1724
  const closeChanges = { action: interrupted ? 'closed_from_interruption' : 'closed' };
@@ -1161,13 +1747,15 @@ async function cancelEscalationReview({ id, cancelledBy, reason = null, requestI
1161
1747
 
1162
1748
  let review;
1163
1749
  try {
1750
+ // Once the doctor has seen or decided the review, cancelling it needs a reason whatever its status.
1164
1751
  review = await updateReview(reviewId, allowed, {
1165
1752
  $set: { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: notes },
1166
- });
1753
+ }, notes ? {} : { 'doctorHandoffs.0': { $exists: false }, 'decisions.0': { $exists: false } });
1167
1754
  } catch (error) {
1168
1755
  if (error?.statusCode !== 409 || notes) throw error;
1169
1756
  const current = await loadReview(reviewId);
1170
- if (CANCELLABLE_AFTER_HANDOFF_STATUSES.includes(current.status)) throw httpError(409, CANCEL_NEEDS_REASON);
1757
+ const doctorInvolved = Boolean(current.doctorHandoffs?.length || current.decisions?.length);
1758
+ if (doctorInvolved || CANCELLABLE_AFTER_HANDOFF_STATUSES.includes(current.status)) throw httpError(409, CANCEL_NEEDS_REASON);
1171
1759
  throw error;
1172
1760
  }
1173
1761
 
@@ -1182,17 +1770,24 @@ async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {})
1182
1770
  }
1183
1771
 
1184
1772
  module.exports = {
1773
+ BOOKKEEPING,
1774
+ PRE_DECISION_STATUSES,
1185
1775
  _resetEscalationReviewIndexes,
1186
1776
  addCallLog,
1187
1777
  addDraft,
1188
1778
  cancelEscalationReview,
1189
1779
  closeEscalationReview,
1780
+ generateBotDraft,
1190
1781
  getEscalationReviewById,
1782
+ getReviewTimeline,
1191
1783
  handOffToDoctor,
1192
1784
  listEscalationReviews,
1193
1785
  openEscalationReview,
1194
1786
  recordEscalationAlarm,
1787
+ recordDirectIndication,
1195
1788
  recordDoctorDecision,
1789
+ sendScheduledDoctorAlert,
1790
+ recordReviewUpdate,
1196
1791
  sendApprovedIndications,
1197
1792
  setReviewCases,
1198
1793
  suggestDraft,