@peopl-health/nexus 6.6.0-dev.20939 → 6.6.0-dev.21352

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.
@@ -23,6 +23,7 @@ const alarmSchema = new mongoose.Schema({
23
23
  urgencyLevel: { type: String, enum: URGENCY_LEVELS, required: true },
24
24
  category: { type: String, default: null },
25
25
  symptom: { type: String, default: null },
26
+ patientLabel: { type: String, default: null },
26
27
  evidenceQuote: { type: String, default: null },
27
28
  suspectedCondition: { type: String, default: null },
28
29
  recommendedAction: { type: String, default: null },
@@ -319,6 +320,7 @@ const caseFollowUpSchema = new mongoose.Schema({
319
320
  firstDueAt: { type: Date, required: true },
320
321
  nextCheckAt: { type: Date, default: null },
321
322
  unansweredAt: { type: Date, default: null },
323
+ unsettledAt: { type: Date, default: null },
322
324
  }, { _id: false });
323
325
 
324
326
  const escalationReviewSchema = new mongoose.Schema({
@@ -372,6 +374,7 @@ const escalationReviewSchema = new mongoose.Schema({
372
374
  monitoringUntil: { type: Date, default: null },
373
375
  watchNotices: { type: [watchNoticeSchema], default: [] },
374
376
  caseFollowUp: { type: caseFollowUpSchema, default: null },
377
+ staleQueueNoticeAt: { type: Date, default: null },
375
378
  blockingAsks: { type: [blockingAskSchema], default: [] },
376
379
  inTurnAsks: { type: [inTurnAskSchema], default: [] },
377
380
  feverPromptStartedAt: { type: Date, default: null },
@@ -4,6 +4,7 @@ const { logger } = require('../utils/logger');
4
4
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
5
5
  const { inlineOf, oneLineOf } = require('../utils/coercionUtils');
6
6
  const { DEFAULT_TIMEZONE, clampToHourWindow } = require('../utils/scheduleUtils');
7
+ const { getMexicoDayLabel } = require('../utils/dateUtils');
7
8
  const { getEscalationReview } = require('../models/escalationReviewModel');
8
9
  const { recordReminder, cancelFollowUp } = require('../clinical/services/clinicalAirtableService');
9
10
  const { escalationCaseFollowUpLive } = require('../clinical/flags/escalationFlags');
@@ -21,8 +22,15 @@ const SEND_WINDOW = { timeZone: DEFAULT_TIMEZONE, startHour: 11, endHour: 21 };
21
22
  const FOLLOW_UP_STATUSES = ['indications_sent', 'monitoring'];
22
23
  const BOOKKEEPING = { timestamps: false };
23
24
  const PLAN_EXCERPT = 400;
25
+ const PATIENT_LABEL_MAX = 40;
24
26
  // The follow-up template the send_reminder automation uses past the 24 h window (Airtable Monitoreo).
25
27
  const FOLLOW_UP_TEMPLATE_SID = 'HX182fee522708bdb43db5ea614f538369';
28
+ // Meta-approved UTILITY templates, by try and by whether she has a label: {{1}} name, {{2}} day she told us, {{3}} label.
29
+ const CASE_TEMPLATES = {
30
+ first: { label: 'HXe9ee7b7cdb018ca78970cd919342de4e', plain: 'HXb079b8c9892d963d1851addcce8b3c6e' },
31
+ retry: { label: 'HXb92572f8516f448c95257b933b123ab0', plain: 'HX6f19d545f6298f97c9d578a62ee2520c' },
32
+ };
33
+ const SENT_TEMPLATE_SIDS = [FOLLOW_UP_TEMPLATE_SID, ...Object.values(CASE_TEMPLATES).flatMap(Object.values)];
26
34
  // send_reminder fires up to 6 min before the row's time.
27
35
  const SEND_LEAD_MS = 10 * 60 * 1000;
28
36
 
@@ -38,34 +46,60 @@ function followUpOf(decision) {
38
46
  return { kind: 'auto', hours: AUTO_HOURS };
39
47
  }
40
48
 
41
- const symptomOf = (review) => inlineOf([...(review.alarms ?? [])].reverse().find((alarm) => inlineOf(alarm.symptom))?.symptom) || null;
49
+ const caseAlarmOf = (review) => [...(review.alarms ?? [])].reverse().find((alarm) => inlineOf(alarm.symptom)) || null;
50
+ const symptomOf = (review) => inlineOf(caseAlarmOf(review)?.symptom) || null;
51
+ const isPatientLabel = (label) => label.length > 0 && label.length <= PATIENT_LABEL_MAX && !/[\d():;+/%=<>≈→—–_]/.test(label);
52
+ const patientLabelOf = (review) => {
53
+ const label = oneLineOf(caseAlarmOf(review)?.patientLabel).replace(/^[¿¡\s]+|[.,¿?¡!\s]+$/g, '').toLowerCase();
54
+ return isPatientLabel(label) ? label : null;
55
+ };
42
56
  const dayOf = (value) => moment(value).tz(DEFAULT_TIMEZONE).format('DD/MM');
43
57
 
44
58
  function questionFor(review, attempt) {
45
- const about = symptomOf(review) ? ` con ${symptomOf(review).toLowerCase()}` : '';
46
- return attempt === 1
47
- ? `¿Cómo has seguido${about}? Cuéntame si vas mejor, igual o peor.`
48
- : `Quería saber cómo vas${about}. ¿Vas mejor, igual o peor?`;
59
+ const label = patientLabelOf(review);
60
+ if (attempt === 1) {
61
+ return label
62
+ ? `${label}. ¿Cómo te has sentido con eso estos días?`
63
+ : 'queremos saber cómo estás. ¿Cómo te has sentido desde entonces?';
64
+ }
65
+ return label
66
+ ? `${label}. Seguimos pendientes de ti. ¿Cómo sigues con eso?`
67
+ : 'seguimos pendientes de ti. ¿Cómo sigues?';
68
+ }
69
+
70
+ function templateFor(review, attempt, sendAt) {
71
+ const label = patientLabelOf(review);
72
+ const templates = attempt === 1 ? CASE_TEMPLATES.first : CASE_TEMPLATES.retry;
73
+ return {
74
+ templateSid: label ? templates.label : templates.plain,
75
+ templateVariables: { 2: getMexicoDayLabel(caseAlarmOf(review)?.raisedAt ?? review.createdAt, sendAt), ...(label && { 3: label }) },
76
+ };
49
77
  }
50
78
 
51
79
  function decisionContext(decision) {
52
80
  const what = decision.decision === 'monitor' ? 'el médico indicó vigilarlo en casa' : 'el médico le dio indicaciones';
53
81
  const sent = decision.plan ? oneLineOf(planSummary(decision.plan)) : oneLineOf(decision.finalText);
54
82
  const excerpt = sent && sent.length > PLAN_EXCERPT ? `${sent.slice(0, PLAN_EXCERPT)}…` : sent;
55
- return `el ${dayOf(decision.createdAt)} ${what}${excerpt ? ` («${excerpt}»)` : ''}`;
83
+ return `El ${dayOf(decision.createdAt)} ${what}${excerpt ? ` («${excerpt}»)` : ''}.`;
56
84
  }
57
85
 
58
86
  function caseInstruction(review, firstName) {
59
87
  const name = firstName || 'la paciente';
60
- const symptom = symptomOf(review)?.toLowerCase() || 'lo que te contó';
61
- const context = decisionContext(review.decisions.at(-1));
88
+ const about = patientLabelOf(review) || 'lo que te contó';
89
+ const note = symptomOf(review);
90
+ const internal = note ? `\n\nNota interna del equipo, solo para ti: «${note}». No la cites ni le pases sus grados, cifras, diagnósticos ni términos clínicos.` : '';
91
+ const how = 'Un solo mensaje breve, cálido y natural, de dos o tres frases. Nombra lo que siente con sus propias palabras de la conversación, nunca con las de la nota. Como mucho una frase de apoyo (por ejemplo «seguimos pendientes de ti»), sin dar por hecho que mejoró, sin prometer nada ni sugerir gravedad. Haz una sola pregunta abierta sobre cómo ha cambiado; no le des opciones como en una encuesta (nada de «mejor, igual o peor»). Tutéala con lenguaje neutro en género.';
92
+ const read = 'Con lo que conteste, entiende tú si va mejor, igual o peor; si no queda claro, repregúntale una sola vez de forma natural, comparando con hace unos días. Si va peor o cuenta algo nuevo, retómalo como cualquier síntoma.';
62
93
  const quiet = 'No menciones alertas, revisiones, el sistema ni que este mensaje estaba programado.';
94
+ const context = `${decisionContext(review.decisions.at(-1))}${internal}`;
63
95
  if (review.caseFollowUp.attempt > 1) {
64
- return `Le preguntaste a ${name} cómo seguía con ${symptom} (${context}) y no ha contestado. Escríbele una vez más, con un mensaje distinto al anterior, breve y cálido, para saber si va mejor, igual o peor. No le reproches que no contestó. ${quiet}`;
96
+ return `Le preguntaste a ${name} cómo seguía con ${about} y no ha contestado. ${context}
97
+
98
+ Escríbele una vez más, distinto al mensaje anterior y más corto. ${how} No le reproches que no contestó. ${read} ${quiet}`;
65
99
  }
66
- return `Toca darle seguimiento a ${name} por ${symptom}: ${context}.
100
+ return `Toca darle seguimiento a ${name} por ${about}. ${context}
67
101
 
68
- Revisa la conversación desde entonces. Si ya te contó cómo va, no se lo vuelvas a preguntar: si dijo que va peor, retómalo; si no, cierra en una línea breve y cálida. Si no lo ha dicho, pregúntale una sola vez, en un mensaje breve y natural, cómo ha seguido con ${symptom}: si va mejor, igual o peor. Si contesta algo poco claro, aclara eso antes de cerrar. ${quiet}`;
102
+ Revisa la conversación desde entonces. Si ya te contó cómo va, no se lo vuelvas a preguntar: si va peor, retómalo; si no, cierra en una línea breve y cálida. Si no lo ha dicho, pregúntaselo una sola vez. ${how} ${read} ${quiet}`;
69
103
  }
70
104
 
71
105
  async function standDown(code, reminderId, reason) {
@@ -77,9 +111,10 @@ async function standDown(code, reminderId, reason) {
77
111
  }
78
112
 
79
113
  async function writeRow(review, caseFollowUp) {
114
+ const template = templateFor(review, caseFollowUp.attempt, caseFollowUp.dueAt);
80
115
  const isRecorded = await recordReminder({
81
116
  code: review.patientCode, trace: null, actionType: 'create', reminderId: caseFollowUp.reminderId, reminderDateUtc: new Date(caseFollowUp.dueAt).toISOString(),
82
- reminderType: 'seguimiento', description: questionFor(review, caseFollowUp.attempt), expiresAtUtc: new Date(new Date(caseFollowUp.dueAt).getTime() + ROW_LIFETIME_MS).toISOString(),
117
+ reminderType: 'seguimiento', description: questionFor(review, caseFollowUp.attempt), ...template, expiresAtUtc: new Date(new Date(caseFollowUp.dueAt).getTime() + ROW_LIFETIME_MS).toISOString(),
83
118
  }).catch((error) => {
84
119
  logger.error('[CaseFollowUp] The follow-up row was not written', { escalationReviewId: String(review._id), error: errorOf(error) });
85
120
  return false;
@@ -167,7 +202,7 @@ async function askedAt(review, now = new Date()) {
167
202
  numero: review.patientCode,
168
203
  from_me: true,
169
204
  createdAt: { $gte: since, $lte: now },
170
- $or: [{ triggeredBy: { $regex: `^send_reminder:${PREFIX}${review._id}_` } }, { triggeredBy: 'send_reminder', content_sid: FOLLOW_UP_TEMPLATE_SID }],
205
+ $or: [{ triggeredBy: { $regex: `^send_reminder:${PREFIX}${review._id}_` } }, { triggeredBy: 'send_reminder', content_sid: { $in: SENT_TEMPLATE_SIDS } }],
171
206
  },
172
207
  { sort: { createdAt: 1 }, limit: 1, select: 'createdAt' },
173
208
  ) || [];
@@ -1,12 +1,12 @@
1
1
  const { logger } = require('../utils/logger');
2
2
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
3
  const { getEscalationReview } = require('../models/escalationReviewModel');
4
- const { escalationCaseFollowUpLive } = require('../clinical/flags/escalationFlags');
4
+ const { escalationCaseFollowUpLive, escalationStaleQueueNoticeLive } = require('../clinical/flags/escalationFlags');
5
5
 
6
6
  const { logPatientChange } = require('./patientService');
7
7
  const { getThreadInfo } = require('./threadService');
8
- const { BOOKKEEPING, closeEscalationReview } = require('./escalationReviewService');
9
- const { effectiveUrgencyOf } = require('./reviewDeadlineService');
8
+ const { BOOKKEEPING, closeEscalationReview, followUpReadingOf, noticeCaseThread } = require('./escalationReviewService');
9
+ const { effectiveUrgencyOf, positiveSetting } = require('./reviewDeadlineService');
10
10
  const { FOLLOW_UP_STATUSES, SECOND_TRY_MS, armCaseFollowUp, askedAt, lastReplyAt, rewriteRow } = require('./caseFollowUpService');
11
11
 
12
12
  const OPERATOR = 'bot:caseFollowUp';
@@ -15,6 +15,14 @@ const SWEEP_LIMIT = 50;
15
15
  const SETTLE_MS = 24 * 60 * 60 * 1000;
16
16
  const RECHECK_MS = 60 * 60 * 1000;
17
17
  const KEPT_OPEN_URGENCIES = ['stat', 'asap'];
18
+ const STALE_QUEUE_STATUSES = ['indications_queued', 'needs_intervention'];
19
+ const DEFAULT_STALE_QUEUE_HOURS = 72;
20
+ const HOUR_MS = 60 * 60 * 1000;
21
+ const STALE_QUEUE_LOOKBACK_MS = 7 * 24 * HOUR_MS;
22
+ const STALE_QUEUE_HEADERS = {
23
+ indications_queued: '⏳ Indicación en cola sin enviar desde hace días',
24
+ needs_intervention: '⏳ Caso que requiere intervención sin movimiento desde hace días',
25
+ };
18
26
 
19
27
  const errorOf = (error) => redactDirectIdentifiers(String(error?.message || error));
20
28
 
@@ -46,6 +54,23 @@ async function keepUnanswered(review, now) {
46
54
  if (kept.modifiedCount) await audit(review, { action: 'followup_result', result: 'unanswered' });
47
55
  }
48
56
 
57
+ async function settleAnswer(review, now) {
58
+ const { review: current, reading } = await followUpReadingOf(review);
59
+ if (reading === 'settled') return close(current, 'answered');
60
+ const held = await getEscalationReview().updateOne(
61
+ { _id: review._id, closedAt: null, status: { $in: FOLLOW_UP_STATUSES }, 'caseFollowUp.reminderId': review.caseFollowUp.reminderId, 'caseFollowUp.unsettledAt': null },
62
+ { $set: { 'caseFollowUp.unsettledAt': now, 'caseFollowUp.nextCheckAt': null, updatedSinceSeen: true } },
63
+ BOOKKEEPING,
64
+ );
65
+ if (!held.modifiedCount) return null;
66
+ await audit(review, { action: 'followup_result', result: 'answered_unsettled', reading });
67
+ return noticeCaseThread(review, {
68
+ header: '💬 La paciente contestó el seguimiento sin mejoría registrada',
69
+ action: 'Qué hacer: leer su respuesta y cerrar el caso o pedir una nueva indicación',
70
+ kind: 'followup_unsettled',
71
+ });
72
+ }
73
+
49
74
  async function settle(review, now) {
50
75
  const followUp = review.caseFollowUp;
51
76
  if ((await getThreadInfo(review.patientCode))?.stopped === true) return checkAgainAt(review, new Date(now.getTime() + RECHECK_MS));
@@ -54,7 +79,7 @@ async function settle(review, now) {
54
79
  const repliedAt = asked && await lastReplyAt(review.patientCode, asked, now);
55
80
  if (repliedAt) {
56
81
  const settleAt = new Date(repliedAt.getTime() + SETTLE_MS);
57
- return now < settleAt ? checkAgainAt(review, settleAt) : close(review, 'answered');
82
+ return now < settleAt ? checkAgainAt(review, settleAt) : settleAnswer(review, now);
58
83
  }
59
84
  const giveUpAt = new Date(new Date(followUp.dueAt).getTime() + SECOND_TRY_MS);
60
85
  if (now < giveUpAt) return checkAgainAt(review, giveUpAt);
@@ -86,4 +111,46 @@ async function sweepCaseFollowUps({ now = new Date() } = {}) {
86
111
  return settled;
87
112
  }
88
113
 
89
- module.exports = { sweepCaseFollowUps };
114
+ const LAST_DECISION_AT = { $arrayElemAt: ['$decisions.createdAt', -1] };
115
+
116
+ async function sweepStaleQueues({ now = new Date() } = {}) {
117
+ if (!escalationStaleQueueNoticeLive()) return 0;
118
+ const hours = positiveSetting('ESCALATION_STALE_QUEUE_HOURS', DEFAULT_STALE_QUEUE_HOURS);
119
+ const cutoff = new Date(now.getTime() - (hours * HOUR_MS < STALE_QUEUE_LOOKBACK_MS ? hours : DEFAULT_STALE_QUEUE_HOURS) * HOUR_MS);
120
+ const reviews = await getEscalationReview()
121
+ .find({
122
+ closedAt: null,
123
+ status: { $in: STALE_QUEUE_STATUSES },
124
+ 'decisions.0': { $exists: true },
125
+ $expr: { $and: [
126
+ { $lte: [LAST_DECISION_AT, cutoff] },
127
+ { $gt: [LAST_DECISION_AT, new Date(now.getTime() - STALE_QUEUE_LOOKBACK_MS)] },
128
+ { $or: [{ $eq: [{ $ifNull: ['$staleQueueNoticeAt', null] }, null] }, { $lt: ['$staleQueueNoticeAt', LAST_DECISION_AT] }] },
129
+ ] },
130
+ })
131
+ .limit(SWEEP_LIMIT)
132
+ .lean();
133
+ let noticed = 0;
134
+ for (const review of reviews) {
135
+ try {
136
+ const claimed = await getEscalationReview().updateOne(
137
+ { _id: review._id, closedAt: null, status: { $in: STALE_QUEUE_STATUSES }, staleQueueNoticeAt: review.staleQueueNoticeAt ?? null },
138
+ { $set: { staleQueueNoticeAt: now } },
139
+ BOOKKEEPING,
140
+ );
141
+ if (!claimed.modifiedCount) continue;
142
+ await noticeCaseThread(review, {
143
+ header: STALE_QUEUE_HEADERS[review.status],
144
+ action: 'Qué hacer: enviar la indicación o cerrar el caso desde el panel',
145
+ kind: 'stale_queue',
146
+ });
147
+ await audit(review, { action: 'stale_queue_noticed', status: review.status });
148
+ noticed += 1;
149
+ } catch (error) {
150
+ logger.error('[CaseFollowUpSweep] Could not notice a stale queued case', { escalationReviewId: String(review._id), error: errorOf(error) });
151
+ }
152
+ }
153
+ return noticed;
154
+ }
155
+
156
+ module.exports = { sweepCaseFollowUps, sweepStaleQueues };
@@ -0,0 +1,45 @@
1
+ const { Message } = require('../models/messageModel');
2
+ const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES: LANDED_STATUSES } = require('../models/deliveryAttemptModel');
3
+ const { botIsPaused } = require('../helpers/pausedThreadHelper');
4
+
5
+ async function freeformLandedElsewhere(messageDoc, body) {
6
+ const siblingMessages = await Message.find({
7
+ numero: messageDoc.numero,
8
+ _id: { $ne: messageDoc._id },
9
+ createdAt: { $gte: messageDoc.createdAt },
10
+ 'statusInfo.status': { $in: LANDED_STATUSES }
11
+ }, '_id').lean();
12
+
13
+ const landed = await DeliveryAttempt.findOne({
14
+ kind: 'freeform',
15
+ status: { $in: LANDED_STATUSES },
16
+ body,
17
+ messageId: { $in: [messageDoc._id, ...siblingMessages.map(m => m._id)] }
18
+ }, '_id').lean();
19
+
20
+ return Boolean(landed);
21
+ }
22
+
23
+ async function patientWroteSince(messageDoc) {
24
+ const inbound = await Message.findOne({
25
+ numero: messageDoc.numero,
26
+ from_me: false,
27
+ createdAt: { $gt: messageDoc.createdAt }
28
+ }, '_id').lean();
29
+ return Boolean(inbound);
30
+ }
31
+
32
+ async function freeformRetryBlockedReason(messageDoc, body) {
33
+ if (await freeformLandedElsewhere(messageDoc, body)) return 'already_sent';
34
+ if (await patientWroteSince(messageDoc)) return 'superseded_by_patient';
35
+ if (messageDoc.origin === 'assistant' && await botIsPaused(messageDoc.numero, { label: '[ChannelRetry]' })) return 'bot_paused';
36
+ return null;
37
+ }
38
+
39
+ async function scheduledRetryBlockedReason(scheduled) {
40
+ const parent = await Message.findById(scheduled.parentMessageId).lean();
41
+ if (!parent?.createdAt) return 'parent_missing';
42
+ return freeformRetryBlockedReason(parent, scheduled.message);
43
+ }
44
+
45
+ module.exports = { freeformRetryBlockedReason, scheduledRetryBlockedReason };
@@ -11,7 +11,7 @@ const { logPatientChange } = require('./patientService');
11
11
  const { getThreadInfo } = require('./threadService');
12
12
  const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES, PRE_DECISION_STATUSES, appliedLevelOf, caseTakenReason, currentAlarms, handOffToDoctor, teamAlertIdentity } = require('./escalationReviewService');
13
13
  const { graveMissingOf, isDraftCurrent, pendingFlagsOf, stillDocumented } = require('./gravePendingService');
14
- const { BUSINESS_HOURS_LEVELS, levelsOf, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
14
+ const { BUSINESS_HOURS_LEVELS, HANDOFF_TAKES_LEVELS, levelsOf, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
15
15
  const { sendGroupNotice, sendTeamAlert } = require('./teamAlertService');
16
16
  const { digestRecipient, digestTimeOf, urgentDigestLive } = require('./doctorDigestService');
17
17
 
@@ -22,7 +22,8 @@ const LEVEL_LABELS = { asap: 'ASAP', urgent: 'URGENT' };
22
22
  const HANDOFF_RETRY_MS = 10 * 60 * 1000;
23
23
  const MAX_HANDOFF_ATTEMPTS = 4;
24
24
  const MAX_NOTE_LENGTH = 200;
25
- const UPDATE_NOTE = 'Actualización: la paciente contestó';
25
+ // A redraft also follows a call note or the agent's own update, so the note does not say the patient answered.
26
+ const UPDATE_NOTE = 'Actualización del caso';
26
27
  const GRAVE_RETRY_MS = 5 * 60 * 1000;
27
28
  const GRAVE_REASONS = { unobtainable: 'no lo puede dar', unanswered: 'no contestó', not_said: 'no lo ha dicho' };
28
29
  const QUIET_REMINDER_TEXT = '¿Pudiste ver lo que te pregunté? Cuando puedas, respóndeme por aquí.';
@@ -63,8 +64,8 @@ function teamGraveOf(review, clock, grave, now) {
63
64
  .filter((ask) => timeOf(ask.draftAt) >= timeOf(firstSeenAt) && (ask.flags ?? []).map(normalizedKeyOf).includes(flag))
64
65
  .map((ask) => timeOf(ask.sentAt)),
65
66
  );
66
- const dueAt = (entry) => (entry.reason === 'unobtainable' ? -Infinity : askedAt(entry) + waitMs);
67
- // A datum the bot never asked about calls no one: it reaches the doctor in the note.
67
+ const dueAt = (entry) => (entry.reason === 'unobtainable' ? Infinity : askedAt(entry) + waitMs);
68
+ // A datum the bot never asked about, or one the patient cannot give, calls no one: it reaches the doctor in the note.
68
69
  const asked = grave.filter((entry) => dueAt(entry) < Infinity);
69
70
  if (asked.some((entry) => dueAt(entry) <= now.getTime())) return { due: asked, waiting: [] };
70
71
  return { due: [], waiting: asked };
@@ -112,7 +113,7 @@ function outcomeOf(review, clock, now) {
112
113
  const teamFirst = !update && !present.length && grave.length + waiting.length > 0;
113
114
  const held = teamFirst && (waiting.length > 0 || grave.some(({ flag }) => now.getTime() < graveDueAt(review, clock, flag) + wait * 60000));
114
115
  if (graveFlags.length || present.length) {
115
- const lacking = graveFlags.length && `Falta dato grave: ${graveFlags.map(({ flag }) => flag).join(', ')}${teamFirst && !held ? ' (no se consiguió)' : ''}`;
116
+ const lacking = graveFlags.length && `Falta dato grave: ${graveFlags.map(({ flag, reason }) => (reason === 'unobtainable' ? `${flag} (${GRAVE_REASONS.unobtainable})` : flag)).join(', ')}${teamFirst && !held ? ' (no se consiguió)' : ''}`;
116
117
  // A grave datum still inside its wait goes in the note too, so the doctor knows it is still open.
117
118
  const pending = pendingFlagsOf(review, clock.since).flags.map(({ flag }) => flag).filter((flag) => !graveFlags.some((entry) => entry.flag === flag));
118
119
  const note = [present.length && `Bandera grave presente: ${present.join(', ')}`, lacking, pending.length && `Pendiente: ${pending.join(', ')}`];
@@ -247,7 +248,7 @@ async function sendGaveUpNotice(review, clock) {
247
248
 
248
249
  async function postHandoffNotice(review, clock, { note }, queuedAt) {
249
250
  const { patient, doctor, link } = await teamAlertIdentity(review);
250
- const taken = await takenOf(review, clock);
251
+ const taken = (HANDOFF_TAKES_LEVELS.includes(clock.level) && !queuedAt) || await takenOf(review, clock);
251
252
  const passed = queuedAt ? `📋 Va al médico en el resumen de urgentes (a más tardar ${digestTimeOf(review, queuedAt)})` : '📋 Pasó al médico';
252
253
  const header = taken ? passed : `${passed} · todavía sin tomar`;
253
254
  const action = !taken && 'Qué hacer: escribir o llamar a la paciente si nadie lo ha hecho';
@@ -354,7 +355,7 @@ async function remindQuietPatient(review, clock, now) {
354
355
  const latest = (review.drafts ?? []).at(-1);
355
356
  if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime()) return;
356
357
  const pending = !latest.urgentPresentRedFlags?.length && (latest.sufficientForDoctor === false || pendingFlagsOf(review, clock.since).flags.length > 0);
357
- if (!pending || (review.quietReminders ?? []).some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
358
+ if (!pending || (review.quietReminders ?? []).some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt) || (!entry.skippedReason && timeOf(entry.draftAt) >= clock.since.getTime()))) return;
358
359
  const dueAt = teamOpenAt(new Date(timeOf(latest.createdAt) + quietReminderMinutes() * 60000), responseDeadlinePolicy());
359
360
  if (now.getTime() < dueAt.getTime() || now.getTime() - lastAskAt(review, clock) < ASK_SPACING_MS) return;
360
361
  // A short reply records no clinical update, so the patient's own messages decide whether she answered.
@@ -4,7 +4,7 @@ const { FOLLOWUP_STATUSES } = require('../models/escalationReviewModel');
4
4
  const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
5
5
  const { escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
6
6
 
7
- const { DRAFT_OPERATOR, PRE_DECISION_STATUSES, caseTakenReason } = require('./escalationReviewService');
7
+ const { DRAFT_OPERATOR, PRE_DECISION_STATUSES, caseTakenBy, caseTakenReason } = require('./escalationReviewService');
8
8
  const { graveMissingOf, isDraftCurrent } = require('./gravePendingService');
9
9
  const { pendingWaitMinutes } = require('./reviewDeadlineService');
10
10
  const { dueStageOf, untakenClockOf } = require('./untakenAlertService');
@@ -14,7 +14,7 @@ const DONE_STATUSES = ['closed', 'cancelled'];
14
14
  const ANSWERABLE_OUTCOMES = ['sent', 'unknown'];
15
15
  const timeOf = (value) => new Date(value).getTime();
16
16
 
17
- const state = (key, label, fields = {}) => ({ key, label, since: null, dueAt: null, nextAlert: null, takenReason: null, graveFlags: [], ...fields });
17
+ const state = (key, label, fields = {}) => ({ key, label, since: null, dueAt: null, nextAlert: null, takenReason: null, takenBy: null, graveFlags: [], ...fields });
18
18
 
19
19
  // The stage the sweep sends on its next tick, else the next one still to come; none while untaken alerts are off.
20
20
  function nextAlertOf(review, clock, now) {
@@ -37,7 +37,13 @@ function waitingOn(review, clock, now) {
37
37
 
38
38
  async function takenOf(review, clock) {
39
39
  try {
40
- return await caseTakenReason(review, clock.since, clock.level);
40
+ const reason = await caseTakenReason(review, clock.since, clock.level);
41
+ if (!reason) return null;
42
+ const by = await caseTakenBy(review, clock.since, reason).catch((error) => {
43
+ logger.warn('[EscalationCaseState] Could not tell who took the case', { escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)) });
44
+ return null;
45
+ });
46
+ return { reason, by };
41
47
  } catch (error) {
42
48
  logger.warn('[EscalationCaseState] Could not tell whether the case was taken', {
43
49
  escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
@@ -56,7 +62,7 @@ async function caseStateOf(review, { now = new Date(), policy } = {}) {
56
62
 
57
63
  const nextAlert = nextAlertOf(review, clock, now);
58
64
  const taken = await takenOf(review, clock);
59
- if (taken) return state('taken', 'Tomado', { since: clock.since, takenReason: taken });
65
+ if (taken) return state('taken', 'Tomado', { since: clock.since, takenReason: taken.reason, takenBy: taken.by });
60
66
  const grave = graveMissingOf(review, clock, now).map(({ flag }) => flag);
61
67
  if (grave.length) return state('grave_missing', 'Falta dato grave', { since: clock.since, nextAlert, graveFlags: grave });
62
68
  if (WITH_DOCTOR_STATUSES.includes(review.status)) return state('with_doctor', label, { since: clock.since, nextAlert });
@@ -57,7 +57,7 @@ const { armCaseFollowUp, cancelCaseFollowUp } = require('./caseFollowUpService')
57
57
 
58
58
  const { getPatientInformation, logPatientChange } = require('./patientService');
59
59
  const { MAX_NOTE_LENGTH, openCaseIds, readPatientCases, updatePatientTask } = require('./patientTaskService');
60
- const { countMessages } = require('./messageService');
60
+ const { countMessages, getMessages } = require('./messageService');
61
61
  const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
62
62
  const { createPrescription } = require('./prescriptionService');
63
63
  const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
@@ -72,6 +72,8 @@ const RECENT_REVIEW_LIMIT = 20;
72
72
  const TIMELINE_LIMIT = 500;
73
73
  const MAX_REVIEW_UPDATES = 50;
74
74
  const DRAFT_DEBOUNCE_MS = 20 * 1000;
75
+ // Long enough for the agent's own turn to finish, so a patient reply is drafted once.
76
+ const INBOUND_DRAFT_DELAY_MS = 90 * 1000;
75
77
  const DRAFT_OPERATOR = 'bot:escalationDraft';
76
78
  const AUTO_HANDOFF_OPERATOR = 'bot:characterizationOutcome';
77
79
  const MAX_DOCTOR_UPDATES = 3;
@@ -87,6 +89,7 @@ const PREVIOUS_REVIEW_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
87
89
  const DUPLICATE_KEY_ERROR = 11000;
88
90
  const HANDING_OFF_WAIT_MS = 3000;
89
91
  const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
92
+ const REFRESHABLE_STATUSES = [...FOLLOWUP_STATUSES, 'needs_intervention'];
90
93
  const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
91
94
  const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
92
95
  const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'monitoring', 'needs_intervention'];
@@ -1105,29 +1108,54 @@ async function takenReason(review, since, timer, ownStart = null) {
1105
1108
  return caseTakenReason(review, from, timer.level);
1106
1109
  }
1107
1110
 
1111
+ const levelsAtOf = (review) => {
1112
+ const changes = review.urgencyReclassifications ?? [];
1113
+ return (at) => levelsOf(currentAlarms(review).filter((alarm) => new Date(alarm.raisedAt) <= new Date(at)), changes.filter((change) => new Date(change.at) < new Date(at)), appliedLevelOf);
1114
+ };
1115
+
1116
+ // A lowering means someone looked at the case; a raise restarts the clock instead.
1117
+ const isLoweringOf = (review) => {
1118
+ const levelsAt = levelsAtOf(review);
1119
+ return (change) => (URGENCY_RANK[change.toLevel] || 0) < Math.max(0, ...levelsAt(change.at).map((entry) => URGENCY_RANK[entry.level] || 0));
1120
+ };
1121
+
1122
+ // Staff sign with their email; automations (the timer itself included) sign with a name and never count.
1123
+ const staffReplyFilter = (review, from) => ({ ...humanReplyFilter(review.patientCode, from), origin: { $in: STAFF_ORIGINS }, $and: [{ triggeredBy: /@/ }] });
1124
+
1125
+ const atOrAfterOf = (from) => (at) => at != null && new Date(at).getTime() >= from.getTime();
1126
+
1127
+ const takingDecisionOf = (review, from) => (review.decisions ?? []).find((decision) => atOrAfterOf(from)(decision.createdAt));
1128
+ const takingLoweringOf = (review, from) => {
1129
+ const isLowering = isLoweringOf(review);
1130
+ return (review.urgencyReclassifications ?? []).find((change) => atOrAfterOf(from)(change.at) && isLowering(change));
1131
+ };
1132
+ const takingCallOf = (review, from) => (review.callLogs ?? []).find((call) => call.outcome === 'contacted' && atOrAfterOf(from)(call.calledAt));
1133
+
1108
1134
  // What says the team took the case from `from` on, for a case timed at `level`.
1109
1135
  async function caseTakenReason(review, from, level) {
1110
- const atOrAfter = (at) => at != null && new Date(at).getTime() >= from.getTime();
1111
- if ((review.decisions ?? []).some((decision) => atOrAfter(decision.createdAt))) return 'decision';
1112
- const changes = review.urgencyReclassifications ?? [];
1113
- const levelsAt = (at) => levelsOf(currentAlarms(review).filter((alarm) => new Date(alarm.raisedAt) <= new Date(at)), changes.filter((change) => new Date(change.at) < new Date(at)), appliedLevelOf);
1114
- if (level !== 'stat' && levelsAt(new Date(8.64e15)).some((entry) => entry.level === 'stat')) return 'stat_alarm';
1115
- // A lowering means someone looked at the case; a raise restarts the clock instead.
1116
- const lowered = (change) => (URGENCY_RANK[change.toLevel] || 0) < Math.max(0, ...levelsAt(change.at).map((entry) => URGENCY_RANK[entry.level] || 0));
1117
- if (changes.some((change) => atOrAfter(change.at) && lowered(change))) return 'reclassified';
1118
- if ((review.callLogs ?? []).some((call) => call.outcome === 'contacted' && atOrAfter(call.calledAt))) return 'call_contacted';
1136
+ if (takingDecisionOf(review, from)) return 'decision';
1137
+ if (level !== 'stat' && levelsAtOf(review)(new Date(8.64e15)).some((entry) => entry.level === 'stat')) return 'stat_alarm';
1138
+ if (takingLoweringOf(review, from)) return 'reclassified';
1139
+ if (takingCallOf(review, from)) return 'call_contacted';
1119
1140
  // A read error goes back to the sweep to retry; only a thread that does not exist (no turn to run
1120
1141
  // anyway) skips the prompt.
1121
1142
  const thread = await getThreadInfo(review.patientCode, { rethrow: true });
1122
1143
  if (!thread) return 'thread_missing';
1123
1144
  if (thread.stopped === true) return 'thread_paused';
1124
1145
  if (thread.hospitalizedAt) return 'patient_hospitalized';
1125
- // Staff write from the platform or act through add-instruction / add-msg, always under their email;
1126
- // automations (the timer itself included) sign with a name and never count.
1127
- const staffMessages = await countMessages({ ...humanReplyFilter(review.patientCode, from), origin: { $in: STAFF_ORIGINS }, $and: [{ triggeredBy: /@/ }] });
1146
+ const staffMessages = await countMessages(staffReplyFilter(review, from));
1128
1147
  return staffMessages ? 'staff_message' : null;
1129
1148
  }
1130
1149
 
1150
+ async function caseTakenBy(review, from, reason) {
1151
+ if (reason === 'decision') return takingDecisionOf(review, from)?.recordedBy ?? null;
1152
+ if (reason === 'reclassified') return takingLoweringOf(review, from)?.reclassifiedBy ?? null;
1153
+ if (reason === 'call_contacted') return takingCallOf(review, from)?.loggedBy ?? null;
1154
+ if (reason !== 'staff_message') return null;
1155
+ const [first] = await getMessages(staffReplyFilter(review, from), { select: 'triggeredBy', sort: { createdAt: 1 }, limit: 1 });
1156
+ return first?.triggeredBy ?? null;
1157
+ }
1158
+
1131
1159
  async function armPatientTimerOnJoin(review, alarm, now) {
1132
1160
  try {
1133
1161
  const level = appliedLevelOf(alarm);
@@ -1498,12 +1526,12 @@ async function closeSettled(review) {
1498
1526
  }
1499
1527
  }
1500
1528
 
1501
- async function settleFollowUp(snapshot, { background = true, canClose = true } = {}) {
1529
+ async function followUpReadingOf(snapshot) {
1502
1530
  const since = (snapshot.decisions ?? []).at(-1)?.createdAt;
1503
- if (!since) return snapshot;
1531
+ if (!since) return { review: snapshot, reading: null };
1504
1532
  const sinceMs = new Date(since).getTime();
1505
1533
  const { review, known } = await followUpCasesOf(snapshot, sinceMs);
1506
- if (!known.size) return review;
1534
+ if (!known.size) return { review, reading: null };
1507
1535
 
1508
1536
  const latest = new Map();
1509
1537
  (review.updates ?? []).filter((entry) => new Date(entry.at).getTime() > sinceMs)
@@ -1512,9 +1540,16 @@ async function settleFollowUp(snapshot, { background = true, canClose = true } =
1512
1540
  .filter((impression) => known.has(impression.caseId) && readingOf(impression))
1513
1541
  .forEach((impression) => latest.set(impression.caseId, readingOf(impression))));
1514
1542
 
1515
- if ([...latest.values()].includes('worsening')) return reopenFromFollowUp(review, 'worsening', { background });
1543
+ if ([...latest.values()].includes('worsening')) return { review, reading: 'worsening' };
1516
1544
  const settled = [...known].every((caseId) => SETTLED_TRAJECTORIES.includes(latest.get(caseId)));
1517
- if (!settled || !canClose || !SETTLEABLE_STATUSES.includes(review.status)) {
1545
+ return { review, reading: settled ? 'settled' : 'unsettled' };
1546
+ }
1547
+
1548
+ async function settleFollowUp(snapshot, { background = true, canClose = true } = {}) {
1549
+ const { review, reading } = await followUpReadingOf(snapshot);
1550
+ if (!reading) return review;
1551
+ if (reading === 'worsening') return reopenFromFollowUp(review, 'worsening', { background });
1552
+ if (reading !== 'settled' || !canClose || !SETTLEABLE_STATUSES.includes(review.status)) {
1518
1553
  await getEscalationReview().updateOne({ _id: review._id }, { $set: { updatedSinceSeen: true } });
1519
1554
  return review;
1520
1555
  }
@@ -1536,13 +1571,14 @@ async function generateBotDraft({ id, lease = null } = {}) {
1536
1571
  const startedAt = new Date();
1537
1572
  const review = await loadReview(reviewIdOf(id));
1538
1573
  const updating = updatesDoctor(review);
1539
- if (review.closedAt || (!DOCUMENTING_STATUSES.includes(review.status) && !updating)) return { review: null, retry: false };
1574
+ const refreshing = REFRESHABLE_STATUSES.includes(review.status);
1575
+ if (review.closedAt || (!DOCUMENTING_STATUSES.includes(review.status) && !updating && !refreshing)) return { review: null, retry: false };
1540
1576
  const latest = (review.drafts ?? []).at(-1);
1541
1577
  if (latest && latest.writtenBy !== DRAFT_OPERATOR) return { review: null, retry: false };
1542
1578
 
1543
1579
  const identity = await readDoctorIdentity(review);
1544
1580
  if (identity.missing.length) {
1545
- if (!review.identityBlock) await blockForMissingIdentity({ review, missing: identity.missing, operator: DRAFT_OPERATOR });
1581
+ if (!review.identityBlock && !refreshing) await blockForMissingIdentity({ review, missing: identity.missing, operator: DRAFT_OPERATOR });
1546
1582
  return { review: null, retry: false };
1547
1583
  }
1548
1584
 
@@ -1552,6 +1588,7 @@ async function generateBotDraft({ id, lease = null } = {}) {
1552
1588
  alarms: review.alarms ?? [],
1553
1589
  agentCharacterization: characterizationSeedOf(review.updates),
1554
1590
  heldUrgentFlags: review.drafts?.at(-1)?.urgentUnassessedRedFlags ?? [],
1591
+ previousQuestions: latest ? { keyQuestions: latest.keyQuestions ?? [], missingCharacterization: latest.missingCharacterization ?? [], urgentUnassessedRedFlags: latest.urgentUnassessedRedFlags ?? [] } : null,
1555
1592
  reviewId: String(review._id),
1556
1593
  });
1557
1594
  if (draft.attempted) {
@@ -1584,14 +1621,17 @@ async function generateBotDraft({ id, lease = null } = {}) {
1584
1621
  ...(draft.symptoms?.length && { symptoms: draft.symptoms }),
1585
1622
  };
1586
1623
  const EscalationReview = getEscalationReview();
1624
+ const stage = (updating && { status: 'awaiting_doctor', doctorHandoffs: { $size: review.doctorHandoffs.length } })
1625
+ || (refreshing && { status: review.status })
1626
+ || { status: { $in: DOCUMENTING_STATUSES } };
1587
1627
  const saved = await EscalationReview.findOneAndUpdate(
1588
1628
  {
1589
1629
  _id: review._id,
1590
- ...(updating ? { status: 'awaiting_doctor', doctorHandoffs: { $size: review.doctorHandoffs.length } } : { status: { $in: DOCUMENTING_STATUSES } }),
1630
+ ...stage,
1591
1631
  draftDueAt: { $lte: lease },
1592
1632
  drafts: { $size: (review.drafts ?? []).length },
1593
1633
  },
1594
- { $push: { drafts: entry }, $set: { status: updating ? 'awaiting_doctor' : 'draft_ready', draftFailedAt: null }, $unset: { identityBlock: '' } },
1634
+ { $push: { drafts: entry }, $set: { status: updating || refreshing ? review.status : 'draft_ready', draftFailedAt: null }, $unset: { identityBlock: '' } },
1595
1635
  { new: true },
1596
1636
  ).lean();
1597
1637
  if (!saved) return { review: null, retry: false };
@@ -2143,6 +2183,29 @@ async function recordPatientSend({ code, channel, sentBy, text, messageId = null
2143
2183
  }
2144
2184
  }
2145
2185
 
2186
+ async function noteIncomingPatientMessage({ code, now = new Date() } = {}) {
2187
+ try {
2188
+ if (!PATIENT_CODE.test(String(code ?? ''))) return false;
2189
+ const due = new Date(now.getTime() + INBOUND_DRAFT_DELAY_MS);
2190
+ const { modifiedCount } = await getEscalationReview().updateOne(
2191
+ {
2192
+ patientCode: patientCodeOf(code),
2193
+ closedAt: null,
2194
+ status: { $in: [...DOCUMENTING_STATUSES, ...REFRESHABLE_STATUSES] },
2195
+ draftDueAt: { $not: { $lte: due } },
2196
+ },
2197
+ { $set: { draftDueAt: due, draftAttempts: 0, updatedSinceSeen: true } },
2198
+ BOOKKEEPING,
2199
+ );
2200
+ return modifiedCount > 0;
2201
+ } catch (error) {
2202
+ logger.error('[EscalationReview] A patient reply could not arm a redraft of the open review', {
2203
+ error: redactedError(error), stack: redactedStack(error),
2204
+ });
2205
+ return false;
2206
+ }
2207
+ }
2208
+
2146
2209
  const latestUpdateGuard = (review) => {
2147
2210
  const updates = review.updates ?? [];
2148
2211
  if (!updates.length) return { 'updates.0': { $exists: false } };
@@ -2545,6 +2608,7 @@ module.exports = {
2545
2608
  _resetEscalationReviewIndexes,
2546
2609
  addCallLog,
2547
2610
  remindDoctorOfCase,
2611
+ caseTakenBy,
2548
2612
  caseTakenReason,
2549
2613
  promptedSince,
2550
2614
  currentAlarms,
@@ -2557,6 +2621,7 @@ module.exports = {
2557
2621
  attachEmergencyRow,
2558
2622
  cancelEscalationReview,
2559
2623
  closeEscalationReview,
2624
+ followUpReadingOf,
2560
2625
  escalationAnchorOf,
2561
2626
  generateBotDraft,
2562
2627
  getEscalationReviewById,
@@ -2564,11 +2629,14 @@ module.exports = {
2564
2629
  previewPlanInstructions,
2565
2630
  handOffToDoctor,
2566
2631
  listEscalationReviews,
2632
+ noticeCaseThread,
2567
2633
  openEscalationReview,
2568
2634
  reclassifyUrgency,
2569
2635
  recordEscalationAlarm,
2570
2636
  recordDirectIndication,
2571
2637
  recordPatientSend,
2638
+ noteIncomingPatientMessage,
2639
+ REFRESHABLE_STATUSES,
2572
2640
  recordDoctorDecision,
2573
2641
  sendScheduledDoctorAlert,
2574
2642
  recordReviewUpdate,