@peopl-health/nexus 6.0.0-dev.16502 → 6.0.0-dev.16508

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.
@@ -22,8 +22,8 @@ function escalationPatientTimerLive() {
22
22
  return flagOn('ESCALATION_PATIENT_TIMER_LIVE');
23
23
  }
24
24
 
25
- function escalationGravePendingShadow() {
26
- return flagOn('ESCALATION_GRAVE_PENDING_SHADOW');
25
+ function escalationAutoHandoffLive() {
26
+ return flagOn('ESCALATION_AUTO_HANDOFF_LIVE');
27
27
  }
28
28
 
29
29
  function escalationUntakenAlertsLive() {
@@ -33,7 +33,7 @@ function escalationUntakenAlertsLive() {
33
33
  module.exports = {
34
34
  escalationApproverAlertLive,
35
35
  escalationAssessmentLive,
36
- escalationGravePendingShadow,
36
+ escalationAutoHandoffLive,
37
37
  escalationPatientTimerLive,
38
38
  escalationUntakenAlertsLive,
39
39
  escalationUpdateModeLive,
@@ -31,6 +31,7 @@ function flagsByStatus(sections) {
31
31
  unassessed: pending.map((flag) => inlineOf(flag.flag)),
32
32
  drugSafety: pending.filter((flag) => flag.blocksDrug !== false).map((flag) => inlineOf(flag.flag)),
33
33
  urgent: pending.filter((flag) => flag.urgentIfPositive === true).map((flag) => inlineOf(flag.flag)),
34
+ urgentPresent: flags.filter((flag) => flag.present === true && flag.urgentIfPositive === true).map((flag) => inlineOf(flag.flag)),
34
35
  unobtainable: pending.filter((flag) => flag.present === UNOBTAINABLE).map((flag) => inlineOf(flag.flag)),
35
36
  };
36
37
  }
@@ -89,6 +89,17 @@ function draftProvider() {
89
89
  }
90
90
  }
91
91
 
92
+ const MAX_URGENT_FLAGS = 2;
93
+ const urgencyRank = (flag) => (flag.present === true ? 0 : flag.present === false ? 2 : 1);
94
+
95
+ // The model does not always keep to two grave flags per symptom: the confirmed ones keep the mark first, then the pending ones in its order.
96
+ function capUrgentFlags(block) {
97
+ const urgent = (Array.isArray(block?.redFlags) ? block.redFlags : []).filter((flag) => flag?.urgentIfPositive === true);
98
+ if (urgent.length <= MAX_URGENT_FLAGS) return block;
99
+ const kept = new Set([...urgent].sort((a, b) => urgencyRank(a) - urgencyRank(b)).slice(0, MAX_URGENT_FLAGS));
100
+ return { ...block, redFlags: block.redFlags.map((flag) => (urgent.includes(flag) && !kept.has(flag) ? { ...flag, urgentIfPositive: false } : flag)) };
101
+ }
102
+
92
103
  async function generateEscalationDraft({
93
104
  code, callLogs = [], alarms = [], agentCharacterization = null, provider, trace = null, reviewId = null, now = Date.now(),
94
105
  } = {}) {
@@ -131,7 +142,7 @@ async function generateEscalationDraft({
131
142
  const parsed = safeParse(readStructuredText(result), null);
132
143
  const patientMessage = trimmed(parsed?.patientMessage);
133
144
  // The schema is not strict, so the model sometimes sends the list JSON-encoded as a string.
134
- const blocks = parsed?.symptoms === undefined ? [parsed] : arrayArg(parsed.symptoms);
145
+ const blocks = (parsed?.symptoms === undefined ? [parsed] : arrayArg(parsed.symptoms)).map(capUrgentFlags);
135
146
  if (!blocks.length) {
136
147
  const shape = parsed.symptoms;
137
148
  logger.warn('[escalationDraft] generation returned a malformed symptom list', {
@@ -186,6 +197,9 @@ async function generateEscalationDraft({
186
197
  return { completed: false, attempted: true, rejected: true, reason: `the model wrote a field name or technical token into the doctor or patient text: "${leaked}"` };
187
198
  }
188
199
 
200
+ const urgentPresent = [...new Set(blocks.flatMap((block) => flagsByStatus(block).urgentPresent))];
201
+ // A grave flag the patient confirmed is enough for the doctor, whatever else is still pending.
202
+ const sufficientForDoctor = urgentPresent.length ? true : (typeof parsed?.sufficientForDoctor === 'boolean' ? parsed.sufficientForDoctor : null);
189
203
  return {
190
204
  completed: true,
191
205
  attempted: true,
@@ -196,9 +210,10 @@ async function generateEscalationDraft({
196
210
  unassessedRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).unassessed))],
197
211
  urgentUnassessedRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).urgent))],
198
212
  unobtainableRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).unobtainable))],
213
+ urgentPresentRedFlags: urgentPresent,
199
214
  missingCharacterization: textList(parsed?.missingCharacterization),
200
- sufficientForDoctor: typeof parsed?.sufficientForDoctor === 'boolean' ? parsed.sufficientForDoctor : null,
201
- blockingQuestion: parsed?.sufficientForDoctor === false ? trimmed(parsed?.blockingQuestion) || null : null,
215
+ sufficientForDoctor,
216
+ blockingQuestion: sufficientForDoctor === false ? trimmed(parsed?.blockingQuestion) || null : null,
202
217
  suggestCall: suggestCallOf(parsed?.suggestCall),
203
218
  sectionsUnavailable: context.degradedSections ?? [],
204
219
  };
@@ -75,11 +75,21 @@ const graveAlertSchema = new mongoose.Schema({
75
75
  firstSeenAt: { type: Date, required: true },
76
76
  reason: { type: String, enum: ['unobtainable', 'unanswered'], required: true },
77
77
  takenReason: { type: String, default: null },
78
- audience: { type: String, enum: ['all', 'group_doctor'], required: true },
79
- shadow: { type: Boolean, default: true },
78
+ audience: { type: String, enum: ['all', 'group_doctor'], default: null },
79
+ dueAt: { type: Date, required: true },
80
+ sentAt: { type: Date, default: null },
81
+ skippedReason: { type: String, default: null },
82
+ delivered: { type: Number, default: null },
80
83
  at: { type: Date, required: true },
81
84
  }, { _id: false });
82
85
 
86
+ const quietReminderSchema = new mongoose.Schema({
87
+ draftAt: { type: Date, required: true },
88
+ sentAt: { type: Date, required: true },
89
+ skippedReason: { type: String, default: null },
90
+ delivered: { type: Boolean, default: null },
91
+ }, { _id: false });
92
+
83
93
  const reviewUpdateSchema = new mongoose.Schema({
84
94
  turnId: { type: String, required: true },
85
95
  tools: { type: [String], default: [] },
@@ -123,6 +133,7 @@ const draftSchema = new mongoose.Schema({
123
133
  unassessedRedFlags: { type: [String], default: undefined },
124
134
  urgentUnassessedRedFlags: { type: [String], default: undefined },
125
135
  unobtainableRedFlags: { type: [String], default: undefined },
136
+ urgentPresentRedFlags: { type: [String], default: undefined },
126
137
  sufficientForDoctor: { type: Boolean, default: undefined },
127
138
  blockingQuestion: { type: String, default: undefined },
128
139
  missingCharacterization: { type: [String], default: undefined },
@@ -232,6 +243,9 @@ const escalationReviewSchema = new mongoose.Schema({
232
243
  doctorAlertAttempts: { type: Number, default: 0 },
233
244
  untakenAlerts: { type: [untakenAlertSchema], default: [] },
234
245
  graveAlerts: { type: [graveAlertSchema], default: [] },
246
+ autoHandoffFailedAt: { type: Date, default: null },
247
+ autoHandoffAttempts: { type: Number, default: 0 },
248
+ quietReminders: { type: [quietReminderSchema], default: [] },
235
249
  feverPromptStartedAt: { type: Date, default: null },
236
250
  approverViewedAt: { type: Date, default: null },
237
251
  previousReviewId: { type: String, default: null },
@@ -0,0 +1,294 @@
1
+ const { oneLineOf } = require('../utils/coercionUtils');
2
+ const { logger } = require('../utils/logger');
3
+ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
4
+ const { getEscalationReview } = require('../models/escalationReviewModel');
5
+ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
6
+ const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
7
+
8
+ const { countMessages } = require('./messageService');
9
+ const { logPatientChange } = require('./patientService');
10
+ const { getThreadInfo } = require('./threadService');
11
+ const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES, PRE_DECISION_STATUSES, caseTakenReason, handOffToDoctor, teamAlertIdentity } = require('./escalationReviewService');
12
+ const { graveMissingOf, isDraftCurrent, pendingFlagsOf } = require('./gravePendingService');
13
+ const { BUSINESS_HOURS_LEVELS, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
14
+ const { sendGroupNotice, sendTeamAlert } = require('./teamAlertService');
15
+
16
+ const OPERATOR = AUTO_HANDOFF_OPERATOR;
17
+ const AUDIT_SOURCE = 'escalation_review';
18
+ const OUTCOME_LEVELS = ['asap', 'urgent'];
19
+ const LEVEL_LABELS = { asap: 'ASAP', urgent: 'URGENT' };
20
+ const HANDOFF_RETRY_MS = 10 * 60 * 1000;
21
+ const MAX_HANDOFF_ATTEMPTS = 4;
22
+ const MAX_NOTE_LENGTH = 200;
23
+ const UPDATE_NOTE = 'Actualización: la paciente contestó';
24
+ const GRAVE_RETRY_MS = 5 * 60 * 1000;
25
+ const GRAVE_REASONS = { unobtainable: 'no lo puede dar', unanswered: 'no contestó' };
26
+ const QUIET_REMINDER_TEXT = '¿Pudiste ver lo que te pregunté? Cuando puedas, respóndeme por aquí.';
27
+ // A reminder this late (an outage, a deploy) is not sent.
28
+ const QUIET_REMINDER_STALE_MS = 30 * 60 * 1000;
29
+ const getMessaging = () => require('../core/NexusMessaging');
30
+
31
+ const noteOf = (text) => oneLineOf(text).slice(0, MAX_NOTE_LENGTH);
32
+ const timeOf = (value) => new Date(value).getTime();
33
+ const minutesSince = (from, now) => (now.getTime() - timeOf(from)) / 60000;
34
+
35
+ // Whether the bot's latest draft goes to the doctor now, and with which note; null while the patient still has time to answer.
36
+ function outcomeOf(review, clock, now) {
37
+ const wait = pendingWaitMinutes(clock?.level);
38
+ if (!wait || !OUTCOME_LEVELS.includes(clock.level) || !['draft_ready', 'awaiting_doctor'].includes(review.status)) return null;
39
+ const handoffs = (review.doctorHandoffs ?? []).filter((handoff) => timeOf(handoff.createdAt) >= clock.since.getTime());
40
+ const last = handoffs.at(-1);
41
+ // After the bot's own handoff, a newer draft goes as an update, unless a person handed it over or the doctor already answered.
42
+ if (handoffs.some((handoff) => handoff.sentBy !== OPERATOR) || handoffs.length > MAX_DOCTOR_UPDATES) return null;
43
+ if (last && (review.decisions ?? []).some((decision) => timeOf(decision.createdAt) > timeOf(last.createdAt))) return null;
44
+ const latest = (review.drafts ?? []).at(-1);
45
+ const after = Math.max(clock.since.getTime(), last ? timeOf(last.createdAt) + 1 : 0);
46
+ if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < after || !isDraftCurrent(review, latest)) return null;
47
+ const update = Boolean(last);
48
+ if (review.status === 'awaiting_doctor' && !update) return null;
49
+ const withUpdate = (note) => (update ? noteOf([UPDATE_NOTE, note].filter(Boolean).join(' · ')) : note);
50
+
51
+ const grave = graveMissingOf(review, clock, now);
52
+ const present = latest.urgentPresentRedFlags ?? [];
53
+ if (grave.length || present.length) {
54
+ const note = [present.length && `Bandera grave presente: ${present.join(', ')}`, grave.length && `Falta dato grave: ${grave.map(({ flag }) => flag).join(', ')}`];
55
+ return { grave, update, note: withUpdate(noteOf(note.filter(Boolean).join(' · '))) };
56
+ }
57
+ // A grave question still inside its wait holds the case even when the rest is enough.
58
+ if (pendingFlagsOf(review, clock.since).flags.length) return null;
59
+ if (latest.sufficientForDoctor === true) return { grave: [], update, note: withUpdate(null) };
60
+ // The latest draft follows the patient's latest answer, so its age is how long the question has gone unanswered.
61
+ if (latest.sufficientForDoctor !== false || minutesSince(latest.createdAt, now) < wait) return null;
62
+ return { grave: [], update, note: withUpdate(noteOf(`Falta: ${latest.blockingQuestion || 'información'} (no contestó)`)) };
63
+ }
64
+
65
+ const audit = (review, changes) => logPatientChange({
66
+ code: review.patientCode,
67
+ updatedBy: OPERATOR,
68
+ source: AUDIT_SOURCE,
69
+ requestId: null,
70
+ changes: { escalationReviewId: String(review._id), ...changes },
71
+ }).catch((error) => logger.error('[CharacterizationOutcome] The audit was not written', {
72
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
73
+ }));
74
+
75
+ // Records each grave datum once per episode; urgent ones found at night wait for the team day.
76
+ async function claimGraveAlerts(review, clock, grave, now) {
77
+ const dueAt = BUSINESS_HOURS_LEVELS.includes(clock.level) ? teamOpenAt(now, responseDeadlinePolicy()) : now;
78
+ const recorded = new Set((review.graveAlerts ?? [])
79
+ .filter((entry) => new Date(entry.since).getTime() === clock.since.getTime()).map((entry) => entry.flag));
80
+ const claimed = [];
81
+ for (const { flag, firstSeenAt, reason } of grave.filter((entry) => !recorded.has(entry.flag))) {
82
+ const entry = { flag, level: clock.level, since: clock.since, firstSeenAt, reason, dueAt, sentAt: null, at: now };
83
+ const result = await getEscalationReview().updateOne(
84
+ { _id: review._id, closedAt: null, graveAlerts: { $not: { $elemMatch: { flag, since: clock.since } } } },
85
+ { $push: { graveAlerts: entry } },
86
+ BOOKKEEPING,
87
+ );
88
+ if (result.modifiedCount) claimed.push(entry);
89
+ }
90
+ return claimed;
91
+ }
92
+
93
+ // A missing thread is no sign that anyone acted on the case.
94
+ const takenOf = async (review, clock) => {
95
+ const reason = await caseTakenReason(review, clock.since, clock.level);
96
+ return reason === 'thread_missing' ? null : reason;
97
+ };
98
+ // Failures from an earlier episode do not count against this one.
99
+ const attemptsOf = (review, clock) => (timeOf(review.autoHandoffFailedAt) >= clock.since.getTime() ? review.autoHandoffAttempts ?? 0 : 0);
100
+
101
+ async function handOff(review, clock, outcome, now) {
102
+ try {
103
+ await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, note: outcome.note });
104
+ } catch (error) {
105
+ const attempt = attemptsOf(review, clock) + 1;
106
+ await getEscalationReview().updateOne({ _id: review._id }, { $set: { autoHandoffFailedAt: now, autoHandoffAttempts: attempt } }, BOOKKEEPING);
107
+ // A 409 is mostly another sweep or a person who moved the case first.
108
+ logger[error?.statusCode === 409 ? 'warn' : 'error']('[CharacterizationOutcome] The case could not go to the doctor by itself', {
109
+ escalationReviewId: String(review._id), attempt, statusCode: error?.statusCode ?? null,
110
+ error: redactDirectIdentifiers(String(error?.message || error)),
111
+ });
112
+ if (attempt === MAX_HANDOFF_ATTEMPTS) await sendGaveUpNotice(review, clock);
113
+ return false;
114
+ }
115
+ if (review.autoHandoffAttempts) await getEscalationReview().updateOne({ _id: review._id }, { $set: { autoHandoffAttempts: 0 } }, BOOKKEEPING);
116
+ await audit(review, { action: outcome.update ? 'doctor_updated' : 'auto_handed_off', urgencyLevel: clock.level, grave: outcome.grave.length > 0, withNote: Boolean(outcome.note) });
117
+ return true;
118
+ }
119
+
120
+ async function sendHandoffNotice(review, clock, outcome) {
121
+ try {
122
+ await postHandoffNotice(review, clock, outcome);
123
+ } catch (error) {
124
+ logger.error('[CharacterizationOutcome] The handoff notice was not sent', {
125
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
126
+ });
127
+ }
128
+ }
129
+
130
+ async function sendGaveUpNotice(review, clock) {
131
+ try {
132
+ const { patient, doctor, link } = await teamAlertIdentity(review);
133
+ const body = [
134
+ `⚠️ No pudo pasar solo al médico · ${LEVEL_LABELS[clock.level]}`,
135
+ [`${patient} (${doctor})`, clock.symptom].filter(Boolean).join(' · '),
136
+ 'Qué hacer: revisar el caso y pasarlo al médico a mano',
137
+ link,
138
+ ].filter(Boolean).join('\n');
139
+ const sent = await sendGroupNotice(body, await readGroupMessageId(clock.emergencyRecordId, review.patientCode));
140
+ await audit(review, { action: 'auto_handoff_gave_up', urgencyLevel: clock.level, delivered: sent.delivered });
141
+ } catch (error) {
142
+ logger.error('[CharacterizationOutcome] The give-up notice was not sent', {
143
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
144
+ });
145
+ }
146
+ }
147
+
148
+ async function postHandoffNotice(review, clock, { note, update }) {
149
+ const { patient, doctor, link } = await teamAlertIdentity(review);
150
+ const taken = await takenOf(review, clock);
151
+ const header = update ? '📋 Actualización al médico' : '📋 Pasó al médico';
152
+ const body = [
153
+ taken ? header : `${header} · todavía sin tomar`,
154
+ [`${patient} (${doctor})`, clock.symptom].filter(Boolean).join(' · '),
155
+ note,
156
+ !taken && 'Qué hacer: escribir o llamar a la paciente si nadie lo ha hecho',
157
+ link,
158
+ ].filter(Boolean).join('\n');
159
+ const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
160
+ const sent = await sendGroupNotice(body, quoted);
161
+ await audit(review, { action: 'handoff_notice_sent', urgencyLevel: clock.level, delivered: sent.delivered });
162
+ }
163
+
164
+ async function graveMessage(review, clock, entries) {
165
+ const { patient, doctor, link } = await teamAlertIdentity(review);
166
+ const missing = entries.map(({ flag, reason }) => `${flag} (${GRAVE_REASONS[reason]})`).join(', ');
167
+ const action = 'Llamar a la paciente para conseguirlo y avisar al médico';
168
+ return {
169
+ body: [
170
+ `❗ Falta dato grave · ${LEVEL_LABELS[clock.level]}`,
171
+ [`${patient} (${doctor})`, clock.symptom].filter(Boolean).join(' · '),
172
+ `Falta: ${missing}`,
173
+ `Qué hacer: ${action}`,
174
+ link,
175
+ ].join('\n'),
176
+ template: { 1: `${LEVEL_LABELS[clock.level]}, falta dato grave${clock.symptom ? ` (${clock.symptom})` : ''}`, 2: patient, 3: doctor, 4: `Falta: ${missing} · ${action}`, 5: link },
177
+ };
178
+ }
179
+
180
+ const sameEntry = (entry) => ({ flag: entry.flag, since: entry.since });
181
+ const setOn = (review, entry, fields, filter = {}) => getEscalationReview().updateOne(
182
+ { _id: review._id, graveAlerts: { $elemMatch: { ...sameEntry(entry), ...filter } } },
183
+ { $set: Object.fromEntries(Object.entries(fields).map(([key, value]) => [`graveAlerts.$.${key}`, value])) },
184
+ BOOKKEEPING,
185
+ );
186
+
187
+ // Sends the grave alerts that are due: to everyone while nobody took the case, to the group once someone did (the doctor already has it).
188
+ async function sendDueGraveAlerts(review, clock, entries, now) {
189
+ const due = entries.filter((entry) => !entry.sentAt && timeOf(entry.dueAt) <= now.getTime() && timeOf(entry.since) === clock.since.getTime());
190
+ // A datum held for the night is dropped once a current draft written after it no longer lists it as pending.
191
+ const { latest, flags } = pendingFlagsOf(review, clock.since);
192
+ const stillPending = new Set(flags.map(({ flag }) => flag));
193
+ const redrafted = latest && isDraftCurrent(review, latest);
194
+ const answered = (entry) => entry.reason === 'unanswered' && redrafted && timeOf(latest.createdAt) > timeOf(entry.at) && !stillPending.has(entry.flag);
195
+ for (const entry of due.filter(answered)) await setOn(review, entry, { sentAt: now, skippedReason: 'answered' }, { sentAt: null });
196
+ const pending = due.filter((entry) => !answered(entry));
197
+ if (!pending.length) return 0;
198
+
199
+ const taken = await takenOf(review, clock);
200
+ const message = await graveMessage(review, clock, pending);
201
+ const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
202
+ const sending = [];
203
+ for (const entry of pending) if ((await setOn(review, entry, { sentAt: now }, { sentAt: null })).modifiedCount) sending.push(entry);
204
+ if (!sending.length) return 0;
205
+ let delivered = 0;
206
+ try {
207
+ delivered = taken
208
+ ? Number((await sendGroupNotice(message.body, quoted)).delivered)
209
+ : (await sendTeamAlert({ message, operator: OPERATOR, quoted })).delivered;
210
+ } catch (error) {
211
+ logger.error('[CharacterizationOutcome] The grave alert was not sent', {
212
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
213
+ });
214
+ }
215
+ // Reaching no one releases the claim and tries again in five minutes, within the team day for urgent.
216
+ const retryAt = new Date(now.getTime() + GRAVE_RETRY_MS);
217
+ for (const entry of sending) {
218
+ await setOn(review, entry, delivered
219
+ ? { audience: taken ? 'group_doctor' : 'all', takenReason: taken, delivered }
220
+ : { sentAt: null, dueAt: BUSINESS_HOURS_LEVELS.includes(clock.level) ? teamOpenAt(retryAt, responseDeadlinePolicy()) : retryAt });
221
+ }
222
+ await audit(review, { action: 'grave_missing_alerted', urgencyLevel: clock.level, flags: sending.length, audience: taken ? 'group_doctor' : 'all', delivered });
223
+ return delivered ? sending.length : 0;
224
+ }
225
+
226
+ const unsentGraveAlerts = (review, clock) => (review.graveAlerts ?? []).filter((entry) => !entry.sentAt && timeOf(entry.since) === clock.since.getTime());
227
+
228
+ // A patient in the hospital is already under care: the doctor still gets the grave datum, the team is not called for it.
229
+ async function skipGraveAlerts(review, clock, now) {
230
+ for (const entry of unsentGraveAlerts(review, clock)) await setOn(review, entry, { sentAt: now, skippedReason: 'patient_hospitalized' }, { sentAt: null });
231
+ }
232
+
233
+ // In urgent, a patient who left the bot's question unanswered gets one reminder, held for the team day at night.
234
+ async function remindQuietPatient(review, clock, now) {
235
+ if (clock.level !== 'urgent' || !PRE_DECISION_STATUSES.includes(review.status) || review.closedAt) return;
236
+ const latest = (review.drafts ?? []).at(-1);
237
+ if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime()) return;
238
+ const pending = !latest.urgentPresentRedFlags?.length && (latest.sufficientForDoctor === false || pendingFlagsOf(review, clock.since).flags.length > 0);
239
+ if (!pending || (review.quietReminders ?? []).some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
240
+ const dueAt = teamOpenAt(new Date(timeOf(latest.createdAt) + quietReminderMinutes() * 60000), responseDeadlinePolicy());
241
+ if (now.getTime() < dueAt.getTime()) return;
242
+ // A short reply records no clinical update, so the patient's own messages decide whether she answered.
243
+ if (await countMessages({ numero: review.patientCode, from_me: false, createdAt: { $gt: latest.createdAt } })) return;
244
+
245
+ let skippedReason = null;
246
+ if (now.getTime() - dueAt.getTime() > QUIET_REMINDER_STALE_MS) skippedReason = 'stale';
247
+ else skippedReason = await takenOf(review, clock);
248
+ if (!skippedReason && !await isWithin24HourWindow(review.patientCode)) skippedReason = 'outside_window';
249
+ const entry = { draftAt: latest.createdAt, sentAt: now, skippedReason, delivered: null };
250
+ const claimed = await getEscalationReview().updateOne(
251
+ { _id: review._id, closedAt: null, status: { $in: PRE_DECISION_STATUSES }, quietReminders: { $not: { $elemMatch: { draftAt: latest.createdAt } } } },
252
+ { $push: { quietReminders: entry } },
253
+ BOOKKEEPING,
254
+ );
255
+ if (!claimed.modifiedCount || skippedReason) return;
256
+ let delivered = false;
257
+ try {
258
+ const result = await getMessaging().sendMessage({
259
+ code: review.patientCode, body: QUIET_REMINDER_TEXT, triggeredBy: OPERATOR, idempotencyKey: `quiet-reminder:${review._id}:${timeOf(latest.createdAt)}`,
260
+ });
261
+ delivered = Boolean(result?.success && !result?.deferred);
262
+ if (!delivered) skippedReason = result?.status ?? 'not_sent';
263
+ } catch (error) {
264
+ skippedReason = 'threw';
265
+ logger.error('[CharacterizationOutcome] The reminder to the patient was not sent', {
266
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
267
+ });
268
+ }
269
+ await getEscalationReview().updateOne(
270
+ { _id: review._id, quietReminders: { $elemMatch: { draftAt: latest.createdAt } } },
271
+ { $set: { 'quietReminders.$.delivered': delivered, 'quietReminders.$.skippedReason': skippedReason } },
272
+ BOOKKEEPING,
273
+ );
274
+ await audit(review, { action: delivered ? 'quiet_patient_reminded' : 'quiet_patient_reminder_failed', urgencyLevel: clock.level, reason: skippedReason });
275
+ }
276
+
277
+ // After the bot escalates: hands the case to the doctor once it is enough or the patient stopped answering, and tells the team.
278
+ async function settleCharacterization(review, clock, now) {
279
+ if (!clock) return;
280
+ const outcome = outcomeOf(review, clock, now);
281
+ const graveWork = outcome?.grave.length || unsentGraveAlerts(review, clock).length;
282
+ const hospitalized = graveWork ? Boolean((await getThreadInfo(review.patientCode))?.hospitalizedAt) : false;
283
+ const claimed = outcome?.grave.length && !hospitalized ? await claimGraveAlerts(review, clock, outcome.grave, now) : [];
284
+ const attempts = attemptsOf(review, clock);
285
+ // Each failure doubles the wait; after the last attempt the team hands the case over by hand.
286
+ const backingOff = attempts >= MAX_HANDOFF_ATTEMPTS
287
+ || (attempts > 0 && now.getTime() - timeOf(review.autoHandoffFailedAt) < HANDOFF_RETRY_MS * 2 ** (attempts - 1));
288
+ if (outcome && !backingOff && await handOff(review, clock, outcome, now) && (hospitalized || !outcome.grave.length)) await sendHandoffNotice(review, clock, outcome);
289
+ if (hospitalized) await skipGraveAlerts(review, clock, now);
290
+ else await sendDueGraveAlerts(review, clock, [...(review.graveAlerts ?? []), ...claimed], now);
291
+ await remindQuietPatient(review, clock, now);
292
+ }
293
+
294
+ module.exports = { outcomeOf, settleCharacterization };
@@ -38,6 +38,7 @@ const {
38
38
  feverPatientTimerLive: feverTimerLive,
39
39
  escalationPatientTimerLive: escalationTimerLive,
40
40
  escalationApproverAlertLive,
41
+ escalationAutoHandoffLive,
41
42
  } = require('../clinical/flags/escalationFlags');
42
43
  const { chemoContextLive } = require('../clinical/flags/clinicalContextFlags');
43
44
  const { cytotoxicWindowDays, daysSinceLastCytotoxic } = require('../clinical/helpers/chemoContextHelper');
@@ -62,6 +63,8 @@ const TIMELINE_LIMIT = 500;
62
63
  const MAX_REVIEW_UPDATES = 50;
63
64
  const DRAFT_DEBOUNCE_MS = 20 * 1000;
64
65
  const DRAFT_OPERATOR = 'bot:escalationDraft';
66
+ const AUTO_HANDOFF_OPERATOR = 'bot:characterizationOutcome';
67
+ const MAX_DOCTOR_UPDATES = 3;
65
68
  const DIRECT_CHAT_ATTEMPTS = 3;
66
69
  const RECHECK_DELAY_MS = 60 * 1000;
67
70
  const ALERT_RETRY_DELAY_MS = 2 * 60 * 1000;
@@ -1396,10 +1399,19 @@ async function settleFollowUp(snapshot, { background = true } = {}) {
1396
1399
  return review;
1397
1400
  }
1398
1401
 
1402
+ // A case the bot handed over by itself is redrafted where it stands, so the doctor can get what the patient said next.
1403
+ function updatesDoctor(review) {
1404
+ if (!escalationAutoHandoffLive() || review.status !== 'awaiting_doctor' || review.doctorHandoffs?.at(-1)?.sentBy !== AUTO_HANDOFF_OPERATOR) return false;
1405
+ const decidedAt = Math.max(0, ...(review.decisions ?? []).map((decision) => new Date(decision.createdAt).getTime()));
1406
+ const botHandoffs = review.doctorHandoffs.filter((handoff) => handoff.sentBy === AUTO_HANDOFF_OPERATOR && new Date(handoff.createdAt).getTime() > decidedAt);
1407
+ return botHandoffs.length <= MAX_DOCTOR_UPDATES;
1408
+ }
1409
+
1399
1410
  async function generateBotDraft({ id, lease = null } = {}) {
1400
1411
  const startedAt = new Date();
1401
1412
  const review = await loadReview(reviewIdOf(id));
1402
- if (review.closedAt || !DOCUMENTING_STATUSES.includes(review.status)) return { review: null, retry: false };
1413
+ const updating = updatesDoctor(review);
1414
+ if (review.closedAt || (!DOCUMENTING_STATUSES.includes(review.status) && !updating)) return { review: null, retry: false };
1403
1415
  const latest = (review.drafts ?? []).at(-1);
1404
1416
  if (latest && latest.writtenBy !== DRAFT_OPERATOR) return { review: null, retry: false };
1405
1417
 
@@ -1436,6 +1448,7 @@ async function generateBotDraft({ id, lease = null } = {}) {
1436
1448
  unassessedRedFlags: draft.unassessedRedFlags,
1437
1449
  urgentUnassessedRedFlags: draft.urgentUnassessedRedFlags,
1438
1450
  unobtainableRedFlags: draft.unobtainableRedFlags,
1451
+ urgentPresentRedFlags: draft.urgentPresentRedFlags,
1439
1452
  sufficientForDoctor: draft.sufficientForDoctor,
1440
1453
  blockingQuestion: draft.blockingQuestion,
1441
1454
  missingCharacterization: draft.missingCharacterization,
@@ -1444,8 +1457,13 @@ async function generateBotDraft({ id, lease = null } = {}) {
1444
1457
  };
1445
1458
  const EscalationReview = getEscalationReview();
1446
1459
  const saved = await EscalationReview.findOneAndUpdate(
1447
- { _id: review._id, status: { $in: DOCUMENTING_STATUSES }, draftDueAt: { $lte: lease }, drafts: { $size: (review.drafts ?? []).length } },
1448
- { $push: { drafts: entry }, $set: { status: 'draft_ready', draftFailedAt: null }, $unset: { identityBlock: '' } },
1460
+ {
1461
+ _id: review._id,
1462
+ ...(updating ? { status: 'awaiting_doctor', doctorHandoffs: { $size: review.doctorHandoffs.length } } : { status: { $in: DOCUMENTING_STATUSES } }),
1463
+ draftDueAt: { $lte: lease },
1464
+ drafts: { $size: (review.drafts ?? []).length },
1465
+ },
1466
+ { $push: { drafts: entry }, $set: { status: updating ? 'awaiting_doctor' : 'draft_ready', draftFailedAt: null }, $unset: { identityBlock: '' } },
1449
1467
  { new: true },
1450
1468
  ).lean();
1451
1469
  if (!saved) return { review: null, retry: false };
@@ -1653,7 +1671,7 @@ async function soleApprover() {
1653
1671
  return approvers[0];
1654
1672
  }
1655
1673
 
1656
- async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, requestId = null } = {}) {
1674
+ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, note = null, requestId = null } = {}) {
1657
1675
  const reviewId = reviewIdOf(id);
1658
1676
  const operator = requiredText(sentBy, 'sentBy');
1659
1677
  if (!HANDOFF_MODES.includes(mode)) throw httpError(400, `mode must be one of: ${HANDOFF_MODES.join(', ')}`);
@@ -1680,8 +1698,8 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
1680
1698
  if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
1681
1699
  const link = doctorLink(review);
1682
1700
  const message = {
1683
- body: renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link }),
1684
- template: { 1: identity.patientName, 2: identity.treatingDoctor, 3: templateSummary(review), 4: link },
1701
+ body: [note, renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link })].filter(Boolean).join('\n\n'),
1702
+ template: { 1: identity.patientName, 2: identity.treatingDoctor, 3: [templateSummary(review), note].filter(Boolean).join(' · '), 4: link },
1685
1703
  };
1686
1704
 
1687
1705
  const patientCaseRecordIds = await reviewCaseIds(review);
@@ -1757,7 +1775,10 @@ async function recordDoctorDecision({
1757
1775
  const allowedStatuses = isDraftless ? [...new Set([...DOCUMENTING_STATUSES, ...DECIDABLE_STATUSES])] : DECIDABLE_STATUSES;
1758
1776
  if (!allowedStatuses.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
1759
1777
  const handoff = review.status === 'awaiting_doctor' ? review.doctorHandoffs.at(-1) : null;
1760
- const draftNumber = handoff?.draftNumber ?? review.drafts.length;
1778
+ // The panel shows the latest draft, so a doctor deciding on a bot update not sent yet decides on that one.
1779
+ const onUnsentUpdate = handoff?.sentBy === AUTO_HANDOFF_OPERATOR && Number(seenDraftNumber) === review.drafts.length
1780
+ && review.drafts.at(-1)?.writtenBy === DRAFT_OPERATOR;
1781
+ const draftNumber = onUnsentUpdate ? review.drafts.length : handoff?.draftNumber ?? review.drafts.length;
1761
1782
  const draft = review.drafts[draftNumber - 1];
1762
1783
  if (!draft && !isDraftless) throw httpError(409, STATUS_CONFLICT);
1763
1784
  if (seenDraftNumber !== null && Number(seenDraftNumber) !== draftNumber) throw httpError(409, DRAFT_CHANGED);
@@ -2148,7 +2169,10 @@ async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {})
2148
2169
 
2149
2170
  module.exports = {
2150
2171
  BOOKKEEPING,
2172
+ AUTO_HANDOFF_OPERATOR,
2151
2173
  DOCUMENTING_STATUSES,
2174
+ DRAFT_OPERATOR,
2175
+ MAX_DOCTOR_UPDATES,
2152
2176
  FEVER_CATEGORY,
2153
2177
  appliedLevelOf,
2154
2178
  MAX_ALERT_ATTEMPTS,
@@ -1,13 +1,5 @@
1
- const { logger } = require('../utils/logger');
2
- const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
- const { getEscalationReview } = require('../models/escalationReviewModel');
4
-
5
- const { logPatientChange } = require('./patientService');
6
- const { BOOKKEEPING, DOCUMENTING_STATUSES, PRE_DECISION_STATUSES, caseTakenReason } = require('./escalationReviewService');
7
-
8
- const UNANSWERED_MINUTES = { asap: 15, urgent: 60 };
9
- const OPERATOR = 'bot:gravePending';
10
- const AUDIT_SOURCE = 'escalation_review';
1
+ const { DOCUMENTING_STATUSES } = require('./escalationReviewService');
2
+ const { pendingWaitMinutes } = require('./reviewDeadlineService');
11
3
 
12
4
  const keyOf = (flag) => String(flag ?? '').trim().toLowerCase().replace(/\s+/g, ' ');
13
5
  const keysOf = (flags) => [...new Set((flags ?? []).map(keyOf).filter(Boolean))];
@@ -28,15 +20,15 @@ function pendingFlagsOf(review, since) {
28
20
  }
29
21
 
30
22
  // The latest draft speaks for the case only while no newer patient turn or redraft is waiting to replace it.
31
- const isCurrent = (review, latest) => !review.draftDueAt
23
+ const isDraftCurrent = (review, latest) => !review.draftDueAt
32
24
  && !(review.updates ?? []).some((update) => new Date(update.at).getTime() > new Date(latest.createdAt).getTime());
33
25
 
34
- // A grave datum becomes C at once when the patient cannot give it, or once it stays unanswered past the level's limit.
26
+ // A grave datum is missing at once when the patient cannot give it, or once it stays unanswered past the level's wait.
35
27
  function graveMissingOf(review, clock, now) {
36
- const limit = UNANSWERED_MINUTES[clock?.level];
28
+ const limit = pendingWaitMinutes(clock?.level);
37
29
  if (!limit) return [];
38
30
  const { latest, flags } = pendingFlagsOf(review, clock.since);
39
- if (!latest || !isCurrent(review, latest)) return [];
31
+ if (!latest || !isDraftCurrent(review, latest)) return [];
40
32
  // Once the case left documenting (with the doctor) no new draft comes, so the wait no longer means unanswered.
41
33
  const waiting = DOCUMENTING_STATUSES.includes(review.status);
42
34
  return flags.flatMap(({ flag, firstSeenAt, unobtainable }) => {
@@ -45,35 +37,4 @@ function graveMissingOf(review, clock, now) {
45
37
  });
46
38
  }
47
39
 
48
- const recordedFor = (review, clock, flag) => (review.graveAlerts ?? [])
49
- .some((entry) => entry.flag === flag && new Date(entry.since).getTime() === clock.since.getTime());
50
-
51
- // Shadow only: records when a grave datum would have gone to C and who would have been alerted, without alerting anyone.
52
- async function recordGraveMissing(review, clock, now) {
53
- const missing = graveMissingOf(review, clock, now).filter(({ flag }) => !recordedFor(review, clock, flag));
54
- if (!missing.length) return 0;
55
- const taken = await caseTakenReason(review, clock.since, clock.level);
56
- let recorded = 0;
57
- for (const { flag, firstSeenAt, reason } of missing) {
58
- const entry = { flag, level: clock.level, since: clock.since, firstSeenAt, reason, takenReason: taken, audience: taken ? 'group_doctor' : 'all', shadow: true, at: now };
59
- const claimed = await getEscalationReview().updateOne(
60
- { _id: review._id, closedAt: null, status: { $in: PRE_DECISION_STATUSES }, graveAlerts: { $not: { $elemMatch: { flag, since: clock.since } } } },
61
- { $push: { graveAlerts: entry } },
62
- BOOKKEEPING,
63
- );
64
- if (!claimed.modifiedCount) continue;
65
- recorded += 1;
66
- await logPatientChange({
67
- code: review.patientCode,
68
- updatedBy: OPERATOR,
69
- source: AUDIT_SOURCE,
70
- requestId: null,
71
- changes: { escalationReviewId: String(review._id), action: 'grave_missing_shadow', urgencyLevel: clock.level, reason, audience: entry.audience, takenReason: taken },
72
- }).catch((error) => logger.error('[GravePending] The shadow audit was not written', {
73
- escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
74
- }));
75
- }
76
- return recorded;
77
- }
78
-
79
- module.exports = { graveMissingOf, recordGraveMissing };
40
+ module.exports = { graveMissingOf, isDraftCurrent, pendingFlagsOf };
@@ -11,6 +11,9 @@ const UNTAKEN_STAGES = { stat: ['deadline'], asap: ['early', 'half', 'deadline']
11
11
  const DEFAULT_PATIENT_TIMER_MINUTES = { stat: 15, asap: 20 };
12
12
  const PATIENT_TIMER_KEYS = { stat: 'ESCALATION_PATIENT_TIMER_MINUTES', asap: 'ESCALATION_ASAP_PATIENT_TIMER_MINUTES' };
13
13
  const DEFAULT_UNTAKEN_EARLY_MINUTES = 15;
14
+ const DEFAULT_PENDING_WAIT_MINUTES = { asap: 5, urgent: 60 };
15
+ const PENDING_WAIT_KEYS = { asap: 'ESCALATION_PENDING_WAIT_MINUTES_ASAP', urgent: 'ESCALATION_PENDING_WAIT_MINUTES_URGENT' };
16
+ const DEFAULT_QUIET_REMINDER_MINUTES = 30;
14
17
 
15
18
  const rankOf = (level) => URGENCY_RANK[level] || 0;
16
19
  const timeOf = (value) => (value ? new Date(value).getTime() : NaN);
@@ -74,6 +77,10 @@ const positiveMinutes = (key, fallback) => {
74
77
  // asap leaves the team its early alert before the patient gets the numbers to call.
75
78
  const patientTimerMinutes = (level) => positiveMinutes(PATIENT_TIMER_KEYS[level], DEFAULT_PATIENT_TIMER_MINUTES[level]);
76
79
  const untakenEarlyMinutes = () => positiveMinutes('ESCALATION_UNTAKEN_EARLY_MINUTES', DEFAULT_UNTAKEN_EARLY_MINUTES);
80
+ // How long a question the patient left unanswered waits before the case goes to the doctor without the answer.
81
+ const pendingWaitMinutes = (level) => (PENDING_WAIT_KEYS[level] ? positiveMinutes(PENDING_WAIT_KEYS[level], DEFAULT_PENDING_WAIT_MINUTES[level]) : null);
82
+ const teamOpenAt = (now, policy) => addWorkingMinutes(now, 0, policy.teamHours);
83
+ const quietReminderMinutes = () => positiveMinutes('ESCALATION_QUIET_REMINDER_MINUTES', DEFAULT_QUIET_REMINDER_MINUTES);
77
84
 
78
85
  // Untaken alerts: asap early, asap and urgent at half the response time, and every level at the deadline.
79
86
  function untakenStagesOf(level, since, policy) {
@@ -101,6 +108,9 @@ module.exports = {
101
108
  effectiveUrgencyOf,
102
109
  responseDeadlineOf,
103
110
  patientTimerMinutes,
111
+ pendingWaitMinutes,
112
+ quietReminderMinutes,
104
113
  responseDeadlinePolicy,
114
+ teamOpenAt,
105
115
  untakenStagesOf,
106
116
  };
@@ -137,4 +137,4 @@ async function sendTeamAlert({ message, operator, level = null, notice = false,
137
137
  return { group, phones, delivered };
138
138
  }
139
139
 
140
- module.exports = { _resetRoster, groupConfigured, sendTeamAlert, teamChannelConfigured, teamPhones };
140
+ module.exports = { _resetRoster, groupConfigured, sendGroupNotice: sendToGroup, sendTeamAlert, teamChannelConfigured, teamPhones };
@@ -3,12 +3,12 @@ const { logger } = require('../utils/logger');
3
3
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
4
4
  const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
5
5
  const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
6
- const { escalationGravePendingShadow, escalationPatientTimerLive, escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
6
+ const { escalationAutoHandoffLive, escalationPatientTimerLive, escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
7
7
 
8
8
  const { logPatientChange } = require('./patientService');
9
9
  const { BUSINESS_HOURS_LEVELS, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
10
10
  const { BOOKKEEPING, FEVER_CATEGORY, PRE_DECISION_STATUSES, appliedLevelOf, caseTakenReason, currentAlarms, teamAlertIdentity } = require('./escalationReviewService');
11
- const { recordGraveMissing } = require('./gravePendingService');
11
+ const { settleCharacterization } = require('./characterizationOutcomeService');
12
12
  const { sendTeamAlert } = require('./teamAlertService');
13
13
 
14
14
  const UNTAKEN_LEVELS = ['stat', 'asap', 'urgent'];
@@ -160,18 +160,19 @@ async function alertIfUntaken(review, clock, stage, now) {
160
160
  return true;
161
161
  }
162
162
 
163
- // Alerts the whole team at each stage of a case nobody took (asap also early); being with the doctor is not taken.
163
+ // Alerts the team at each stage of a case nobody took (being with the doctor is not taken) and settles the bot's characterization.
164
164
  async function sweepUntakenAlerts({ now = new Date() } = {}) {
165
165
  const alerts = escalationUntakenAlertsLive();
166
- const graveShadow = escalationGravePendingShadow();
167
- if (!alerts && !graveShadow) return 0;
166
+ const autoHandoff = escalationAutoHandoffLive();
167
+ if (!alerts && !autoHandoff) return 0;
168
168
  const reviews = await getEscalationReview()
169
169
  .find({
170
170
  closedAt: null,
171
171
  status: { $in: PRE_DECISION_STATUSES },
172
172
  alarms: { $elemMatch: { raisedAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } } },
173
- }, { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
174
- 'drafts.createdAt': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
173
+ }, { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, quietReminders: 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
174
+ 'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
175
+ 'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1,
175
176
  })
176
177
  .sort({ _id: -1 })
177
178
  .limit(SWEEP_LIMIT)
@@ -183,7 +184,7 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
183
184
  const clock = untakenClockOf(review, policy);
184
185
  const stage = alerts && clock && dueStageOf(review, clock, now);
185
186
  if (stage && await alertIfUntaken(review, clock, stage, now)) sent += 1;
186
- if (graveShadow && clock) await recordGraveMissing(review, clock, now);
187
+ if (autoHandoff) await settleCharacterization(review, clock, now);
187
188
  } catch (error) {
188
189
  logger.error('[UntakenAlert] Could not check a review for an untaken alert', {
189
190
  escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.0-dev.16502",
3
+ "version": "6.0.0-dev.16508",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",