@peopl-health/nexus 5.73.0 → 5.74.0-dev.15344

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.
@@ -0,0 +1,3 @@
1
+ const CHECK_IN_TYPES = ['contingencia', 'seguimiento'];
2
+
3
+ module.exports = { CHECK_IN_TYPES };
@@ -19,7 +19,6 @@ const ESCALATION_DRAFT_DEFAULTS = { presetId: '' };
19
19
  const ESCALATION_QUESTIONS_DEFAULTS = { presetId: '' };
20
20
  const ESCALATION_NOTE_FACTS_DEFAULTS = { presetId: '' };
21
21
  const SUPPORT_LIGHT_DEFAULTS = { presetId: '' };
22
- const ESCALATION_PATTERN_FLOOR_DEFAULTS = { presetId: '' };
23
22
 
24
23
  const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL });
25
24
 
@@ -75,12 +74,7 @@ async function load() {
75
74
  if (!isSupportLightValid) logger.error('[subAgentsConfig] SUPPORT_LIGHT is not a JSON object; the support-light sweep stays unconfigured');
76
75
  const supportLight = { ...SUPPORT_LIGHT_DEFAULTS, ...(isSupportLightValid ? parsedSupportLight || {} : {}) };
77
76
 
78
- const parsedPatternFloor = safeParse(byKey.ESCALATION_PATTERN_FLOOR, null);
79
- const isPatternFloorValid = !byKey.ESCALATION_PATTERN_FLOOR || isPlainObject(parsedPatternFloor);
80
- if (!isPatternFloorValid) logger.error('[subAgentsConfig] ESCALATION_PATTERN_FLOOR is not a JSON object; the clinical pattern floor stays unconfigured');
81
- const escalationPatternFloor = { ...ESCALATION_PATTERN_FLOOR_DEFAULTS, ...(isPatternFloorValid ? parsedPatternFloor || {} : {}) };
82
-
83
- const config = { EXTRACTOR: extractor, COMPOSER: composer, PATTERN_CONSULT: patternConsult, RISK_ASSESSMENT: riskAssessment, TRIAGE_GATE: triageGate, TRIAGE_PLAN: triagePlan, ESCALATION_DRAFT: escalationDraft, ESCALATION_QUESTIONS: escalationQuestions, ESCALATION_NOTE_FACTS: escalationNoteFacts, SUPPORT_LIGHT: supportLight, ESCALATION_PATTERN_FLOOR: escalationPatternFloor };
77
+ const config = { EXTRACTOR: extractor, COMPOSER: composer, PATTERN_CONSULT: patternConsult, RISK_ASSESSMENT: riskAssessment, TRIAGE_GATE: triageGate, TRIAGE_PLAN: triagePlan, ESCALATION_DRAFT: escalationDraft, ESCALATION_QUESTIONS: escalationQuestions, ESCALATION_NOTE_FACTS: escalationNoteFacts, SUPPORT_LIGHT: supportLight };
84
78
  cache.set(CACHE_KEY, config);
85
79
  return config;
86
80
  }
@@ -100,5 +94,4 @@ module.exports = {
100
94
  getEscalationQuestions: () => get('ESCALATION_QUESTIONS'),
101
95
  getEscalationNoteFacts: () => get('ESCALATION_NOTE_FACTS'),
102
96
  getSupportLightEvaluator: () => get('SUPPORT_LIGHT'),
103
- getEscalationPatternFloor: () => get('ESCALATION_PATTERN_FLOOR'),
104
97
  };
@@ -1,7 +1,6 @@
1
1
  const { isCohortEnabled } = require('../config/cohortConfig');
2
2
  const { isBridgeEnabled } = require('./bridgeConfig');
3
3
  const { contextReadLive, contextMirrorLive, contextVerifierLive } = require('./clinicalContextFlags');
4
- const { clinicalPatternFloorLive } = require('./clinicalPatternFloorFlags');
5
4
  const { isComposerEnabled, isAgentSelfRenderEnabled } = require('./composerFlags');
6
5
  const { isContingencyCancelOnReplyLive, isArmOnOpenCeilingLive, isContingencyRuleBlockLive } = require('./contingencyFlags');
7
6
  const { escalationAssessmentLive, escalationUpdateModeLive } = require('./escalationFlags');
@@ -12,7 +11,6 @@ const { patternConsultLive } = require('./patternConsultFlags');
12
11
  const { recommendationRetryLive } = require('./recommendationRecoveryFlags');
13
12
  const { isShadowEnabled } = require('./shadowConfig');
14
13
  const { supportLightFromChatLive } = require('./supportLightFlags');
15
- const { triageGateFloorLive } = require('./triageGateFloorFlags');
16
14
  const { triageRecommendationLive, rankComparatorLive } = require('./triageRecommendationFlags');
17
15
  const { isConversationalDeclarationLive, isConversationalDraftReuseLive, isDeclarationModelCheckLive } = require('./turnEfficiencyFlags');
18
16
 
@@ -22,7 +20,6 @@ const FLAG_READERS = {
22
20
  contextRead: contextReadLive,
23
21
  contextMirror: contextMirrorLive,
24
22
  contextVerifier: contextVerifierLive,
25
- clinicalPatternFloor: clinicalPatternFloorLive,
26
23
  composer: isComposerEnabled,
27
24
  agentSelfRender: isAgentSelfRenderEnabled,
28
25
  contingencyCancelOnReply: isContingencyCancelOnReplyLive,
@@ -38,7 +35,6 @@ const FLAG_READERS = {
38
35
  recommendationRetry: recommendationRetryLive,
39
36
  shadow: isShadowEnabled,
40
37
  supportLightFromChat: supportLightFromChatLive,
41
- triageGateFloor: triageGateFloorLive,
42
38
  triageRecommendation: triageRecommendationLive,
43
39
  rankComparator: rankComparatorLive,
44
40
  conversationalDeclaration: isConversationalDeclarationLive,
@@ -19,6 +19,7 @@ const { TAIL_PLACEMENT, CURRENT_TURN } = require('../promptPlacement');
19
19
  const { logger } = require('../../utils/logger');
20
20
  const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
21
21
  const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
22
+ const { getCurrentMexicoDateTime } = require('../../utils/dateUtils');
22
23
  const { isJsonBlob } = require('../../utils/formatUtils');
23
24
  const { isPlainObject, safeParse } = require('../../utils/jsonUtils');
24
25
  const { MAX_ADDITIONAL_TOOL_IDS } = require('../../core/runtimeToolPolicy');
@@ -355,6 +356,8 @@ class BaseLLMProvider {
355
356
  })
356
357
  .filter(Boolean);
357
358
 
359
+ if (outreachBrief.checkIn) return this._buildCheckInDueMessage(outreachBrief, lines);
360
+
358
361
  const why = lines([
359
362
  ['último triaje contestado', outreachBrief.lastTriageAt],
360
363
  ['grado máximo en ese triaje', outreachBrief.maxGrade],
@@ -388,6 +391,49 @@ class BaseLLMProvider {
388
391
  return [{ role: 'developer', content: parts.join('\n') }];
389
392
  }
390
393
 
394
+ _buildCheckInDueMessage({ checkIn, recentCheckIns = [], exchange = null, asOf = null }, lines) {
395
+ const ago = (at) => {
396
+ const minutes = asOf ? Math.round((new Date(asOf) - new Date(at)) / 60000) : NaN;
397
+ if (!Number.isFinite(minutes) || minutes < 0) return '';
398
+ return minutes < 60 ? ` (hace ${minutes} min)` : ` (hace ${Math.floor(minutes / 60)} h ${minutes % 60} min)`;
399
+ };
400
+ const local = (at) => (at ? `${getCurrentMexicoDateTime(at)}${ago(at)}` : null);
401
+ const said = (message) => (message ? `${local(message.at)} — «${sanitizeInlineText(message.text)}»` : null);
402
+ const pending = lines([
403
+ ['lo que querías preguntarle', checkIn.question],
404
+ ['por qué quedó abierto', checkIn.concern],
405
+ ['qué dato esperabas', checkIn.awaiting],
406
+ ['desde', local(checkIn.armedAt)],
407
+ ['nivel de la escalación', checkIn.urgency],
408
+ ]);
409
+ const conversation = lines([
410
+ ['su último mensaje', said(exchange?.patient)],
411
+ ['tu último mensaje (tuyo o del equipo)', said(exchange?.own)],
412
+ ['mensajes tuyos o del equipo hoy', exchange ? String(exchange.ownMessagesToday) : null],
413
+ ]);
414
+ const sent = (recentCheckIns || []).map((at) => `- ${sanitizeInlineText(local(at))}`);
415
+ const parts = [
416
+ '[CHECK-IN QUE VENCE (prioritario) para este turno]',
417
+ 'Venció el plazo para retomar algo pendiente con ella. Nadie te ha escrito: decide si hoy le escribes, cuándo volver a buscarla o si ya no hace falta.',
418
+ '', '## Qué quedó pendiente', ...pending,
419
+ ];
420
+ if (conversation.length) parts.push('', '## Cómo va la conversación', ...conversation);
421
+ parts.push(
422
+ '', '## Check-ins que ya le llegaron en las últimas 48 h', ...(sent.length ? sent : ['- ninguno']),
423
+ '',
424
+ `Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Antes, revisa la conversación desde que quedó pendiente:`,
425
+ '- Si ya lo respondió, a ti o al equipo, no se lo vuelvas a preguntar. Si es una red de contingencia, resuélvela con setContingencyPlan y registra hold con hold_reason answered_since_armed.',
426
+ '- Si tu último mensaje ya le hace esta pregunta o la cubre, y ella estuvo activa hoy y dejó de contestar hace menos de 6 h, no la repitas hoy: programa la siguiente vez o resuélvela si ya no hace falta.',
427
+ '- Si sólo quedó una pregunta tuya sin respuesta y lleva 8 h o más en silencio, retomarla es justo para lo que existe este check-in: escríbele, salvo que sea de noche.',
428
+ '- Fuera de esos casos, decide la siguiente vez según el tipo de seguimiento y lo que ella ha ido contando: lo que puede empeorar en horas se pregunta pronto; un síntoma estable o ya en manejo puede esperar días. Si ya le llegó otro check-in hoy y esto puede esperar, no le escribas hoy: programa con schedulePatientReminder (reminder_type seguimiento, con la utility_basis de lo que quedó pendiente, nunca entre 07:30 y 11:00) la hora que corresponda y registra hold con hold_reason rescheduled_for_cadence y el mismo next_check_at.',
429
+ '- Si la red viene de una escalación, su urgencia marca el plazo del equipo para revisarla, no una razón para volver a escribirle.',
430
+ '- Este check-in es el seguimiento que vencía: no cuenta como otro pendiente. Si un seguimiento distinto en la lista de pendientes, o una red activa, ya va a preguntar esto, no programes otro: registra hold con next_check_at null y hold_reason contingency_already_armed.',
431
+ '- Si le escribes, un solo mensaje con una sola pregunta; si otro tema pendiente se responde con esa misma pregunta, intégralo y resuelve las redes que ese mensaje ya cubre. Registra en utility_basis lo que ella contó o acordó.',
432
+ 'Si escribes: breve, sin saludar ni escribir su nombre, sin listas de señales de alarma, sin mencionar recordatorios, planes ni seguimientos programados, y sin repetir un mensaje que ya le enviaste.',
433
+ );
434
+ return [{ role: 'developer', content: parts.join('\n') }];
435
+ }
436
+
391
437
  _buildSkillCatalogMessage(skillCatalog) {
392
438
  const described = (Array.isArray(skillCatalog) ? skillCatalog : []).filter((skill) => skill?.name && skill?.description);
393
439
  if (!described.length) return [];
@@ -0,0 +1,93 @@
1
+ const moment = require('moment-timezone');
2
+
3
+ const { getMessages } = require('../../services/messageService');
4
+ const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
5
+ const { readActiveNets, escalationUrgencyOf } = require('./contingencyDispatchService');
6
+ const { readPendingReminderForPatient } = require('./clinicalAirtableService');
7
+
8
+ const MANDATORY_URGENCIES = new Set(['stat', 'asap']);
9
+ const RECENT_CHECK_IN_WINDOW_MS = 48 * 60 * 60 * 1000;
10
+ const TRIGGERED_BY_PREFIX = 'send_reminder:';
11
+ const NET_INSTRUCTION_MARKER = 'no ha vuelto a escribir y quedó un tema abierto';
12
+ const EXCERPT_LENGTH = 160;
13
+
14
+ const checkInTriggeredBy = (reminderId) => `${TRIGGERED_BY_PREFIX}${reminderId}`;
15
+
16
+ function mandatoryInstruction(firstName, question) {
17
+ return `${firstName || 'La paciente'} no ha vuelto a escribir y quedó un tema abierto que querías retomar. Esto es lo que decidiste preguntarle: "${question}".
18
+
19
+ Antes de escribir, revisa la conversación desde que decidiste preguntarlo. Si ya lo respondió — a ti o al equipo —, no se lo vuelvas a preguntar: retoma desde lo que dijo y pregunta solo lo que siga faltando; si ya no falta nada, cierra en una línea breve y cálida. No le preguntes si el equipo ya la contactó o ya le dio indicaciones: eso no te toca a ti; si tu pregunta lo incluía, quita esa parte.
20
+
21
+ Escríbele tú, de forma breve y natural, en tu tono de siempre, como quien retoma algo pendiente de una conversación. NO digas que pidió un recordatorio ni que se lo prometiste — no lo hizo. No menciones alertas, planes, seguimientos programados ni nada del sistema. No repitas un mensaje que ya le enviaste. Si contesta, sigue la conversación con normalidad.`;
22
+ }
23
+
24
+ async function recentCheckIns(code, now) {
25
+ const rows = await getMessages(
26
+ {
27
+ numero: code,
28
+ from_me: true,
29
+ createdAt: { $gte: new Date(now.getTime() - RECENT_CHECK_IN_WINDOW_MS) },
30
+ $or: [
31
+ { origin: 'assistant', triggeredBy: { $regex: `^(?:${TRIGGERED_BY_PREFIX}|seguimiento:|followup_)` } },
32
+ { origin: 'instruction', triggeredBy: null, message_id: { $regex: '^instruction_' }, 'raw.gated': { $ne: true }, plainBody: { $regex: NET_INSTRUCTION_MARKER } },
33
+ ],
34
+ },
35
+ { sort: { createdAt: 1 }, select: 'createdAt' },
36
+ );
37
+ return (rows || []).map((row) => new Date(row.createdAt).toISOString());
38
+ }
39
+
40
+ async function lastMessage(code, now, fromMe) {
41
+ const [row] = await getMessages(
42
+ { numero: code, from_me: fromMe, origin: { $ne: 'instruction' }, createdAt: { $lt: now } },
43
+ { sort: { createdAt: -1 }, limit: 1, select: 'createdAt plainBody body' },
44
+ ) || [];
45
+ if (!row) return null;
46
+ const text = String(row.plainBody || row.body || '').trim();
47
+ return { at: new Date(row.createdAt).toISOString(), text: text.length > EXCERPT_LENGTH ? `…${text.slice(-EXCERPT_LENGTH)}` : text };
48
+ }
49
+
50
+ async function recentExchange(code, now) {
51
+ const startOfDay = moment(now).tz(DEFAULT_TIMEZONE).startOf('day').toDate();
52
+ const [patient, own, ownToday] = await Promise.all([
53
+ lastMessage(code, now, false),
54
+ lastMessage(code, now, true),
55
+ getMessages({ numero: code, from_me: true, origin: { $ne: 'instruction' }, createdAt: { $gte: startOfDay, $lt: now } }, { select: 'createdAt' }),
56
+ ]);
57
+ return { patient, own, ownMessagesToday: (ownToday || []).length };
58
+ }
59
+
60
+ async function briefFor(code, now, checkIn) {
61
+ const [sent, exchange] = await Promise.all([recentCheckIns(code, now), recentExchange(code, now)]);
62
+ return { reason: 'check_in_due', checkIn, recentCheckIns: sent, exchange, asOf: now.toISOString() };
63
+ }
64
+
65
+ async function planCheckInDue({ code, reminderId, type, question = '', firstName = null, now = new Date() }) {
66
+ let checkIn;
67
+ if (type === 'contingencia') {
68
+ const planId = String(reminderId).replace(/-patient$/, '');
69
+ const net = (await readActiveNets(code)).find((candidate) => candidate.carePlan.planId === planId);
70
+ if (!net) return { mode: 'stale', reason: 'net_not_active' };
71
+ const urgency = escalationUrgencyOf(net);
72
+ const netQuestion = net.patientReminder?.message || question;
73
+ if (MANDATORY_URGENCIES.has(urgency)) {
74
+ return { mode: 'mandatory', planId, instruction: mandatoryInstruction(firstName, netQuestion) };
75
+ }
76
+ checkIn = {
77
+ type,
78
+ question: netQuestion,
79
+ concern: net.carePlan.concern,
80
+ awaiting: net.carePlan.awaitingCharacterization,
81
+ armedAt: net.carePlan.createdAt,
82
+ urgency,
83
+ };
84
+ return { mode: 'decide', planId, brief: await briefFor(code, now, checkIn) };
85
+ }
86
+
87
+ const plan = await readPendingReminderForPatient({ code, reminderId });
88
+ if (!plan) return { mode: 'stale', reason: 'plan_not_pending' };
89
+ checkIn = { type, question: plan.message || question, concern: plan.windowReasoning, awaiting: null, armedAt: null, urgency: null };
90
+ return { mode: 'decide', planId: null, brief: await briefFor(code, now, checkIn) };
91
+ }
92
+
93
+ module.exports = { checkInTriggeredBy, planCheckInDue };
@@ -552,6 +552,34 @@ async function markReminderSent({ code, reminderId, trace = null }) {
552
552
  });
553
553
  }
554
554
 
555
+ async function settleCheckInRow({ code, reminderId, sent = false, reason = null, requireActive = false, onlyIfDispatched = false, trace = null }) {
556
+ if (!code || !reminderId) return false;
557
+ return auditedWrite({
558
+ trace,
559
+ code,
560
+ table: 'reminder',
561
+ meta: { reminderId, lifecycle: sent ? 'sent' : 'stood_down' },
562
+ write: async () => {
563
+ const fields = sent ? { is_active: false, is_sent: true } : { is_active: false, stand_down_reason: reason };
564
+ const updated = await airtableService.updateRecordByFilter(
565
+ Monitoreo_ID,
566
+ 'reminder',
567
+ `AND(${[
568
+ fieldEquals('whatsapp_id', code),
569
+ fieldEquals('schedule_id', reminderId),
570
+ 'IF({is_sent}, "true", "false") = "false"',
571
+ requireActive ? 'IF({is_active}, "true", "false") = "true"' : null,
572
+ onlyIfDispatched ? fieldEquals('stand_down_reason', 'dispatched') : null,
573
+ ].filter(Boolean).join(', ')})`,
574
+ fields,
575
+ code,
576
+ );
577
+ if (!updated?.length) throw new Error(`check-in ${reminderId} was not settled`);
578
+ return updated;
579
+ },
580
+ });
581
+ }
582
+
555
583
  async function recordContingencyEscalation({ code, trace, planId, dueAtUtc, firesAfterSilenceMinutes = null, expiresAtUtc = null, concern, message, actionRequested, priority = null, isLive = null }) {
556
584
  return auditedWrite({
557
585
  trace,
@@ -698,6 +726,7 @@ module.exports = {
698
726
  cancelFollowUp,
699
727
  hasCheckInNear,
700
728
  markReminderSent,
729
+ settleCheckInRow,
701
730
  recordContingencyEscalation,
702
731
  cancelContingencyRows,
703
732
  standDownAllPendingRows,
@@ -278,6 +278,12 @@ const supersedeForEscalation = ({ patientCode, trace, isLive }) => retireCeiling
278
278
  patientCode, trace, isLive, select: (active) => active.filter(isCeilingNet), context: 'after the escalation armed',
279
279
  });
280
280
 
281
+ function escalationUrgencyOf(net) {
282
+ if (net?.carePlan?.armedBy !== ARMED_BY.ESCALATION) return null;
283
+ const silence = net?.patientReminder?.firesAfterSilenceMinutes;
284
+ return Object.keys(ESCALATION_SILENCE_MINUTES).find((level) => ESCALATION_SILENCE_MINUTES[level] === silence) || null;
285
+ }
286
+
281
287
  async function armEscalationNet({ patientCode, urgencyLevel, symptom, suspectedCondition = null, checkIn = null, trace = null, isLive = null }) {
282
288
  const silence = ESCALATION_SILENCE_MINUTES[urgencyLevel];
283
289
  if (!silence) return { armed: false, reason: 'urgency_not_covered' };
@@ -462,4 +468,4 @@ async function applyContingencyEvent({ patientCode, planId, stage, event, at = n
462
468
  return { applied: true, status: next, teamStageArmed: handoff.armed, ...(handoff.armed ? {} : { teamStageReason: handoff.reason }) };
463
469
  }
464
470
 
465
- module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
471
+ module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
@@ -7,12 +7,8 @@ const { evidenceQuoteAnchoring } = require('../helpers/evidenceAnchorHelper');
7
7
  const { dispatcherService } = require('../services/dispatcherService');
8
8
  const { armEscalationNet } = require('../services/contingencyDispatchService');
9
9
  const { recordEmergency, writeUnresolvedRequest } = require('../services/clinicalAirtableService');
10
- const { activeTriageGateFloor } = require('../services/triageGateFloorService');
11
- const { clinicalPatternFloor } = require('../services/clinicalPatternFloorService');
12
10
  const { escalationAssessmentLive, escalationUpdateModeLive, feverPatientTimerLive } = require('../flags/escalationFlags');
13
- const { triageGateFloorLive } = require('../flags/triageGateFloorFlags');
14
- const { clinicalPatternFloorLive } = require('../flags/clinicalPatternFloorFlags');
15
- const { attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm, setAlarmAppliedLevel } = require('../../services/escalationReviewService');
11
+ const { attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
16
12
  const { URGENCY_RANK } = require('../../models/escalationReviewModel');
17
13
  const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
18
14
  const { logger } = require('../../utils/logger');
@@ -331,21 +327,8 @@ async function handler(args, context = {}) {
331
327
  : null;
332
328
  const anchor = updateMode && review ? escalationAnchorOf(review, alarmId) : null;
333
329
  const keptOpenLevel = Boolean(anchor) && (URGENCY_RANK[anchor.urgencyLevel] || 0) > (URGENCY_RANK[requestedLevel] || 0);
334
- const agentLevel = keptOpenLevel ? anchor.urgencyLevel : requestedLevel;
335
- const gateCheck = triageGateFloorLive() && runtime.patientCode ? await activeTriageGateFloor(runtime.patientCode) : null;
336
- const gateFloor = gateCheck?.floor || null;
337
- const raisedByGate = Boolean(gateFloor) && (URGENCY_RANK[gateFloor.level] || 0) > (URGENCY_RANK[agentLevel] || 0);
338
- const flooredLevel = raisedByGate ? gateFloor.level : agentLevel;
339
- const patternCheck = clinicalPatternFloorLive() && runtime.patientCode && flooredLevel === 'routine'
340
- ? await clinicalPatternFloor({ code: runtime.patientCode, turnId: runtime.turnId, details, justification: args?.urgency_justification })
341
- : null;
342
- const patternFloor = patternCheck?.floor || null;
343
- const raisedByPattern = Boolean(patternFloor) && (URGENCY_RANK[patternFloor.level] || 0) > (URGENCY_RANK[flooredLevel] || 0);
344
- const urgencyLevel = raisedByPattern ? patternFloor.level : flooredLevel;
330
+ const urgencyLevel = keptOpenLevel ? anchor.urgencyLevel : requestedLevel;
345
331
  const raisesOpen = !anchor || (URGENCY_RANK[urgencyLevel] || 0) > (URGENCY_RANK[anchor.urgencyLevel] || 0);
346
- // Recorded on the alarm now, not only with the emergency row, so a floor-raised level is never
347
- // treated by the review as the level the bot asked for.
348
- if (review && (raisedByGate || raisedByPattern)) await setAlarmAppliedLevel({ reviewId: review._id, alarmId, appliedLevel: urgencyLevel });
349
332
 
350
333
  trace.setSafetyDecision({ ...(trace.safetyDecision || {}), escalationKind: 'medical_urgent' });
351
334
  trace.setSignals({
@@ -367,11 +350,6 @@ async function handler(args, context = {}) {
367
350
  detailsArg,
368
351
  ...(updateMode ? { mode: 'update', openUrgencyLevel: anchor?.urgencyLevel || null, keptOpenLevel } : {}),
369
352
  ...(clinicalAssessment ? { clinicalAssessment } : {}),
370
- ...(gateFloor ? { triageGateFloor: { ...gateFloor, raised: raisedByGate } } : {}),
371
- ...(patternFloor ? { clinicalPatternFloor: { ...patternFloor, raised: raisedByPattern } } : {}),
372
- ...(gateCheck?.degraded ? { triageGateFloorDegraded: gateCheck.degraded } : {}),
373
- ...(patternCheck?.degraded ? { clinicalPatternFloorDegraded: patternCheck.degraded } : {}),
374
- ...(patternCheck?.check ? { clinicalPatternFloorCheck: patternCheck.check } : {}),
375
353
  },
376
354
  });
377
355
 
@@ -413,9 +391,7 @@ async function handler(args, context = {}) {
413
391
  recommendedAction: details.recommended_action || '',
414
392
  urgencyFhir: urgencyLevel,
415
393
  documentation: [
416
- keptOpenLevel ? `Actualización: el bot sugirió ${requestedLevel}; se mantiene ${agentLevel}.` : '',
417
- raisedByGate ? `Piso del triaje: el gate de seguridad pidió acción en ${gateFloor.maxActionTimeHours ?? '<24'} h (${gateFloor.escalationRoute}); se aplica ${flooredLevel} aunque el bot sugirió ${agentLevel}.` : '',
418
- raisedByPattern ? `Piso clínico (${patternFloor.pattern}): ${patternFloor.reason || 'patrón de riesgo cumplido'}; se aplica ${urgencyLevel} en lugar de ${flooredLevel}.` : '',
394
+ keptOpenLevel ? `Actualización: el bot sugirió ${requestedLevel}; se mantiene ${urgencyLevel}.` : '',
419
395
  args?.urgency_justification || '',
420
396
  details.evidence_quote ? `Evidencia: «${details.evidence_quote}»` : '',
421
397
  assessmentNote(clinicalAssessment),
@@ -425,12 +401,11 @@ async function handler(args, context = {}) {
425
401
  onRecorded: (recordId) => { emergencyRecordId = recordId; },
426
402
  });
427
403
  if (review && emergencyRecordId) await attachEmergencyRow({ reviewId: review._id, alarmId, emergencyRecordId, appliedLevel: urgencyLevel });
428
- const netLevel = raisedByGate || raisedByPattern ? urgencyLevel : agentLevel;
429
- if (netLevel !== 'routine') {
404
+ if (urgencyLevel !== 'routine') {
430
405
  try {
431
406
  const net = queued ? await armEscalationNet({
432
407
  patientCode: runtime.patientCode,
433
- urgencyLevel: netLevel,
408
+ urgencyLevel,
434
409
  symptom: details.symptom || '',
435
410
  suspectedCondition: details.suspected_condition || null,
436
411
  checkIn: args?.patient_check_in || null,
@@ -464,16 +439,6 @@ async function handler(args, context = {}) {
464
439
  follow_up: followUpNote(netArmed, netReason),
465
440
  ...(escalationUpdateModeLive() ? { mode: updateMode ? 'update' : 'new', update_anchor: anchor ? 'open_escalation' : 'none' } : {}),
466
441
  ...(keptOpenLevel ? { kept_open_level: true, requested_urgency_level: requestedLevel } : {}),
467
- ...(raisedByGate ? {
468
- raised_by_triage_gate: true,
469
- requested_urgency_level: requestedLevel,
470
- triage_gate: { escalation_route: gateFloor.escalationRoute, max_action_time_hours: gateFloor.maxActionTimeHours },
471
- } : {}),
472
- ...(raisedByPattern ? {
473
- raised_by_clinical_pattern: true,
474
- requested_urgency_level: requestedLevel,
475
- clinical_pattern: { pattern: patternFloor.pattern, reason: patternFloor.reason },
476
- } : {}),
477
442
  ...(isCoerced ? { coerced_urgency: true, requested_urgency_level: requested } : {}),
478
443
  ...(categoryCoerced ? { coerced_category: true, requested_category: requestedCategory } : {}),
479
444
  ...(detailsArg === 'unreadable' ? { details_unreadable: true } : {}),
@@ -8,11 +8,13 @@ const DECISIONS = ['write', 'hold'];
8
8
 
9
9
  const HOLD_REASONS = [
10
10
  'already_wrote_today',
11
+ 'answered_since_armed',
11
12
  'case_closed_nothing_pending',
12
13
  'contingency_already_armed',
13
14
  'no_change_since_last_outreach',
14
15
  'no_utility_anchor',
15
16
  'recent_patient_activity',
17
+ 'rescheduled_for_cadence',
16
18
  'unanswered_outreach_limit',
17
19
  'other',
18
20
  ];
@@ -8,7 +8,8 @@ const { AssistantMessageError, injectAssistantMessages } = require('../services/
8
8
  const { getThreadInfo, setThreadDoNotAlert, switchThreadStoppedStatus } = require('../services/threadService');
9
9
 
10
10
  const { getRecordByFilter } = require('../services/airtableService');
11
- const { sendMessage, processInstruction, processSystemMessage } = require('../core/NexusMessaging');
11
+ const { sendMessage, processInstruction, processSystemMessage, processCheckInDue, isDraining } = require('../core/NexusMessaging');
12
+ const { CHECK_IN_TYPES } = require('../clinical/config/checkInConfig');
12
13
  const { createAssistant, switchAssistant } = require('../clinical');
13
14
  const { cancelPendingFollowUps } = require('../clinical/services/clinicalAirtableService');
14
15
 
@@ -70,6 +71,18 @@ const addInsAssistantController = async (req, res) => {
70
71
  }
71
72
  };
72
73
 
74
+ const checkInDueController = async (req, res) => {
75
+ const { code, reminder_id: reminderId, type, description, first_name: firstName } = req.body || {};
76
+ if (!code || !reminderId) return res.status(400).json({ success: false, error: 'code and reminder_id are required' });
77
+ if (!CHECK_IN_TYPES.includes(type)) return res.status(400).json({ success: false, error: `type must be one of ${CHECK_IN_TYPES.join(' | ')}` });
78
+ if (isDraining()) return res.status(503).json({ success: false, error: 'draining' });
79
+
80
+ processCheckInDue(code, { reminderId, type, question: description || '', firstName: firstName || null })
81
+ .then((result) => logger.info('[AssistantController] Check-in settled', { code, reminderId, ...result }))
82
+ .catch((error) => logger.error('[AssistantController] Check-in failed', { error: error.message, code, reminderId }));
83
+ return res.status(202).json({ success: true, accepted: true });
84
+ };
85
+
73
86
  const addMsgAssistantController = async (req, res) => {
74
87
  try {
75
88
  await injectAssistantMessages(req.body, processSystemMessage);
@@ -148,6 +161,7 @@ const switchAssistantController = async (req, res) => {
148
161
 
149
162
  module.exports = {
150
163
  addInsAssistantController,
164
+ checkInDueController,
151
165
  addMsgAssistantController,
152
166
  createAssistantController,
153
167
  doNotAlertController,
@@ -45,10 +45,12 @@ const {
45
45
  readPendingReminderForPatient,
46
46
  cancelPendingFollowUps,
47
47
  markReminderSent,
48
+ settleCheckInRow,
48
49
  cancelFollowUp,
49
50
  hasCheckInNear,
50
51
  } = require('../clinical/services/clinicalAirtableService');
51
- const { cancelContingencies } = require('../clinical/services/contingencyDispatchService');
52
+ const { cancelContingencies, applyContingencyEvent } = require('../clinical/services/contingencyDispatchService');
53
+ const { checkInTriggeredBy, planCheckInDue } = require('../clinical/services/checkInDueService');
52
54
  const { isContingencyCancelOnReplyLive } = require('../clinical/flags/contingencyFlags');
53
55
  const { isLlmMonitorEnabled } = require('../clinical/flags/llmMonitorConfig');
54
56
 
@@ -484,7 +486,7 @@ class NexusMessaging {
484
486
 
485
487
  async sendAssistantReply(messageData) {
486
488
  if (await patientIsDeceased(messageData.code)) return NOT_SENT_DECEASED;
487
- if (!messageData.contactCode && !messageData.preemptiveWindowRoute && !messageData.outreachStartedAt) {
489
+ if (!messageData.contactCode && (messageData.outreachCarrier?.replyToContact || (!messageData.preemptiveWindowRoute && !messageData.outreachStartedAt))) {
488
490
  const contact = await replyContactFor(messageData.code);
489
491
  if (contact) messageData = { ...messageData, ...contact };
490
492
  }
@@ -512,7 +514,7 @@ class NexusMessaging {
512
514
  // Proactive outreach lands days after the patient last wrote, so the session is usually closed.
513
515
  // Waiting for Twilio 63016 to bounce would delay every message in the batch by a round-trip.
514
516
  if (messageData.preemptiveWindowRoute && this._needsTemplateRoute(messageData)
515
- && !(await isWithin24HourWindow(messageData.code))) {
517
+ && !(await isWithin24HourWindow(messageData.code, { contactCode: messageData.contactCode }))) {
516
518
  try {
517
519
  messageData = await buildOutreachCarrier(messageData, {
518
520
  provider: this.provider,
@@ -1000,6 +1002,7 @@ class NexusMessaging {
1000
1002
  firstName = null,
1001
1003
  reminderType = 'seguimiento',
1002
1004
  reminderPrefix = null,
1005
+ replyToContact = false,
1003
1006
  dryRun = false,
1004
1007
  } = {}) {
1005
1008
  const outreachStartedAt = new Date().toISOString();
@@ -1030,7 +1033,7 @@ class NexusMessaging {
1030
1033
  turnKind: TURN_KIND.PROACTIVE_OUTREACH,
1031
1034
  outreachBrief: brief,
1032
1035
  preemptiveWindowRoute: true,
1033
- outreachCarrier: { reminderType, reminderPrefix, firstName },
1036
+ outreachCarrier: { reminderType, reminderPrefix, firstName, replyToContact },
1034
1037
  outreachStartedAt,
1035
1038
  // Stamped on the outbound so a delivered message joins back to the row that surfaced her.
1036
1039
  triggeredBy: triggeredBy || null,
@@ -1119,6 +1122,62 @@ class NexusMessaging {
1119
1122
  };
1120
1123
  }
1121
1124
 
1125
+ async processCheckInDue(code, { reminderId, type, question = '', firstName = null } = {}) {
1126
+ if (!code || !reminderId) throw new Error('code and reminderId are required');
1127
+ const claim = await acquireSendClaim({ idempotencyKey: `checkin-due:${reminderId}`, code });
1128
+ if (!claim.acquired) return { decision: 'skipped', holdReason: 'duplicate', sent: false };
1129
+
1130
+ let plan = null;
1131
+ let dispatched = false;
1132
+ try {
1133
+ plan = await planCheckInDue({ code, reminderId, type, question, firstName });
1134
+ if (plan.mode === 'stale') {
1135
+ await settleCheckInRow({ code, reminderId, reason: plan.reason });
1136
+ await completeSendClaim(claim.claimId);
1137
+ return { decision: 'skipped', holdReason: plan.reason, sent: false };
1138
+ }
1139
+ dispatched = await settleCheckInRow({ code, reminderId, reason: 'dispatched', requireActive: true });
1140
+ if (!dispatched) {
1141
+ await completeSendClaim(claim.claimId);
1142
+ return { decision: 'skipped', holdReason: 'row_not_active', sent: false };
1143
+ }
1144
+ await this._fireCheckInNet(code, plan.planId, reminderId);
1145
+
1146
+ const triggeredBy = checkInTriggeredBy(reminderId);
1147
+ let result;
1148
+ if (plan.mode === 'mandatory') {
1149
+ const { outcome } = await this.processInstruction(code, plan.instruction, 'developer', { triggeredBy });
1150
+ const sent = outcome === 'sent' || outcome === 'unknown';
1151
+ result = { decision: sent ? 'write' : 'skipped', holdReason: sent ? null : outcome, sent };
1152
+ } else {
1153
+ const decision = await this.processOutreach(code, { brief: plan.brief, triggeredBy, reason: 'check_in_due', firstName, replyToContact: true });
1154
+ result = { decision: decision.decision, holdReason: decision.holdReason, nextCheckAt: decision.nextCheckAt, sent: decision.accepted };
1155
+ }
1156
+
1157
+ const settled = result.sent
1158
+ ? await settleCheckInRow({ code, reminderId, sent: true, onlyIfDispatched: true })
1159
+ : await settleCheckInRow({ code, reminderId, reason: result.holdReason === 'turn_not_run' ? 'failed' : `held_${result.holdReason || result.decision}`, onlyIfDispatched: true });
1160
+ if (!settled) logger.warn('[processCheckInDue] check-in row was not settled after the turn', { reminderId, sent: result.sent });
1161
+ await completeSendClaim(claim.claimId);
1162
+ return result;
1163
+ } catch (error) {
1164
+ logger.error('[processCheckInDue] check-in turn failed', { reminderId, error: error.message });
1165
+ if (dispatched) await settleCheckInRow({ code, reminderId, reason: 'failed', onlyIfDispatched: true });
1166
+ await releaseSendClaim(claim.claimId);
1167
+ throw error;
1168
+ }
1169
+ }
1170
+
1171
+ async _fireCheckInNet(code, planId, reminderId) {
1172
+ if (!planId) return;
1173
+ try {
1174
+ const fired = await applyContingencyEvent({ patientCode: code, planId, stage: 'patient', event: 'fired' });
1175
+ if (!fired?.applied) logger.info('[processCheckInDue] net was not fired', { reminderId, planId, reason: fired?.reason || null });
1176
+ } catch (error) {
1177
+ logger.error('[processCheckInDue] net fire failed; team stage not armed', { reminderId, planId, teamStageArmed: false, error: error.message });
1178
+ }
1179
+ }
1180
+
1122
1181
  async _retireSkippedFollowUp(code, reminderId, holdReason) {
1123
1182
  const retired = await cancelFollowUp({ code, reminderId, reason: `skipped_${holdReason}` });
1124
1183
  if (!retired) logger.warn('[processScheduledFollowUp] skipped follow-up was not stood down', { reminderId, holdReason });
@@ -1348,6 +1407,10 @@ const processOutreach = async (code, options) => {
1348
1407
  return await requireDefaultInstance().processOutreach(code, options);
1349
1408
  };
1350
1409
 
1410
+ const processCheckInDue = async (code, options) => {
1411
+ return await requireDefaultInstance().processCheckInDue(code, options);
1412
+ };
1413
+
1351
1414
  const processScheduledFollowUp = async (code, options) => {
1352
1415
  return await requireDefaultInstance().processScheduledFollowUp(code, options);
1353
1416
  };
@@ -1356,6 +1419,8 @@ const processSystemMessage = async (code, messages, role, options) => {
1356
1419
  return await requireDefaultInstance().processSystemMessage(code, messages, role, options);
1357
1420
  };
1358
1421
 
1422
+ const isDraining = () => Boolean(getDefaultInstance()?.getBatchingManager()?.isDraining());
1423
+
1359
1424
  const getEventBus = () => getDefaultInstance()?.getEventBus();
1360
1425
 
1361
1426
  const getPhiProcessor = () => getDefaultInstance()?.getPhiProcessor();
@@ -1369,8 +1434,10 @@ module.exports = {
1369
1434
  scheduleTemplateApproval,
1370
1435
  processInstruction,
1371
1436
  processOutreach,
1437
+ processCheckInDue,
1372
1438
  processScheduledFollowUp,
1373
1439
  processSystemMessage,
1440
+ isDraining,
1374
1441
  setDefaultInstance,
1375
1442
  getDefaultInstance,
1376
1443
  requireDefaultInstance,
package/lib/index.d.ts CHANGED
@@ -275,6 +275,7 @@ declare module '@peopl-health/nexus' {
275
275
  processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string; beforeRun?: () => Promise<string | null | undefined> | string | null | undefined }): Promise<{ outcome: string | null; reason?: string; error?: string }>;
276
276
  processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<void>;
277
277
  processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean }): Promise<OutreachDecision>;
278
+ processCheckInDue(code: string, options: { reminderId: string; type: 'contingencia' | 'seguimiento'; question?: string; firstName?: string | null }): Promise<CheckInDueResult>;
278
279
  processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
279
280
  isConnected(): boolean;
280
281
  shutdown(options?: ShutdownOptions): Promise<DrainResult>;
@@ -467,6 +468,15 @@ declare module '@peopl-health/nexus' {
467
468
  lastInboundAt?: string | null;
468
469
  lastOutboundAt?: string | null;
469
470
  lastOutreach?: string | null;
471
+ checkIn?: { type: string; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null } | null;
472
+ recentCheckIns?: string[];
473
+ }
474
+
475
+ export interface CheckInDueResult {
476
+ decision: 'write' | 'hold' | 'skipped';
477
+ holdReason: string | null;
478
+ nextCheckAt?: string | null;
479
+ sent: boolean;
470
480
  }
471
481
 
472
482
  export interface OutreachDecision {
@@ -2,6 +2,7 @@ const express = require('express');
2
2
 
3
3
  const assistantRouteDefinitions = {
4
4
  'POST /add-instruction': 'addInsAssistantController',
5
+ 'POST /check-in-due': 'checkInDueController',
5
6
  'POST /add-msg': 'addMsgAssistantController',
6
7
  'POST /create': 'createAssistantController',
7
8
  'POST /info': 'getInfoAssistantController',
@@ -195,6 +196,7 @@ const officeAssistantController = require('../controllers/officeAssistantControl
195
196
  const builtInControllers = {
196
197
  // Assistant controllers
197
198
  addInsAssistantController: assistantController.addInsAssistantController,
199
+ checkInDueController: assistantController.checkInDueController,
198
200
  addMsgAssistantController: assistantController.addMsgAssistantController,
199
201
  createAssistantController: assistantController.createAssistantController,
200
202
  getInfoAssistantController: assistantController.getInfoAssistantController,
@@ -614,20 +614,6 @@ async function attachEmergencyRow({ reviewId, alarmId, emergencyRecordId, applie
614
614
  }
615
615
  }
616
616
 
617
- async function setAlarmAppliedLevel({ reviewId, alarmId, appliedLevel }) {
618
- try {
619
- await getEscalationReview().updateOne(
620
- { _id: reviewId, 'alarms.alarmId': alarmId },
621
- { $set: { 'alarms.$.appliedLevel': appliedLevel } },
622
- { timestamps: false },
623
- );
624
- } catch (error) {
625
- logger.error('[EscalationReview] The applied level was not recorded on its alarm', {
626
- error: error.message, stack: redactedStack(error),
627
- });
628
- }
629
- }
630
-
631
617
  async function openEscalationReview({
632
618
  code,
633
619
  patientCaseRecordId = null,
@@ -2094,7 +2080,6 @@ module.exports = {
2094
2080
  recordReviewUpdate,
2095
2081
  requestBotDraft,
2096
2082
  sendApprovedIndications,
2097
- setAlarmAppliedLevel,
2098
2083
  setReviewCases,
2099
2084
  suggestDraft,
2100
2085
  suggestKeyQuestions,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.73.0",
3
+ "version": "5.74.0-dev.15344",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,19 +0,0 @@
1
- const runtimeConfig = require('../../config/runtimeConfig');
2
-
3
- const DEFAULT_TIMEOUT_MS = 20000;
4
- const MAX_TIMEOUT_MS = 60000;
5
-
6
- function clinicalPatternFloorLive() {
7
- return String(runtimeConfig.get('ESCALATION_CLINICAL_PATTERN_FLOOR_LIVE', 'true')).trim().toLowerCase() !== 'false';
8
- }
9
-
10
- function clinicalPatternFloorTimeoutMs() {
11
- const value = Number(runtimeConfig.get('ESCALATION_CLINICAL_PATTERN_FLOOR_TIMEOUT_MS', DEFAULT_TIMEOUT_MS));
12
- if (!Number.isFinite(value) || value <= 0) return DEFAULT_TIMEOUT_MS;
13
- return Math.min(value, MAX_TIMEOUT_MS);
14
- }
15
-
16
- module.exports = {
17
- clinicalPatternFloorLive,
18
- clinicalPatternFloorTimeoutMs,
19
- };
@@ -1,17 +0,0 @@
1
- const runtimeConfig = require('../../config/runtimeConfig');
2
-
3
- const DEFAULT_MAX_HOURS = 6;
4
-
5
- function triageGateFloorLive() {
6
- return String(runtimeConfig.get('ESCALATION_TRIAGE_GATE_FLOOR_LIVE', 'true')).trim().toLowerCase() !== 'false';
7
- }
8
-
9
- function triageGateFloorMaxHours() {
10
- const value = Number(runtimeConfig.get('ESCALATION_TRIAGE_GATE_FLOOR_MAX_HOURS', DEFAULT_MAX_HOURS));
11
- return Number.isFinite(value) && value > 0 ? value : DEFAULT_MAX_HOURS;
12
- }
13
-
14
- module.exports = {
15
- triageGateFloorLive,
16
- triageGateFloorMaxHours,
17
- };
@@ -1,146 +0,0 @@
1
- const crypto = require('crypto');
2
-
3
- const { getEscalationPatternFloor } = require('../config/subAgentsConfig');
4
- const { requireGatewayProvider } = require('../config/llmConfig');
5
- const { readClinicalProfile } = require('../helpers/clinicalProfileHelper');
6
- const { buildExposureBlock } = require('../helpers/triageCaseBaseHelper');
7
- const { readStructuredText } = require('../helpers/structuredTextHelper');
8
- const { clinicalPatternFloorTimeoutMs } = require('../flags/clinicalPatternFloorFlags');
9
- const { cleanText } = require('../../fhir/helpers/triagePayloadHelper');
10
- const { isPlainObject, safeParse } = require('../../utils/jsonUtils');
11
- const { logger } = require('../../utils/logger');
12
- const { redactDirectIdentifiers } = require('../../utils/sanitizerUtils');
13
- const { withTimeout } = require('../../utils/timeoutUtils');
14
- const { composePrompt } = require('./promptComposerService');
15
-
16
- const FLOOR_LEVELS = ['urgent', 'asap', 'stat'];
17
- const FLOOR_CEILING = 'urgent';
18
- const PATTERN_NAME = /^[a-z0-9_]{1,64}$/;
19
- const UNLABELLED_PATTERN = 'sin_etiqueta';
20
- const MAX_TEXT_LENGTH = 500;
21
- const MAX_LEVEL_LENGTH = 32;
22
- const MAX_PATTERN_LENGTH = 64;
23
- const PROVENANCE_GRACE_MS = 500;
24
-
25
- const degraded = (reason, check = null) => ({ floor: null, degraded: reason, check });
26
-
27
- function normalizePattern(raw) {
28
- const name = typeof raw === 'string' ? raw.trim().toLowerCase() : '';
29
- return PATTERN_NAME.test(name) ? name : UNLABELLED_PATTERN;
30
- }
31
-
32
- const clippedText = (value) => cleanText(value)?.slice(0, MAX_TEXT_LENGTH) || null;
33
-
34
- // Which prompt judged this escalation. Prompt text is edited in Airtable without bumping the preset
35
- // version, so the version alone cannot tell two prompts apart; the hash of the composed prompt can.
36
- async function promptProvenance(presetId, turnId) {
37
- try {
38
- // Composed alongside runStructured's own compose, with the same inputs and caches: it names the prompt
39
- // the model ran with, though an Airtable edit landing between the two reads could make them differ.
40
- const composed = await composePrompt({ presetId });
41
- // A missing preset composes to an empty prompt; a hash of nothing would read as real provenance.
42
- const promptHash = composed.resolvedPrompt
43
- ? crypto.createHash('sha256').update(`${composed.resolvedPrompt}\n${JSON.stringify(composed.modelConfig || null)}`).digest('hex').slice(0, 12)
44
- : null;
45
- return { presetId, presetVersion: composed.presetVersion || null, promptHash };
46
- } catch (error) {
47
- logger.warn('[clinicalPatternFloor] The prompt provenance could not be read', { turnId, error: error.message });
48
- return { presetId, presetVersion: null, promptHash: null };
49
- }
50
- }
51
-
52
- // What the model answered, before validation, so a rejected or empty answer can be audited too.
53
- const rawOutput = (parsed) => ({
54
- minLevel: typeof parsed.min_level === 'string' ? parsed.min_level.slice(0, MAX_LEVEL_LENGTH) : null,
55
- pattern: typeof parsed.pattern === 'string' ? parsed.pattern.slice(0, MAX_PATTERN_LENGTH) : null,
56
- evidence: clippedText(parsed.evidence),
57
- reason: clippedText(parsed.reason),
58
- });
59
-
60
- function buildPatternInput({ profile, details, justification, today }) {
61
- const indicators = Array.isArray(details.indicators) ? details.indicators.filter((item) => typeof item === 'string' && item.trim()) : [];
62
- const exposure = buildExposureBlock(profile);
63
- return [
64
- `Fecha de hoy: ${today}`,
65
- '',
66
- '## Escalación que el agente está registrando',
67
- `Síntoma: ${cleanText(details.symptom) || 'no especificado'}`,
68
- `Palabras del paciente: ${cleanText(details.evidence_quote) ? `«${details.evidence_quote.trim()}»` : 'no citadas'}`,
69
- `Indicadores: ${indicators.length ? indicators.join('; ') : 'ninguno'}`,
70
- `Sospecha del agente: ${cleanText(details.suspected_condition) || 'no especificada'}`,
71
- `Justificación del agente: ${cleanText(justification) || 'no especificada'}`,
72
- '',
73
- '## Contexto clínico del paciente',
74
- JSON.stringify(profile),
75
- ...(exposure ? ['', '## Exposición antineoplásica y medicación documentadas', exposure] : []),
76
- ].join('\n');
77
- }
78
-
79
- async function evaluatePatternFloor({ code, turnId, details, justification, provider, now }) {
80
- const { presetId } = await getEscalationPatternFloor();
81
- if (!presetId) {
82
- logger.info('[clinicalPatternFloor] No preset is configured; the check is skipped', { turnId });
83
- return degraded('no_preset');
84
- }
85
- const profile = await readClinicalProfile(code);
86
- if (!profile) {
87
- const reason = profile === undefined ? 'profile_unreadable' : 'profile_missing';
88
- logger.warn('[clinicalPatternFloor] The clinical profile is missing or unreadable; the check is skipped', { turnId, profile: reason });
89
- return degraded(reason);
90
- }
91
- // Read alongside the model call so the audit never spends the floor's deadline.
92
- const pendingProvenance = promptProvenance(presetId, turnId);
93
- const result = await (provider || requireGatewayProvider()).runStructured({
94
- presetId,
95
- input: [{ role: 'user', content: buildPatternInput({ profile, details, justification, today: now.toISOString().slice(0, 10) }) }],
96
- metadata: { subAgent: 'escalation-pattern-floor', turnId },
97
- });
98
- // Once the model has answered, provenance gets a short grace and is otherwise dropped: a slow
99
- // Airtable read must never turn an answer the floor already has into a timeout.
100
- const provenance = await withTimeout(pendingProvenance, PROVENANCE_GRACE_MS, 'pattern floor provenance').catch((error) => {
101
- logger.warn('[clinicalPatternFloor] The prompt provenance was not ready; the answer is kept without it', { turnId, error: error.message });
102
- return { presetId, presetVersion: null, promptHash: null };
103
- });
104
- if (result?.status && result.status !== 'completed') {
105
- logger.warn('[clinicalPatternFloor] The pattern check did not complete', { turnId, status: result.status });
106
- return degraded('incomplete', { ...provenance, output: null });
107
- }
108
- const parsed = safeParse(readStructuredText(result), null);
109
- if (!isPlainObject(parsed)) {
110
- logger.warn('[clinicalPatternFloor] The pattern check did not return a JSON object', { turnId });
111
- return degraded('malformed_output', { ...provenance, output: null });
112
- }
113
- const check = { ...provenance, output: rawOutput(parsed) };
114
- if (parsed.min_level == null) {
115
- if (parsed.pattern == null) return { floor: null, degraded: null, check };
116
- logger.warn('[clinicalPatternFloor] The pattern check named a pattern without a level', { turnId, pattern: parsed.pattern });
117
- return degraded('missing_level', check);
118
- }
119
- if (!FLOOR_LEVELS.includes(parsed.min_level)) {
120
- logger.warn('[clinicalPatternFloor] The pattern check returned an unsupported level', { turnId, minLevel: parsed.min_level, pattern: parsed.pattern });
121
- return degraded('unsupported_level', check);
122
- }
123
- return {
124
- floor: { level: FLOOR_CEILING, pattern: normalizePattern(parsed.pattern), evidence: clippedText(parsed.evidence), reason: clippedText(parsed.reason) },
125
- degraded: null,
126
- check,
127
- };
128
- }
129
-
130
- async function clinicalPatternFloor({ code, turnId = null, details = {}, justification = null, provider = null, now = new Date() }) {
131
- try {
132
- return await withTimeout(
133
- evaluatePatternFloor({ code, turnId, details, justification, provider, now }),
134
- clinicalPatternFloorTimeoutMs(),
135
- 'clinical pattern floor',
136
- );
137
- } catch (error) {
138
- const timedOut = /timed out after/.test(error?.message || '');
139
- logger.error('[clinicalPatternFloor] The clinical pattern check failed', {
140
- turnId, error: error.message, stack: redactDirectIdentifiers(String(error?.stack || '')),
141
- });
142
- return degraded(timedOut ? 'timeout' : 'error');
143
- }
144
- }
145
-
146
- module.exports = { clinicalPatternFloor, buildPatternInput };
@@ -1,49 +0,0 @@
1
- const { getTriageRecommendationEventModel } = require('../models/triageRecommendationEventModel');
2
- const { triageGateFloorMaxHours } = require('../flags/triageGateFloorFlags');
3
- const { logger } = require('../../utils/logger');
4
- const { redactDirectIdentifiers } = require('../../utils/sanitizerUtils');
5
-
6
- const HOUR_MS = 60 * 60 * 1000;
7
- const LOOKBACK_MS = 24 * HOUR_MS;
8
- const ROUTE_FLOOR = { emergencia: 'stat', urgencias: 'asap', equipo_tratante_hoy: 'urgent' };
9
- const DEFAULT_FLOOR = 'asap';
10
- const PROMPT_ROUTES = ['urgencias', 'emergencia'];
11
- const NO_FLOOR = { floor: null, degraded: null };
12
-
13
- const settledAt = (event) => new Date(event.createdAt).getTime();
14
- const gateTime = (event) => Math.min(new Date(event.triageAuthoredAt || event.createdAt).getTime(), settledAt(event));
15
-
16
- async function activeTriageGateFloor(code, now = new Date()) {
17
- try {
18
- const gates = await getTriageRecommendationEventModel()
19
- .find({ patientCode: code, gateVerdict: { $ne: null }, createdAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } })
20
- .select('runId triageRecordId urgentUnder24h escalationRoute maxActionTimeHours triageAuthoredAt createdAt')
21
- .lean();
22
- const latest = gates.reduce((best, event) => (!best || gateTime(event) > gateTime(best)
23
- || (gateTime(event) === gateTime(best) && settledAt(event) > settledAt(best)) ? event : best), null);
24
- if (!latest?.urgentUnder24h) return NO_FLOOR;
25
-
26
- const hours = Number.isFinite(latest.maxActionTimeHours) ? latest.maxActionTimeHours : null;
27
- const promptRoute = PROMPT_ROUTES.includes(latest.escalationRoute);
28
- if (!promptRoute && (hours === null || hours > triageGateFloorMaxHours())) return NO_FLOOR;
29
-
30
- const windowMs = Math.max(hours ?? 24, 1) * HOUR_MS;
31
- if (now.getTime() - gateTime(latest) > windowMs) return NO_FLOOR;
32
-
33
- return {
34
- floor: {
35
- level: ROUTE_FLOOR[latest.escalationRoute] || DEFAULT_FLOOR,
36
- runId: latest.runId,
37
- triageRecordId: latest.triageRecordId,
38
- escalationRoute: latest.escalationRoute,
39
- maxActionTimeHours: hours,
40
- },
41
- degraded: null,
42
- };
43
- } catch (error) {
44
- logger.error('[triageGateFloor] The latest triage gate could not be read', { error: error.message, stack: redactDirectIdentifiers(String(error?.stack || '')) });
45
- return { floor: null, degraded: 'read_failed' };
46
- }
47
- }
48
-
49
- module.exports = { activeTriageGateFloor };