@peopl-health/nexus 5.56.18 → 5.56.21

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.
@@ -8,7 +8,12 @@ function isConversationalDraftReuseLive() {
8
8
  return runtimeConfig.get('CONVERSATIONAL_DRAFT_REUSE_ENABLED', 'true') === 'true';
9
9
  }
10
10
 
11
+ function isDeclarationModelCheckLive() {
12
+ return runtimeConfig.get('DECLARATION_MODEL_CHECK_ENABLED', 'true') === 'true';
13
+ }
14
+
11
15
  module.exports = {
12
16
  isConversationalDeclarationLive,
13
17
  isConversationalDraftReuseLive,
18
+ isDeclarationModelCheckLive,
14
19
  };
@@ -13,6 +13,7 @@ const FIELD_LABELS = {
13
13
  medicacion_actual: 'Medicación',
14
14
  alergias_medicamentos: 'Alergias',
15
15
  comorbilidades: 'Comorbilidades',
16
+ episodios_intercurrentes: 'Episodios',
16
17
  };
17
18
 
18
19
  const FIELD_VARIABLES = Object.freeze({
@@ -21,6 +22,7 @@ const FIELD_VARIABLES = Object.freeze({
21
22
  medicacion_actual: Object.freeze(['other_meds_summary']),
22
23
  alergias_medicamentos: Object.freeze(['allergies_list']),
23
24
  comorbilidades: Object.freeze(['comorbidities_summary']),
25
+ episodios_intercurrentes: Object.freeze(['intercurrent_events_summary']),
24
26
  });
25
27
 
26
28
  const AGE_EXTENSION_SUFFIX = 'patient-age';
@@ -53,10 +53,13 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
53
53
  getExtractor(),
54
54
  ]);
55
55
 
56
- const flags = new Set(detectSafetyFlags(text || '', patterns));
56
+ const regexFlags = detectSafetyFlags(text || '', patterns);
57
+ const flags = new Set(regexFlags);
58
+ const modelFlags = new Set();
59
+ const sources = () => ({ regex: [...regexFlags], model: [...modelFlags] });
57
60
 
58
61
  if (!text || !text.trim() || !presetId || !provider?.runStructured) {
59
- return { completed: false, clinicalMentions: [], safetyFlags: [...flags] };
62
+ return { completed: false, clinicalMentions: [], safetyFlags: [...flags], safetyFlagSources: sources() };
60
63
  }
61
64
 
62
65
  try {
@@ -81,21 +84,32 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
81
84
  const parsed = safeParse(outputText, null);
82
85
  if (outputText && outputText.trim() && parsed === null) {
83
86
  logger.warn('[clinicalExtraction] model output did not parse as JSON; no mentions extracted', { turnId });
84
- return { completed: false, clinicalMentions: [], safetyFlags: [...flags] };
87
+ return { completed: false, clinicalMentions: [], safetyFlags: [...flags], safetyFlagSources: sources() };
85
88
  }
86
- const rawMentions = Array.isArray(parsed?.mentions) ? parsed.mentions : [];
89
+ const wellFormed = Array.isArray(parsed?.mentions);
90
+ const rawMentions = wellFormed ? parsed.mentions : [];
87
91
 
88
92
  const now = new Date().toISOString();
89
93
  const clinicalMentions = [];
90
94
  const pendingMentions = [];
91
95
  let unanchored = 0;
96
+ let unusable = 0;
92
97
  let forcedPending = 0;
93
98
  rawMentions.forEach((raw, index) => {
94
- if (!raw || typeof raw !== 'object') return;
95
- for (const f of raw.safety_flags || []) flags.add(f);
99
+ if (!raw || typeof raw !== 'object') {
100
+ unusable += 1;
101
+ return;
102
+ }
103
+ for (const f of raw.safety_flags || []) {
104
+ flags.add(f);
105
+ modelFlags.add(f);
106
+ }
96
107
  const options = { code, turnId, index, now, intakeSource, responseFormat, spanishByTerm };
97
108
  let mention = toClinicalMention(raw, options);
98
- if (!mention) return;
109
+ if (!mention) {
110
+ unusable += 1;
111
+ return;
112
+ }
99
113
  const quotes = mention.provenance.verbatimQuotes;
100
114
  if (!quotes.some((quote) => isQuoteAnchored(quote, text))) {
101
115
  unanchored += 1;
@@ -136,10 +150,13 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
136
150
  pendingMentions,
137
151
  askAgenda: buildAskAgenda({ pendingMentions, contextGaps, safetyFlags: [...flags] }),
138
152
  safetyFlags: [...flags],
153
+ safetyFlagSources: sources(),
154
+ wellFormed,
155
+ discardedMentions: unanchored + unusable,
139
156
  };
140
157
  } catch (err) {
141
158
  logger.error('[clinicalExtraction] extraction failed; returning deterministic safety flags only', { turnId, error: err?.message });
142
- return { completed: false, clinicalMentions: [], safetyFlags: [...flags] };
159
+ return { completed: false, clinicalMentions: [], safetyFlags: [...flags], safetyFlagSources: sources() };
143
160
  }
144
161
  }
145
162
 
@@ -6,7 +6,7 @@ const { projectClinicalFacts, renderClinicalIntakeSummary } = require('../helper
6
6
  const { extractClinicalMentions, getConversationalTokens } = require('../services/clinicalExtractionService');
7
7
  const { recordClinicalIntake } = require('../services/clinicalAirtableService');
8
8
  const { getCtcaeCatalog } = require('../stores/CtcaeCatalog');
9
- const { isConversationalDeclarationLive } = require('../flags/turnEfficiencyFlags');
9
+ const { isConversationalDeclarationLive, isDeclarationModelCheckLive } = require('../flags/turnEfficiencyFlags');
10
10
  const { logger } = require('../../utils/logger');
11
11
 
12
12
  const DETECTED_TAG_ENUM = [
@@ -15,6 +15,7 @@ const DETECTED_TAG_ENUM = [
15
15
  ];
16
16
  const NON_CLINICAL_REQUESTS = ['external_booking'];
17
17
  const CONVERSATIONAL_REQUEST = 'conversational';
18
+ const CATEGORIES_A_DECLARATION_CARRIES = { external_booking: ['appointment'] };
18
19
 
19
20
  function declarableRequests() {
20
21
  return isConversationalDeclarationLive() ? [...NON_CLINICAL_REQUESTS, CONVERSATIONAL_REQUEST] : NON_CLINICAL_REQUESTS;
@@ -150,9 +151,19 @@ async function handler(args, context = {}) {
150
151
  if (declaredRequest && trace?.signals?.clinicalFactsExtracted) {
151
152
  return JSON.stringify({ success: false, error: 'This turn already extracted clinical facts, so it cannot be declared a non-clinical request. Continue the clinical workflow those facts require.' });
152
153
  }
154
+ if (declaredRequest && isDeclarationModelCheckLive()) {
155
+ return declareNonClinical({ declaredRequest, rawMessage, intakeSource, priorTurns, runtime, trace });
156
+ }
153
157
  const scannedFlags = await scanSafetyFlags(rawMessage);
154
158
  const safetyFlags = scannedFlags || [];
155
- if (trace?.setSignals) trace.setSignals({ clinicalIntakeCompleted: false, clinicalMentions: [], safetyFlags });
159
+ if (trace?.setSignals) {
160
+ trace.setSignals({
161
+ clinicalIntakeCompleted: false,
162
+ clinicalMentions: [],
163
+ safetyFlags,
164
+ safetyFlagSources: scannedFlags ? { regex: scannedFlags, model: [] } : null,
165
+ });
166
+ }
156
167
 
157
168
  const providerDecision = trace?.signals?.clinicalIntakeDecisionRequired;
158
169
  let conversationalInbound = providerDecision === false;
@@ -203,7 +214,7 @@ async function handler(args, context = {}) {
203
214
  provider: requireGatewayProvider(),
204
215
  trace,
205
216
  });
206
- const { clinicalMentions, safetyFlags, askAgenda = null } = extraction;
217
+ const { clinicalMentions, safetyFlags, safetyFlagSources = null, askAgenda = null } = extraction;
207
218
  const pendingMentions = extraction.pendingMentions || [];
208
219
  const intakeCompleted = extraction.completed !== false;
209
220
 
@@ -212,6 +223,7 @@ async function handler(args, context = {}) {
212
223
  clinicalIntakeCompleted: intakeCompleted,
213
224
  clinicalMentions: [...clinicalMentions, ...pendingMentions],
214
225
  safetyFlags,
226
+ safetyFlagSources,
215
227
  ...(clinicalMentions.length || pendingMentions.length ? { clinicalFactsExtracted: true } : {}),
216
228
  });
217
229
  } else {
@@ -256,6 +268,58 @@ async function handler(args, context = {}) {
256
268
  return JSON.stringify(envelope);
257
269
  }
258
270
 
271
+ async function declareNonClinical({ declaredRequest, rawMessage, intakeSource, priorTurns, runtime, trace }) {
272
+ let check = null;
273
+ if (runtime?.turnId && runtime?.patientCode) {
274
+ try {
275
+ check = await extractClinicalMentions({
276
+ text: rawMessage,
277
+ detectedTags: DETECTED_TAG_ENUM,
278
+ intakeSource,
279
+ priorTurns,
280
+ turnId: runtime.turnId,
281
+ code: runtime.patientCode,
282
+ provider: requireGatewayProvider(),
283
+ trace,
284
+ persist: false,
285
+ });
286
+ } catch (err) {
287
+ logger.warn('[extractClinicalInfo] declaration check failed; refusing the declaration', { turnId: runtime?.turnId, error: err?.message });
288
+ }
289
+ }
290
+ const carried = CATEGORIES_A_DECLARATION_CARRIES[declaredRequest] || [];
291
+ const usable = check?.completed && check.wellFormed === true && !check.discardedMentions;
292
+ const found = usable
293
+ ? [...(check.clinicalMentions || []), ...(check.pendingMentions || [])].filter((mention) => !carried.includes(mention.fact?.category))
294
+ : null;
295
+ const safetyFlags = check?.safetyFlags || [];
296
+ const categories = found ? [...new Set(found.map((mention) => mention.fact?.category).filter(Boolean))] : [];
297
+ trace?.setSignals?.({
298
+ declarationCheck: { request: declaredRequest, completed: Boolean(usable), categories, safetyFlags },
299
+ safetyFlagSources: check?.safetyFlagSources || null,
300
+ });
301
+
302
+ if (found && !found.length && !safetyFlags.length) {
303
+ trace?.setSignals?.({ clinicalIntakeCompleted: true, clinicalMentions: [], safetyFlags: [] });
304
+ return JSON.stringify({
305
+ success: true,
306
+ data: { degraded: false, non_clinical_request: declaredRequest, clinical_facts: [] },
307
+ });
308
+ }
309
+
310
+ trace?.setSignals?.({ clinicalIntakeCompleted: false, clinicalMentions: [], safetyFlags });
311
+ const supported = [...SUPPORTED_TAGS].sort();
312
+ const reason = found
313
+ ? `the clinical check found content in it (${[...categories, ...safetyFlags].join(', ')})`
314
+ : 'the clinical check could not run';
315
+ return JSON.stringify({
316
+ success: false,
317
+ error: `This message cannot be declared a non-clinical request: ${reason}. Re-call extractClinicalInfo with every applicable supported tag (${supported.join(', ')}).`,
318
+ supported_tags: supported,
319
+ received_tags: [],
320
+ });
321
+ }
322
+
259
323
  async function scanSafetyFlags(text) {
260
324
  try {
261
325
  const patterns = await getSafetyFlagPatterns();
@@ -1,9 +1,11 @@
1
1
  const { MEDICATION_NAMING_RULE } = require('../helpers/medicationNamingRule');
2
2
  const { auditReasoningSchema } = require('../helpers/auditReasoningHelper');
3
+ const { isShadowRun } = require('../helpers/shadowHelper');
4
+ const { evidenceQuoteAnchoring } = require('../helpers/evidenceAnchorHelper');
3
5
  const { dispatcherService } = require('../services/dispatcherService');
4
6
  const { armEscalationNet } = require('../services/contingencyDispatchService');
5
- const { evidenceQuoteAnchoring } = require('../helpers/evidenceAnchorHelper');
6
7
  const { recordEmergency, writeUnresolvedRequest } = require('../services/clinicalAirtableService');
8
+ const { recordEscalationAlarm } = require('../../services/escalationReviewService');
7
9
  const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
8
10
  const { logger } = require('../../utils/logger');
9
11
 
@@ -229,6 +231,18 @@ async function handler(args, context = {}) {
229
231
  });
230
232
  queued = written || duplicate;
231
233
  } else {
234
+ if (!isShadowRun() && runtime.isLive?.() !== false) await recordEscalationAlarm({
235
+ code: runtime.patientCode,
236
+ alarm: {
237
+ urgencyLevel,
238
+ category,
239
+ symptom: details.symptom || null,
240
+ evidenceQuote: details.evidence_quote || null,
241
+ suspectedCondition: details.suspected_condition || null,
242
+ recommendedAction: details.recommended_action || null,
243
+ justification: args?.urgency_justification || null,
244
+ },
245
+ });
232
246
  queued = await recordEmergency({
233
247
  code: runtime.patientCode,
234
248
  trace,
@@ -5,6 +5,7 @@ const { getDb, getModelDatabase } = require('../config/mongoConfig');
5
5
  const { logger } = require('../utils/logger');
6
6
 
7
7
  const CALL_OUTCOMES = ['contacted', 'no_answer', 'voicemail'];
8
+ const URGENCY_LEVELS = ['stat', 'asap', 'urgent', 'routine'];
8
9
  const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
9
10
  const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
10
11
  const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
@@ -12,6 +13,17 @@ const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLAB
12
13
  const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned'];
13
14
  const DECISION_SOURCES = ['platform', 'registered_by_navigator'];
14
15
 
16
+ const alarmSchema = new mongoose.Schema({
17
+ urgencyLevel: { type: String, enum: URGENCY_LEVELS, required: true },
18
+ category: { type: String, default: null },
19
+ symptom: { type: String, default: null },
20
+ evidenceQuote: { type: String, default: null },
21
+ suspectedCondition: { type: String, default: null },
22
+ recommendedAction: { type: String, default: null },
23
+ justification: { type: String, default: null },
24
+ raisedAt: { type: Date, required: true },
25
+ }, { _id: false });
26
+
15
27
  const noteFactSchema = new mongoose.Schema({
16
28
  variableId: { type: String, required: true },
17
29
  concept: { type: String, default: null },
@@ -105,6 +117,7 @@ const escalationReviewSchema = new mongoose.Schema({
105
117
  },
106
118
  openedBy: { type: String, required: true },
107
119
  assistantPausedByReview: { type: Boolean, default: false },
120
+ alarms: { type: [alarmSchema], default: [] },
108
121
  callLogs: { type: [callLogSchema], default: [] },
109
122
  noteFacts: { type: [noteFactSchema], default: [] },
110
123
  drafts: { type: [draftSchema], default: [] },
@@ -4,6 +4,8 @@ const runtimeConfig = require('../config/runtimeConfig');
4
4
  const { httpError } = require('../utils/httpErrorUtils');
5
5
  const { logger } = require('../utils/logger');
6
6
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
7
+ const { mexicoStamp } = require('../utils/dateUtils');
8
+ const { isoDay } = require('../utils/dateUtils');
7
9
  const {
8
10
  CALL_OUTCOMES,
9
11
  CANCELLABLE_AFTER_HANDOFF_STATUSES,
@@ -299,13 +301,42 @@ async function syncCase(review, operator, requestId) {
299
301
  }
300
302
  }
301
303
 
304
+ const URGENCY_LABELS = {
305
+ stat: 'inmediata', asap: 'lo antes posible', urgent: 'urgente', routine: 'rutina',
306
+ };
307
+
308
+ const inlineOf = (value) => String(Array.isArray(value) ? value[0] ?? '' : value ?? '').trim();
309
+
310
+ function doctorHeader(review, patient) {
311
+ const name = inlineOf(patient?.name);
312
+ const phone = review.patientCode.replace(/^whatsapp:/, '');
313
+ const treating = inlineOf(patient?.doctor) || inlineOf(patient?.doctor_auna);
314
+
315
+ const lines = [name ? `${name} · ${phone}` : phone];
316
+ lines.push(`Médico tratante: ${treating || 'no registrado'}`);
317
+
318
+ const alarm = review.alarms?.[review.alarms.length - 1];
319
+ if (alarm) {
320
+ const said = [
321
+ alarm.symptom,
322
+ alarm.suspectedCondition,
323
+ URGENCY_LABELS[alarm.urgencyLevel] ?? alarm.urgencyLevel,
324
+ mexicoStamp(alarm.raisedAt),
325
+ ].map(inlineOf).filter(Boolean);
326
+ if (said.length) lines.push(`Alarma: ${said.join(' · ')}`);
327
+ }
328
+ return lines.join('\n');
329
+ }
330
+
302
331
  async function sendDoctorAlert({ review, draft, approver, operator }) {
303
332
  const doctorCode = ensureWhatsAppFormat(String(approver.phone ?? '').replace(/[^\d+]/g, ''));
304
333
  if (!PATIENT_CODE.test(doctorCode)) throw httpError(422, 'The physician has no usable WhatsApp number on record');
305
334
  const link = `${configured('PEOPL_INTERFACE_URL').replace(/\/+$/, '')}/escalation-review/${review._id}`;
306
335
  const inWindow = await isWithin24HourWindow(doctorCode);
336
+ const patient = await getPatientInformation(review.patientCode).catch(() => null);
337
+ const body = `${doctorHeader(review, patient)}\n\n${draft.doctorText}\n\n${link}`;
307
338
  const message = inWindow
308
- ? { code: doctorCode, body: `${draft.doctorText}\n\n${link}`, triggeredBy: operator }
339
+ ? { code: doctorCode, body, triggeredBy: operator }
309
340
  : { code: doctorCode, contentSid: configured('ESCALATION_REVIEW_DOCTOR_ALERT_CONTENT_SID'), variables: { 1: link }, triggeredBy: operator };
310
341
  const result = await sendMessage(message);
311
342
  if (!result?.success && !result?.completed) {
@@ -375,6 +406,43 @@ async function requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseR
375
406
  return recordIds;
376
407
  }
377
408
 
409
+ const BOT_OPERATOR = 'bot:reportMedicalEscalation';
410
+
411
+ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
412
+ try {
413
+ const patientCode = patientCodeOf(code);
414
+ const entry = { ...alarm, raisedAt: alarm?.raisedAt ?? now };
415
+ const EscalationReview = getEscalationReview();
416
+ const join = () => EscalationReview
417
+ .findOneAndUpdate({ patientCode, closedAt: null }, { $push: { alarms: entry } }, { new: true })
418
+ .lean();
419
+
420
+ await ensureActiveReviewIndex(EscalationReview);
421
+ const joined = await join();
422
+ if (joined) {
423
+ if (!DOCUMENTING_STATUSES.includes(joined.status)) {
424
+ logger.error('[EscalationReview] An alarm arrived after the doctor already had the case', {
425
+ escalationReviewId: String(joined._id), status: joined.status, urgencyLevel: entry.urgencyLevel,
426
+ });
427
+ }
428
+ return joined;
429
+ }
430
+ try {
431
+ return (await EscalationReview.create({
432
+ patientCode, openedBy: BOT_OPERATOR, alarms: [entry], assistantPausedByReview: false,
433
+ })).toObject();
434
+ } catch (error) {
435
+ if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
436
+ return await join();
437
+ }
438
+ } catch (error) {
439
+ logger.error('[EscalationReview] The alarm was not recorded against a review', {
440
+ error: error.message, stack: redactedStack(error),
441
+ });
442
+ return null;
443
+ }
444
+ }
445
+
378
446
  async function openEscalationReview({
379
447
  code,
380
448
  patientCaseRecordId = null,
@@ -409,11 +477,29 @@ async function openEscalationReview({
409
477
  }
410
478
  throw error;
411
479
  }
412
- const existing = await EscalationReview.findOne({ patientCode, closedAt: null }).lean();
480
+ let existing = await EscalationReview.findOne({ patientCode, closedAt: null }).lean();
413
481
  if (!existing) {
414
482
  if (pausedHere) await switchThreadStoppedStatus(patientCode, false).catch(() => {});
415
483
  throw httpError(409, 'This patient already has a review being opened; try again in a moment');
416
484
  }
485
+ if (recordIds.length && !(existing.patientCaseRecordIds ?? []).length) {
486
+ const adopted = await EscalationReview.findOneAndUpdate(
487
+ { _id: existing._id, closedAt: null, patientCaseRecordIds: { $size: 0 } },
488
+ { $set: { patientCaseRecordIds: recordIds } },
489
+ { new: true },
490
+ ).lean();
491
+ if (adopted) {
492
+ existing.patientCaseRecordIds = adopted.patientCaseRecordIds;
493
+ await audit(existing, operator, requestId, { action: 'cases_attached', patientCaseRecordIds: recordIds });
494
+ } else {
495
+ const fresh = await EscalationReview.findOne({ _id: existing._id, closedAt: null }).lean();
496
+ if (!fresh) {
497
+ if (pausedHere) await switchThreadStoppedStatus(patientCode, false).catch(() => {});
498
+ throw httpError(409, 'The review closed while this one was being opened; try again');
499
+ }
500
+ existing = fresh;
501
+ }
502
+ }
417
503
  if (pausedHere && existing.assistantPausedByReview !== true) {
418
504
  try {
419
505
  await EscalationReview.updateOne({ _id: existing._id }, { $set: { assistantPausedByReview: true } });
@@ -939,6 +1025,62 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
939
1025
  return syncCase(review, operator, requestId);
940
1026
  }
941
1027
 
1028
+ const EPISODE_TRUST = 0.7;
1029
+ const EPISODE_VARIABLE = 'intercurrent_events_summary';
1030
+ const EPISODE_SOURCE = 'doctor';
1031
+
1032
+ const DECISION_WORDS = {
1033
+ approved: 'el médico aprobó las indicaciones',
1034
+ edited_approved: 'el médico aprobó las indicaciones con cambios',
1035
+ needs_intervention: 'el médico pidió valoración presencial',
1036
+ returned: 'el médico devolvió el caso a navegación',
1037
+ };
1038
+
1039
+ function episodeFact(review, now) {
1040
+ const alarm = review.alarms?.[review.alarms.length - 1];
1041
+ const named = inlineOf(alarm?.suspectedCondition) || inlineOf(alarm?.symptom);
1042
+ if (!named) return null;
1043
+
1044
+ const raisedAt = new Date(alarm?.raisedAt ?? review.createdAt ?? now);
1045
+ // The record files list-like variables by concept, so the day keeps two episodes apart.
1046
+ const concept = `${named} (${isoDay(raisedAt.toISOString())})`;
1047
+
1048
+ const handedOffAt = review.doctorHandoffs?.[review.doctorHandoffs.length - 1]?.createdAt ?? null;
1049
+ const decided = handedOffAt && raisedAt.getTime() <= new Date(handedOffAt).getTime()
1050
+ ? review.decisions?.[review.decisions.length - 1]
1051
+ : null;
1052
+
1053
+ const delivery = decided ? review.patientDelivery : null;
1054
+ const said = [
1055
+ inlineOf(alarm?.symptom) || named,
1056
+ DECISION_WORDS[decided?.decision],
1057
+ delivery?.confirmedAt || delivery?.deferred === false ? 'se le enviaron indicaciones' : null,
1058
+ ].filter(Boolean);
1059
+
1060
+ return {
1061
+ patientId: review.patientCode,
1062
+ variableId: EPISODE_VARIABLE,
1063
+ concept,
1064
+ value: said.join('. '),
1065
+ source: EPISODE_SOURCE,
1066
+ trust: EPISODE_TRUST,
1067
+ validTime: raisedAt.toISOString(),
1068
+ recordTime: new Date(now).toISOString(),
1069
+ };
1070
+ }
1071
+
1072
+ async function recordEpisode(review, now = new Date()) {
1073
+ try {
1074
+ const assertion = episodeFact(review, now);
1075
+ if (!assertion) return;
1076
+ await storeContextFacts({ patientId: review.patientCode, assertions: [assertion] });
1077
+ } catch (error) {
1078
+ logger.error('[EscalationReview] The episode did not reach the clinical record', {
1079
+ escalationReviewId: String(review._id), error: error.message, stack: redactedStack(error),
1080
+ });
1081
+ }
1082
+ }
1083
+
942
1084
  async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false, interruptionNotes = null, requestId = null } = {}) {
943
1085
  const reviewId = reviewIdOf(id);
944
1086
  const operator = requiredText(closedBy, 'closedBy');
@@ -970,6 +1112,7 @@ async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false,
970
1112
  if (interrupted) closeChanges.fromStatus = current.status;
971
1113
  if (queued) closeChanges.deliveryConfirmed = true;
972
1114
  await audit(review, operator, requestId, closeChanges);
1115
+ await recordEpisode(review);
973
1116
  return syncCase(await resumeAssistant(review, operator, requestId), operator, requestId);
974
1117
  }
975
1118
 
@@ -1015,6 +1158,7 @@ module.exports = {
1015
1158
  handOffToDoctor,
1016
1159
  listEscalationReviews,
1017
1160
  openEscalationReview,
1161
+ recordEscalationAlarm,
1018
1162
  recordDoctorDecision,
1019
1163
  sendApprovedIndications,
1020
1164
  setReviewCases,
@@ -240,17 +240,17 @@ async function sweepColdUnansweredInbound({
240
240
  }
241
241
  }
242
242
 
243
- if (!waiting.length) return { waiting: 0, alerted: 0 };
244
-
245
243
  waiting.sort((a, b) => new Date(a.inbound.createdAt) - new Date(b.inbound.createdAt));
246
244
 
247
245
  if (mode === 'report') {
248
- logger.error('[inboundRecovery] patients have been waiting since long before this sweep looked', {
249
- waiting: waiting.length, oldest: waiting[0].inbound.createdAt, atCeiling, mode,
246
+ logger.error('[inboundRecovery] counted the patients waiting far longer than the live pass looks', {
247
+ waiting: waiting.length, oldest: waiting[0]?.inbound?.createdAt ?? null, atCeiling, mode,
250
248
  });
251
249
  return { waiting: waiting.length, alerted: 0 };
252
250
  }
253
251
 
252
+ if (!waiting.length) return { waiting: 0, alerted: 0 };
253
+
254
254
  let alerted = 0;
255
255
  for (const { code, inbound } of waiting) {
256
256
  if (alerted >= COLD_TICKETS_PER_PASS) break;
@@ -34,6 +34,11 @@ const ageInYears = (birthDate) => {
34
34
  return born.isValid() ? moment.utc().diff(born, 'years') : null;
35
35
  };
36
36
 
37
+ const mexicoStamp = (value) => {
38
+ const at = Date.parse(value instanceof Date ? value.toISOString() : value);
39
+ return Number.isFinite(at) ? moment.tz(at, MEXICO_TZ).locale('es').format('D [de] MMMM, HH:mm') : null;
40
+ };
41
+
37
42
  const isoDay = (value) => (typeof value === 'string' && value.length >= 10 ? value.slice(0, 10) : null);
38
43
 
39
44
  const mexicoDay = (value) => {
@@ -55,5 +60,6 @@ module.exports = {
55
60
  ageInYears,
56
61
  isoDay,
57
62
  mexicoDay,
63
+ mexicoStamp,
58
64
  daysSince
59
65
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.56.18",
3
+ "version": "5.56.21",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",