@peopl-health/nexus 6.0.0-dev.16341 → 6.0.0-dev.16505

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,
@@ -14,6 +14,9 @@ const NEGATION = /\b(sin|niega|no|ninguna?)\b/;
14
14
 
15
15
  const isDay = (value) => typeof value === 'string' && ISO_DAY.test(value) && !Number.isNaN(Date.parse(`${value}T00:00:00Z`));
16
16
  const dmy = (iso) => `${iso.slice(8, 10)}/${iso.slice(5, 7)}/${iso.slice(0, 4)}`;
17
+ // a weekday with the date: the model miscounts the day of the week from a bare date ("el viernes" for a Saturday)
18
+ const WEEKDAYS = ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'];
19
+ const weekdayDmy = (iso) => `${WEEKDAYS[new Date(`${iso}T00:00:00Z`).getUTCDay()]} ${dmy(iso)}`;
17
20
  const addDays = (iso, days) => new Date(Date.parse(`${iso}T00:00:00Z`) + days * 86400000).toISOString().slice(0, 10);
18
21
  const fold = (value) => foldAccents(String(value || '')).toLowerCase().trim();
19
22
  const text = (value) => (typeof value === 'string' ? value.trim() : '');
@@ -132,13 +135,13 @@ function chemoLines(context, today) {
132
135
  }
133
136
  if (context.proximaSesion && context.proximaSesion.fecha >= today) {
134
137
  lines.push(context.proximaSesion.tipo === 'agendada'
135
- ? `Próxima sesión de quimioterapia: ${dmy(context.proximaSesion.fecha)}${CLOCK.test(context.proximaSesion.hora) ? ` a las ${context.proximaSesion.hora}` : ''} (${['agendada', confirmation(context.proximaSesion)].filter(Boolean).join('; ')})`
136
- : `Próxima sesión de quimioterapia: ${dmy(context.proximaSesion.fecha)} (estimada; no la confirmes como cita)`);
138
+ ? `Próxima sesión de quimioterapia: ${weekdayDmy(context.proximaSesion.fecha)}${CLOCK.test(context.proximaSesion.hora) ? ` a las ${context.proximaSesion.hora}` : ''} (${['agendada', confirmation(context.proximaSesion)].filter(Boolean).join('; ')})`
139
+ : `Próxima sesión de quimioterapia: ${weekdayDmy(context.proximaSesion.fecha)} (estimada; no la confirmes como cita)`);
137
140
  }
138
141
  const support = context.proximaVisitaSoporte;
139
142
  if (support && support.fecha >= today) {
140
143
  const care = texts(support.detalle);
141
- lines.push(`Próxima visita a la unidad sin quimioterapia: ${dmy(support.fecha)} (${[care.join(', '), confirmation(support)].filter(Boolean).join('; ')})`);
144
+ lines.push(`Próxima visita a la unidad sin quimioterapia: ${weekdayDmy(support.fecha)} (${[care.join(', '), confirmation(support)].filter(Boolean).join('; ')})`);
142
145
  }
143
146
  if (context.noAplicadas.length) lines.push(`Sesiones no aplicadas en los últimos 90 días: ${context.noAplicadas.map(dmy).join(', ')}`);
144
147
  if (text(context.reaccionInfusion?.texto)) lines.push(`Reacción durante la infusión registrada: ${text(context.reaccionInfusion.texto)} (${dmy(context.reaccionInfusion.fecha)})`);
@@ -880,6 +880,13 @@ function issuePaths(issues) {
880
880
  return [...new Set(issues.map((issue) => String(issue.path || '').replace(/\[[^\]]*\]/g, '[]')).filter(Boolean))];
881
881
  }
882
882
 
883
+ // Zod issue paths in dotted form with indices collapsed; keys are the DTO's camelCase, not the model's snake_case.
884
+ function dtoIssues(err) {
885
+ const issues = Array.isArray(err?.issues) ? err.issues : [];
886
+ const paths = issues.map((issue) => ({ path: arr(issue.path).map((key) => (typeof key === 'number' ? '[]' : `.${String(key)}`)).join('').replace(/^\./, '') }));
887
+ return paths.some((issue) => issue.path) ? paths : null;
888
+ }
889
+
883
890
  function truncateToCardLimit(elements, repairs) {
884
891
  const excess = elements.length - MAX_TRIAGE_CARDS;
885
892
  if (excess <= 0) return 0;
@@ -992,7 +999,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
992
999
  plan = buildPlan(takeaways, elements);
993
1000
  } catch (err) {
994
1001
  lastIssues = [{ path: 'plan', problem: err?.message || 'DTO inválido' }];
995
- if (attempt < PLAN_MAX_ATTEMPTS) { retried(attempt, 'plan_dto_invalid'); continue; }
1002
+ if (attempt < PLAN_MAX_ATTEMPTS) { retried(attempt, 'plan_dto_invalid', dtoIssues(err)); continue; }
996
1003
  return outcome({ attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_invalid', hardRejectIssues: lastIssues } });
997
1004
  }
998
1005
  return outcome({
@@ -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: [] },
@@ -232,6 +242,9 @@ const escalationReviewSchema = new mongoose.Schema({
232
242
  doctorAlertAttempts: { type: Number, default: 0 },
233
243
  untakenAlerts: { type: [untakenAlertSchema], default: [] },
234
244
  graveAlerts: { type: [graveAlertSchema], default: [] },
245
+ autoHandoffFailedAt: { type: Date, default: null },
246
+ autoHandoffAttempts: { type: Number, default: 0 },
247
+ quietReminders: { type: [quietReminderSchema], default: [] },
235
248
  feverPromptStartedAt: { type: Date, default: null },
236
249
  approverViewedAt: { type: Date, default: null },
237
250
  previousReviewId: { type: String, default: null },
@@ -0,0 +1,279 @@
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 { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES, PRE_DECISION_STATUSES, caseTakenReason, handOffToDoctor, teamAlertIdentity } = require('./escalationReviewService');
11
+ const { graveMissingOf, isDraftCurrent, pendingFlagsOf } = require('./gravePendingService');
12
+ const { BUSINESS_HOURS_LEVELS, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
13
+ const { sendGroupNotice, sendTeamAlert } = require('./teamAlertService');
14
+
15
+ const OPERATOR = AUTO_HANDOFF_OPERATOR;
16
+ const AUDIT_SOURCE = 'escalation_review';
17
+ const OUTCOME_LEVELS = ['asap', 'urgent'];
18
+ const LEVEL_LABELS = { asap: 'ASAP', urgent: 'URGENT' };
19
+ const HANDOFF_RETRY_MS = 10 * 60 * 1000;
20
+ const MAX_HANDOFF_ATTEMPTS = 4;
21
+ const MAX_NOTE_LENGTH = 200;
22
+ const UPDATE_NOTE = 'Actualización: la paciente contestó';
23
+ const GRAVE_RETRY_MS = 5 * 60 * 1000;
24
+ const GRAVE_REASONS = { unobtainable: 'no lo puede dar', unanswered: 'no contestó' };
25
+ const QUIET_REMINDER_TEXT = '¿Pudiste ver lo que te pregunté? Cuando puedas, respóndeme por aquí.';
26
+ // A reminder this late (an outage, a deploy) is not sent.
27
+ const QUIET_REMINDER_STALE_MS = 30 * 60 * 1000;
28
+ const getMessaging = () => require('../core/NexusMessaging');
29
+
30
+ const noteOf = (text) => oneLineOf(text).slice(0, MAX_NOTE_LENGTH);
31
+ const timeOf = (value) => new Date(value).getTime();
32
+ const minutesSince = (from, now) => (now.getTime() - timeOf(from)) / 60000;
33
+
34
+ // Whether the bot's latest draft goes to the doctor now, and with which note; null while the patient still has time to answer.
35
+ function outcomeOf(review, clock, now) {
36
+ const wait = pendingWaitMinutes(clock?.level);
37
+ if (!wait || !OUTCOME_LEVELS.includes(clock.level) || !['draft_ready', 'awaiting_doctor'].includes(review.status)) return null;
38
+ const handoffs = (review.doctorHandoffs ?? []).filter((handoff) => timeOf(handoff.createdAt) >= clock.since.getTime());
39
+ const last = handoffs.at(-1);
40
+ // After the bot's own handoff, a newer draft goes as an update, unless a person handed it over or the doctor already answered.
41
+ if (handoffs.some((handoff) => handoff.sentBy !== OPERATOR) || handoffs.length > MAX_DOCTOR_UPDATES) return null;
42
+ if (last && (review.decisions ?? []).some((decision) => timeOf(decision.createdAt) > timeOf(last.createdAt))) return null;
43
+ const latest = (review.drafts ?? []).at(-1);
44
+ const after = Math.max(clock.since.getTime(), last ? timeOf(last.createdAt) + 1 : 0);
45
+ if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < after || !isDraftCurrent(review, latest)) return null;
46
+ const update = Boolean(last);
47
+ if (review.status === 'awaiting_doctor' && !update) return null;
48
+ const withUpdate = (note) => (update ? noteOf([UPDATE_NOTE, note].filter(Boolean).join(' · ')) : note);
49
+
50
+ const grave = graveMissingOf(review, clock, now);
51
+ if (grave.length) return { grave, update, note: withUpdate(noteOf(`Falta dato grave: ${grave.map(({ flag }) => flag).join(', ')}`)) };
52
+ // A grave question still inside its wait holds the case even when the rest is enough.
53
+ if (pendingFlagsOf(review, clock.since).flags.length) return null;
54
+ if (latest.sufficientForDoctor === true) return { grave: [], update, note: withUpdate(null) };
55
+ // The latest draft follows the patient's latest answer, so its age is how long the question has gone unanswered.
56
+ if (latest.sufficientForDoctor !== false || minutesSince(latest.createdAt, now) < wait) return null;
57
+ return { grave: [], update, note: withUpdate(noteOf(`Falta: ${latest.blockingQuestion || 'información'} (no contestó)`)) };
58
+ }
59
+
60
+ const audit = (review, changes) => logPatientChange({
61
+ code: review.patientCode,
62
+ updatedBy: OPERATOR,
63
+ source: AUDIT_SOURCE,
64
+ requestId: null,
65
+ changes: { escalationReviewId: String(review._id), ...changes },
66
+ }).catch((error) => logger.error('[CharacterizationOutcome] The audit was not written', {
67
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
68
+ }));
69
+
70
+ // Records each grave datum once per episode; urgent ones found at night wait for the team day.
71
+ async function claimGraveAlerts(review, clock, grave, now) {
72
+ const dueAt = BUSINESS_HOURS_LEVELS.includes(clock.level) ? teamOpenAt(now, responseDeadlinePolicy()) : now;
73
+ const recorded = new Set((review.graveAlerts ?? [])
74
+ .filter((entry) => new Date(entry.since).getTime() === clock.since.getTime()).map((entry) => entry.flag));
75
+ const claimed = [];
76
+ for (const { flag, firstSeenAt, reason } of grave.filter((entry) => !recorded.has(entry.flag))) {
77
+ const entry = { flag, level: clock.level, since: clock.since, firstSeenAt, reason, dueAt, sentAt: null, at: now };
78
+ const result = await getEscalationReview().updateOne(
79
+ { _id: review._id, closedAt: null, graveAlerts: { $not: { $elemMatch: { flag, since: clock.since } } } },
80
+ { $push: { graveAlerts: entry } },
81
+ BOOKKEEPING,
82
+ );
83
+ if (result.modifiedCount) claimed.push(entry);
84
+ }
85
+ return claimed;
86
+ }
87
+
88
+ // A missing thread is no sign that anyone acted on the case.
89
+ const takenOf = async (review, clock) => {
90
+ const reason = await caseTakenReason(review, clock.since, clock.level);
91
+ return reason === 'thread_missing' ? null : reason;
92
+ };
93
+ // Failures from an earlier episode do not count against this one.
94
+ const attemptsOf = (review, clock) => (timeOf(review.autoHandoffFailedAt) >= clock.since.getTime() ? review.autoHandoffAttempts ?? 0 : 0);
95
+
96
+ async function handOff(review, clock, outcome, now) {
97
+ try {
98
+ await handOffToDoctor({ id: String(review._id), mode: 'sent_whatsapp', sentBy: OPERATOR, note: outcome.note });
99
+ } catch (error) {
100
+ const attempt = attemptsOf(review, clock) + 1;
101
+ await getEscalationReview().updateOne({ _id: review._id }, { $set: { autoHandoffFailedAt: now, autoHandoffAttempts: attempt } }, BOOKKEEPING);
102
+ // A 409 is mostly another sweep or a person who moved the case first.
103
+ logger[error?.statusCode === 409 ? 'warn' : 'error']('[CharacterizationOutcome] The case could not go to the doctor by itself', {
104
+ escalationReviewId: String(review._id), attempt, statusCode: error?.statusCode ?? null,
105
+ error: redactDirectIdentifiers(String(error?.message || error)),
106
+ });
107
+ if (attempt === MAX_HANDOFF_ATTEMPTS) await sendGaveUpNotice(review, clock);
108
+ return false;
109
+ }
110
+ if (review.autoHandoffAttempts) await getEscalationReview().updateOne({ _id: review._id }, { $set: { autoHandoffAttempts: 0 } }, BOOKKEEPING);
111
+ await audit(review, { action: outcome.update ? 'doctor_updated' : 'auto_handed_off', urgencyLevel: clock.level, grave: outcome.grave.length > 0, withNote: Boolean(outcome.note) });
112
+ return true;
113
+ }
114
+
115
+ async function sendHandoffNotice(review, clock, outcome) {
116
+ try {
117
+ await postHandoffNotice(review, clock, outcome);
118
+ } catch (error) {
119
+ logger.error('[CharacterizationOutcome] The handoff notice was not sent', {
120
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
121
+ });
122
+ }
123
+ }
124
+
125
+ async function sendGaveUpNotice(review, clock) {
126
+ try {
127
+ const { patient, doctor, link } = await teamAlertIdentity(review);
128
+ const body = [
129
+ `⚠️ No pudo pasar solo al médico · ${LEVEL_LABELS[clock.level]}`,
130
+ [`${patient} (${doctor})`, clock.symptom].filter(Boolean).join(' · '),
131
+ 'Qué hacer: revisar el caso y pasarlo al médico a mano',
132
+ link,
133
+ ].filter(Boolean).join('\n');
134
+ const sent = await sendGroupNotice(body, await readGroupMessageId(clock.emergencyRecordId, review.patientCode));
135
+ await audit(review, { action: 'auto_handoff_gave_up', urgencyLevel: clock.level, delivered: sent.delivered });
136
+ } catch (error) {
137
+ logger.error('[CharacterizationOutcome] The give-up notice was not sent', {
138
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
139
+ });
140
+ }
141
+ }
142
+
143
+ async function postHandoffNotice(review, clock, { note, update }) {
144
+ const { patient, doctor, link } = await teamAlertIdentity(review);
145
+ const taken = await takenOf(review, clock);
146
+ const header = update ? '📋 Actualización al médico' : '📋 Pasó al médico';
147
+ const body = [
148
+ taken ? header : `${header} · todavía sin tomar`,
149
+ [`${patient} (${doctor})`, clock.symptom].filter(Boolean).join(' · '),
150
+ note,
151
+ !taken && 'Qué hacer: escribir o llamar a la paciente si nadie lo ha hecho',
152
+ link,
153
+ ].filter(Boolean).join('\n');
154
+ const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
155
+ const sent = await sendGroupNotice(body, quoted);
156
+ await audit(review, { action: 'handoff_notice_sent', urgencyLevel: clock.level, delivered: sent.delivered });
157
+ }
158
+
159
+ async function graveMessage(review, clock, entries) {
160
+ const { patient, doctor, link } = await teamAlertIdentity(review);
161
+ const missing = entries.map(({ flag, reason }) => `${flag} (${GRAVE_REASONS[reason]})`).join(', ');
162
+ const action = 'Llamar a la paciente para conseguirlo y avisar al médico';
163
+ return {
164
+ body: [
165
+ `❗ Falta dato grave · ${LEVEL_LABELS[clock.level]}`,
166
+ [`${patient} (${doctor})`, clock.symptom].filter(Boolean).join(' · '),
167
+ `Falta: ${missing}`,
168
+ `Qué hacer: ${action}`,
169
+ link,
170
+ ].join('\n'),
171
+ template: { 1: `${LEVEL_LABELS[clock.level]}, falta dato grave${clock.symptom ? ` (${clock.symptom})` : ''}`, 2: patient, 3: doctor, 4: `Falta: ${missing} · ${action}`, 5: link },
172
+ };
173
+ }
174
+
175
+ const sameEntry = (entry) => ({ flag: entry.flag, since: entry.since });
176
+ const setOn = (review, entry, fields, filter = {}) => getEscalationReview().updateOne(
177
+ { _id: review._id, graveAlerts: { $elemMatch: { ...sameEntry(entry), ...filter } } },
178
+ { $set: Object.fromEntries(Object.entries(fields).map(([key, value]) => [`graveAlerts.$.${key}`, value])) },
179
+ BOOKKEEPING,
180
+ );
181
+
182
+ // 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).
183
+ async function sendDueGraveAlerts(review, clock, entries, now) {
184
+ const due = entries.filter((entry) => !entry.sentAt && timeOf(entry.dueAt) <= now.getTime() && timeOf(entry.since) === clock.since.getTime());
185
+ // A datum held for the night is dropped once a current draft written after it no longer lists it as pending.
186
+ const { latest, flags } = pendingFlagsOf(review, clock.since);
187
+ const stillPending = new Set(flags.map(({ flag }) => flag));
188
+ const redrafted = latest && isDraftCurrent(review, latest);
189
+ const answered = (entry) => entry.reason === 'unanswered' && redrafted && timeOf(latest.createdAt) > timeOf(entry.at) && !stillPending.has(entry.flag);
190
+ for (const entry of due.filter(answered)) await setOn(review, entry, { sentAt: now, skippedReason: 'answered' }, { sentAt: null });
191
+ const pending = due.filter((entry) => !answered(entry));
192
+ if (!pending.length) return 0;
193
+
194
+ const taken = await takenOf(review, clock);
195
+ const message = await graveMessage(review, clock, pending);
196
+ const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
197
+ const sending = [];
198
+ for (const entry of pending) if ((await setOn(review, entry, { sentAt: now }, { sentAt: null })).modifiedCount) sending.push(entry);
199
+ if (!sending.length) return 0;
200
+ let delivered = 0;
201
+ try {
202
+ delivered = taken
203
+ ? Number((await sendGroupNotice(message.body, quoted)).delivered)
204
+ : (await sendTeamAlert({ message, operator: OPERATOR, quoted })).delivered;
205
+ } catch (error) {
206
+ logger.error('[CharacterizationOutcome] The grave alert was not sent', {
207
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
208
+ });
209
+ }
210
+ // Reaching no one releases the claim and tries again in five minutes, within the team day for urgent.
211
+ const retryAt = new Date(now.getTime() + GRAVE_RETRY_MS);
212
+ for (const entry of sending) {
213
+ await setOn(review, entry, delivered
214
+ ? { audience: taken ? 'group_doctor' : 'all', takenReason: taken, delivered }
215
+ : { sentAt: null, dueAt: BUSINESS_HOURS_LEVELS.includes(clock.level) ? teamOpenAt(retryAt, responseDeadlinePolicy()) : retryAt });
216
+ }
217
+ await audit(review, { action: 'grave_missing_alerted', urgencyLevel: clock.level, flags: sending.length, audience: taken ? 'group_doctor' : 'all', delivered });
218
+ return delivered ? sending.length : 0;
219
+ }
220
+
221
+ // In urgent, a patient who left the bot's question unanswered gets one reminder, held for the team day at night.
222
+ async function remindQuietPatient(review, clock, now) {
223
+ if (clock.level !== 'urgent' || !PRE_DECISION_STATUSES.includes(review.status) || review.closedAt) return;
224
+ const latest = (review.drafts ?? []).at(-1);
225
+ if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime()) return;
226
+ const pending = latest.sufficientForDoctor === false || pendingFlagsOf(review, clock.since).flags.length > 0;
227
+ if (!pending || (review.quietReminders ?? []).some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
228
+ const dueAt = teamOpenAt(new Date(timeOf(latest.createdAt) + quietReminderMinutes() * 60000), responseDeadlinePolicy());
229
+ if (now.getTime() < dueAt.getTime()) return;
230
+ // A short reply records no clinical update, so the patient's own messages decide whether she answered.
231
+ if (await countMessages({ numero: review.patientCode, from_me: false, createdAt: { $gt: latest.createdAt } })) return;
232
+
233
+ let skippedReason = null;
234
+ if (now.getTime() - dueAt.getTime() > QUIET_REMINDER_STALE_MS) skippedReason = 'stale';
235
+ else skippedReason = await takenOf(review, clock);
236
+ if (!skippedReason && !await isWithin24HourWindow(review.patientCode)) skippedReason = 'outside_window';
237
+ const entry = { draftAt: latest.createdAt, sentAt: now, skippedReason, delivered: null };
238
+ const claimed = await getEscalationReview().updateOne(
239
+ { _id: review._id, closedAt: null, status: { $in: PRE_DECISION_STATUSES }, quietReminders: { $not: { $elemMatch: { draftAt: latest.createdAt } } } },
240
+ { $push: { quietReminders: entry } },
241
+ BOOKKEEPING,
242
+ );
243
+ if (!claimed.modifiedCount || skippedReason) return;
244
+ let delivered = false;
245
+ try {
246
+ const result = await getMessaging().sendMessage({
247
+ code: review.patientCode, body: QUIET_REMINDER_TEXT, triggeredBy: OPERATOR, idempotencyKey: `quiet-reminder:${review._id}:${timeOf(latest.createdAt)}`,
248
+ });
249
+ delivered = Boolean(result?.success && !result?.deferred);
250
+ if (!delivered) skippedReason = result?.status ?? 'not_sent';
251
+ } catch (error) {
252
+ skippedReason = 'threw';
253
+ logger.error('[CharacterizationOutcome] The reminder to the patient was not sent', {
254
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
255
+ });
256
+ }
257
+ await getEscalationReview().updateOne(
258
+ { _id: review._id, quietReminders: { $elemMatch: { draftAt: latest.createdAt } } },
259
+ { $set: { 'quietReminders.$.delivered': delivered, 'quietReminders.$.skippedReason': skippedReason } },
260
+ BOOKKEEPING,
261
+ );
262
+ await audit(review, { action: delivered ? 'quiet_patient_reminded' : 'quiet_patient_reminder_failed', urgencyLevel: clock.level, reason: skippedReason });
263
+ }
264
+
265
+ // After the bot escalates: hands the case to the doctor once it is enough or the patient stopped answering, and tells the team.
266
+ async function settleCharacterization(review, clock, now) {
267
+ if (!clock) return;
268
+ const outcome = outcomeOf(review, clock, now);
269
+ const claimed = outcome?.grave.length ? await claimGraveAlerts(review, clock, outcome.grave, now) : [];
270
+ const attempts = attemptsOf(review, clock);
271
+ // Each failure doubles the wait; after the last attempt the team hands the case over by hand.
272
+ const backingOff = attempts >= MAX_HANDOFF_ATTEMPTS
273
+ || (attempts > 0 && now.getTime() - timeOf(review.autoHandoffFailedAt) < HANDOFF_RETRY_MS * 2 ** (attempts - 1));
274
+ if (outcome && !backingOff && await handOff(review, clock, outcome, now) && !outcome.grave.length) await sendHandoffNotice(review, clock, outcome);
275
+ await sendDueGraveAlerts(review, clock, [...(review.graveAlerts ?? []), ...claimed], now);
276
+ await remindQuietPatient(review, clock, now);
277
+ }
278
+
279
+ 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
 
@@ -1444,8 +1456,13 @@ async function generateBotDraft({ id, lease = null } = {}) {
1444
1456
  };
1445
1457
  const EscalationReview = getEscalationReview();
1446
1458
  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: '' } },
1459
+ {
1460
+ _id: review._id,
1461
+ ...(updating ? { status: 'awaiting_doctor', doctorHandoffs: { $size: review.doctorHandoffs.length } } : { status: { $in: DOCUMENTING_STATUSES } }),
1462
+ draftDueAt: { $lte: lease },
1463
+ drafts: { $size: (review.drafts ?? []).length },
1464
+ },
1465
+ { $push: { drafts: entry }, $set: { status: updating ? 'awaiting_doctor' : 'draft_ready', draftFailedAt: null }, $unset: { identityBlock: '' } },
1449
1466
  { new: true },
1450
1467
  ).lean();
1451
1468
  if (!saved) return { review: null, retry: false };
@@ -1653,7 +1670,7 @@ async function soleApprover() {
1653
1670
  return approvers[0];
1654
1671
  }
1655
1672
 
1656
- async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, requestId = null } = {}) {
1673
+ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, note = null, requestId = null } = {}) {
1657
1674
  const reviewId = reviewIdOf(id);
1658
1675
  const operator = requiredText(sentBy, 'sentBy');
1659
1676
  if (!HANDOFF_MODES.includes(mode)) throw httpError(400, `mode must be one of: ${HANDOFF_MODES.join(', ')}`);
@@ -1680,8 +1697,8 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
1680
1697
  if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
1681
1698
  const link = doctorLink(review);
1682
1699
  const message = {
1683
- body: renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link }),
1684
- template: { 1: identity.patientName, 2: identity.treatingDoctor, 3: templateSummary(review), 4: link },
1700
+ body: [note, renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link })].filter(Boolean).join('\n\n'),
1701
+ template: { 1: identity.patientName, 2: identity.treatingDoctor, 3: [templateSummary(review), note].filter(Boolean).join(' · '), 4: link },
1685
1702
  };
1686
1703
 
1687
1704
  const patientCaseRecordIds = await reviewCaseIds(review);
@@ -1757,7 +1774,10 @@ async function recordDoctorDecision({
1757
1774
  const allowedStatuses = isDraftless ? [...new Set([...DOCUMENTING_STATUSES, ...DECIDABLE_STATUSES])] : DECIDABLE_STATUSES;
1758
1775
  if (!allowedStatuses.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
1759
1776
  const handoff = review.status === 'awaiting_doctor' ? review.doctorHandoffs.at(-1) : null;
1760
- const draftNumber = handoff?.draftNumber ?? review.drafts.length;
1777
+ // The panel shows the latest draft, so a doctor deciding on a bot update not sent yet decides on that one.
1778
+ const onUnsentUpdate = handoff?.sentBy === AUTO_HANDOFF_OPERATOR && Number(seenDraftNumber) === review.drafts.length
1779
+ && review.drafts.at(-1)?.writtenBy === DRAFT_OPERATOR;
1780
+ const draftNumber = onUnsentUpdate ? review.drafts.length : handoff?.draftNumber ?? review.drafts.length;
1761
1781
  const draft = review.drafts[draftNumber - 1];
1762
1782
  if (!draft && !isDraftless) throw httpError(409, STATUS_CONFLICT);
1763
1783
  if (seenDraftNumber !== null && Number(seenDraftNumber) !== draftNumber) throw httpError(409, DRAFT_CHANGED);
@@ -2148,7 +2168,10 @@ async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {})
2148
2168
 
2149
2169
  module.exports = {
2150
2170
  BOOKKEEPING,
2171
+ AUTO_HANDOFF_OPERATOR,
2151
2172
  DOCUMENTING_STATUSES,
2173
+ DRAFT_OPERATOR,
2174
+ MAX_DOCTOR_UPDATES,
2152
2175
  FEVER_CATEGORY,
2153
2176
  appliedLevelOf,
2154
2177
  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 };
@@ -6,11 +6,14 @@ const RESPONSE_MINUTES = { stat: 15, asap: 60, urgent: 240, routine: 720 };
6
6
  const MAX_RESPONSE_MINUTES = 7 * 24 * 60;
7
7
  const BUSINESS_HOURS_LEVELS = ['urgent', 'routine'];
8
8
  const TEAM_TIMEZONE = 'America/Mexico_City';
9
- const DEFAULT_TEAM_HOURS = { days: [1, 2, 3, 4, 5, 6, 7], startHour: 9, endHour: 20 };
9
+ const DEFAULT_TEAM_HOURS = { days: [1, 2, 3, 4, 5, 6, 7], startHour: 9, endHour: 22 };
10
10
  const UNTAKEN_STAGES = { stat: ['deadline'], asap: ['early', 'half', 'deadline'], urgent: ['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.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.16341",
3
+ "version": "6.0.0-dev.16505",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",