@peopl-health/nexus 6.0.0-dev.15993 → 6.0.0-dev.16255

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.
@@ -14,6 +14,10 @@ function chemoContextLive() {
14
14
  return flagOn('CHEMO_CONTEXT_LIVE');
15
15
  }
16
16
 
17
+ function rtContextBlockLive() {
18
+ return flagOn('RT_CONTEXT_BLOCK');
19
+ }
20
+
17
21
  function profileFromMongo() {
18
22
  return flagOn('PATIENT_PROFILE_FROM_MONGO');
19
23
  }
@@ -38,4 +42,5 @@ module.exports = {
38
42
  profileFromMongo,
39
43
  profileSyncOn,
40
44
  regimenCloserLive,
45
+ rtContextBlockLive,
41
46
  };
@@ -1,6 +1,8 @@
1
1
  const { isCohortEnabled } = require('../config/cohortConfig');
2
2
  const { isBridgeEnabled } = require('./bridgeConfig');
3
- const { contextReadLive, contextMirrorLive, contextVerifierLive } = require('./clinicalContextFlags');
3
+ const {
4
+ contextReadLive, contextMirrorLive, contextVerifierLive, rtContextBlockLive,
5
+ } = require('./clinicalContextFlags');
4
6
  const { isComposerEnabled, isAgentSelfRenderEnabled } = require('./composerFlags');
5
7
  const { isContingencyCancelOnReplyLive, isArmOnOpenCeilingLive, isContingencyRuleBlockLive } = require('./contingencyFlags');
6
8
  const { escalationAssessmentLive, escalationUpdateModeLive } = require('./escalationFlags');
@@ -20,6 +22,7 @@ const FLAG_READERS = {
20
22
  contextRead: contextReadLive,
21
23
  contextMirror: contextMirrorLive,
22
24
  contextVerifier: contextVerifierLive,
25
+ rtContextBlock: rtContextBlockLive,
23
26
  composer: isComposerEnabled,
24
27
  agentSelfRender: isAgentSelfRenderEnabled,
25
28
  contingencyCancelOnReply: isContingencyCancelOnReplyLive,
@@ -8,6 +8,7 @@ const ACTIVE_DAYS = 35;
8
8
  const DEFAULT_CYTOTOXIC_WINDOW_DAYS = 42;
9
9
  const HEADER = 'Quimioterapia (registro de la unidad de quimioterapia; úsalo para contextualizar y priorizar síntomas, nunca para bajar la urgencia; no comuniques dosis ni ajustes de tratamiento; si el paciente dice algo distinto, créele: si es otra fecha de cita, que el paciente la confirme con el área de tratamiento, sin avisar al equipo; si es un dato clínico, o una sesión suspendida o cambiada por un motivo clínico, avisa al equipo)';
10
10
  const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/;
11
+ const CLOCK = /^([01]\d|2[0-3]):[0-5]\d$/;
11
12
  const NO_ALLERGY = /^(ninguna?s?|no|negadas?|desconocidas?|(niega|no refiere|sin|no tiene|no presenta) alergias?( conocidas| a medicamentos)?)$/;
12
13
  const NEGATION = /\b(sin|niega|no|ninguna?)\b/;
13
14
 
@@ -131,7 +132,7 @@ function chemoLines(context, today) {
131
132
  }
132
133
  if (context.proximaSesion && context.proximaSesion.fecha >= today) {
133
134
  lines.push(context.proximaSesion.tipo === 'agendada'
134
- ? `Próxima sesión de quimioterapia: ${dmy(context.proximaSesion.fecha)} (${['agendada', confirmation(context.proximaSesion)].filter(Boolean).join('; ')})`
135
+ ? `Próxima sesión de quimioterapia: ${dmy(context.proximaSesion.fecha)}${CLOCK.test(context.proximaSesion.hora) ? ` a las ${context.proximaSesion.hora}` : ''} (${['agendada', confirmation(context.proximaSesion)].filter(Boolean).join('; ')})`
135
136
  : `Próxima sesión de quimioterapia: ${dmy(context.proximaSesion.fecha)} (estimada; no la confirmes como cita)`);
136
137
  }
137
138
  const support = context.proximaVisitaSoporte;
@@ -0,0 +1,30 @@
1
+ const TRIAGE_RESULT_MARKER = 'acaba de completar el triaje de síntomas PRO-CTCAE';
2
+
3
+ const SCALE_HEADER = 'Escala CTCAE de este síntoma. El grado de arriba es una APROXIMACIÓN calculada a partir del PRO-CTCAE, no una lectura de estas cláusulas: contrasta lo que el paciente describe contra ellas antes de darlo por confirmado. Si la evidencia sostiene otra cláusula, ese es el grado.';
4
+ const DEFINITION_PREFIX = 'Definición del síntoma - ';
5
+ const SCALE_CLAUSE_RX = /^\s+G\d:/;
6
+
7
+ const isTriageResultMessage = (body) => typeof body === 'string' && body.includes(TRIAGE_RESULT_MARKER);
8
+
9
+ const isReferenceLine = (line, next) => line === SCALE_HEADER
10
+ || (line.startsWith(DEFINITION_PREFIX) && next === SCALE_HEADER);
11
+
12
+ // Drops only fixed CTCAE reference text (the scale header leaves with its clauses); every patient-specific line stays verbatim.
13
+ function compactTriageResult(body) {
14
+ if (!isTriageResultMessage(body)) return body;
15
+ const lines = body.split('\n');
16
+ const kept = [];
17
+ let inScale = false;
18
+ let dropped = false;
19
+ lines.forEach((line, i) => {
20
+ if (inScale && SCALE_CLAUSE_RX.test(line)) { dropped = true; return; }
21
+ inScale = line === SCALE_HEADER;
22
+ if (isReferenceLine(line, lines[i + 1])) { dropped = true; return; }
23
+ const isBlank = !line.trim();
24
+ if (isBlank && kept.length && !kept[kept.length - 1].trim()) return;
25
+ kept.push(line);
26
+ });
27
+ return dropped ? kept.join('\n') : body;
28
+ }
29
+
30
+ module.exports = { TRIAGE_RESULT_MARKER, compactTriageResult, isTriageResultMessage };
@@ -1,4 +1,5 @@
1
1
  const { pairTriageSymptoms } = require('../helpers/triageSymptomsHelper');
2
+ const { compactTriageResult, isTriageResultMessage } = require('../helpers/triageResultMessageHelper');
2
3
  const { parseChemoContext, renderChemoContext, withChemoContext } = require('../helpers/chemoContextHelper');
3
4
  const { handlePendingFunctionCalls: handlePendingFunctionCallsUtil } = require('../providers/OpenAIResponsesProviderTools');
4
5
 
@@ -99,13 +100,15 @@ class DefaultMemoryManager extends MemoryManager {
99
100
 
100
101
  const skipTools = new Set(getTurnScopedToolNames());
101
102
  const replayArgs = getReplayArgsByTool();
103
+ const latestTriage = config.compactOlderTriage ? ordered.findLastIndex(msg => isTriageResultMessage(msg.body)) : -1;
102
104
 
103
105
  const context = ordered.flatMap((msg, index) => {
104
106
  const toolItems = getMessageTools(msg, { skipTools, replayArgs });
105
107
  if (index >= turnStart) return toolItems;
106
108
  const role = this._resolveContextRole(msg);
107
109
  const prefix = this._speakerPrefix(msg, role);
108
- const contentItems = formatMessage(msg)
110
+ const shown = index < latestTriage ? { ...msg, body: compactTriageResult(msg.body) } : msg;
111
+ const contentItems = formatMessage(shown)
109
112
  .filter(Boolean)
110
113
  .map(content => ({
111
114
  role,
@@ -53,6 +53,7 @@ const triageRecommendationEventSchema = new mongoose.Schema({
53
53
  classifierWaitMs: { type: Number, default: null },
54
54
  deniedCardsDropped: { type: Number, default: null },
55
55
  deniedTargetsStripped: { type: Number, default: null },
56
+ cardsTruncated: { type: Number, default: null },
56
57
  adherenceRecorded: { type: Number, default: null },
57
58
  adherenceSkipped: { type: Number, default: null },
58
59
  adherenceNoTask: { type: Number, default: null },
@@ -10,6 +10,7 @@ const { composePrompt, resolveTools } = require('../services/promptComposerServi
10
10
  const { resolveSkillCatalog } = require('../services/skillService');
11
11
  const { RISK_HEADLINE_MARKER } = require('../services/riskHeadlineService');
12
12
  const { resolveClinicalContext } = require('../services/clinicalContextReadService');
13
+ const { radiotherapyBlockFor, withRadiotherapyBlock } = require('../services/radiotherapyContextService');
13
14
  const { isContingencyRuleBlockLive } = require('../flags/contingencyFlags');
14
15
  const { snapshotClinicalFlags } = require('../flags/flagSnapshot');
15
16
  const { TURN_KIND } = require('../context/turnContext');
@@ -21,7 +22,7 @@ const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
21
22
  const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
22
23
  const { getCurrentMexicoDateTime } = require('../../utils/dateUtils');
23
24
  const { isJsonBlob } = require('../../utils/formatUtils');
24
- const { isPlainObject, safeParse } = require('../../utils/jsonUtils');
25
+ const { isPlainObject, safeParse, decodeLiteralUnicodeEscapes } = require('../../utils/jsonUtils');
25
26
  const { MAX_ADDITIONAL_TOOL_IDS } = require('../../core/runtimeToolPolicy');
26
27
 
27
28
  const EXCHANGE_LINE_LENGTH = 400;
@@ -321,7 +322,7 @@ class BaseLLMProvider {
321
322
  ...this._buildFollowUpPolicyMessage(toolIds),
322
323
  ...this._buildFollowUpMessage(promptVariables),
323
324
  ...this._buildFollowUpCheckMessage(toolIds),
324
- ...this._buildContingencyCheckMessage(promptVariables, toolIds),
325
+ ...this._buildContingencyCheckMessage(promptVariables, toolIds, outreachBrief),
325
326
  ...this._buildClockMessage(promptVariables, interpolatedVariables),
326
327
  ...messages,
327
328
  ...this._buildOutreachBriefMessage({ outreachBrief, toolIds }),
@@ -494,12 +495,16 @@ class BaseLLMProvider {
494
495
  // Rides behind the history like the follow-up check: the nets block above lists the nets, the decision lives here,
495
496
  // because an unresolved net later asks the patient a question they had already answered.
496
497
  // Only answers given after the net was armed count: an escalation net waits for how the reported symptom evolved.
497
- _buildContingencyCheckMessage(promptVariables, toolIds = []) {
498
+ // A net is marked fired before its own check-in turn runs, so during that turn its check-in has not reached the patient yet.
499
+ _buildContingencyCheckMessage(promptVariables, toolIds = [], outreachBrief = null) {
498
500
  if (!(toolIds || []).includes('setContingencyPlan')) return [];
499
501
  const active = Array.isArray(promptVariables?.active_contingencies) ? promptVariables.active_contingencies : [];
500
502
  if (!active.length) return [];
503
+ const dueNet = outreachBrief?.checkIn?.planId || null;
501
504
  const waiting = active.map(({ carePlan: plan = {} } = {}) => {
502
- const fired = plan.status === 'fired_reminder' ? ' Su check-in ya se envió.' : '';
505
+ let fired = '';
506
+ if (dueNet && plan.planId === dueNet) fired = ' Su check-in es el de este turno: todavía no le ha llegado.';
507
+ else if (plan.status === 'fired_reminder') fired = ' Su check-in ya se envió.';
503
508
  return `- ${plan.planId} (armada ${localFireTime(plan.createdAt)}) espera: ${sanitizeInlineText(plan.awaitingCharacterization)}.${fired}`;
504
509
  });
505
510
  return [{
@@ -621,6 +626,7 @@ class BaseLLMProvider {
621
626
  ...config,
622
627
  threadId: conversationId,
623
628
  assistantId,
629
+ compactOlderTriage: true,
624
630
  }
625
631
  });
626
632
 
@@ -633,6 +639,7 @@ class BaseLLMProvider {
633
639
 
634
640
  logger.info('[executeRun] Context built', { conversationId, messageCount: context?.length || 0 });
635
641
 
642
+ const radiotherapyBlock = radiotherapyBlockFor(thread.code, Date.now());
636
643
  const override = config.clinicalData;
637
644
  const hasOverride = override && typeof override === 'object' && Object.keys(override).length > 0;
638
645
  const clinicalData = hasOverride ? override : await this.conversationManager.getClinicalData(thread.code);
@@ -656,8 +663,9 @@ class BaseLLMProvider {
656
663
  patientId: thread.code,
657
664
  legacyBlock: promptVariables.clinical_context,
658
665
  });
659
- promptVariables.clinical_context = withHospitalization(block, thread?.hospitalizedAt);
660
- assistant?.toolRuntimeContext?.trace?.setSignals?.({ contextSource: source });
666
+ const rtBlock = await radiotherapyBlock;
667
+ promptVariables.clinical_context = withRadiotherapyBlock(withHospitalization(block, thread?.hospitalizedAt), rtBlock);
668
+ assistant?.toolRuntimeContext?.trace?.setSignals?.({ contextSource: source, rtBlockPresent: Boolean(rtBlock) });
661
669
 
662
670
  const result = await this.runConversation({
663
671
  threadId: conversationId,
@@ -859,7 +867,7 @@ class BaseLLMProvider {
859
867
  _bridgeFrom(calls) {
860
868
  const pick = (name, field) => {
861
869
  const value = calls.find(call => call.name === name)?.input?.[field];
862
- return typeof value === 'string' && value.trim() ? value : null;
870
+ return typeof value === 'string' && value.trim() ? decodeLiteralUnicodeEscapes(value) : null;
863
871
  };
864
872
  const extraction = calls.find(call => call.name === EXTRACTION_TOOL)?.input;
865
873
  if (pick(EXTRACTION_TOOL, 'non_clinical_request') && pick(EXTRACTION_TOOL, 'raw_message') && extraction?.detected_tags?.length === 0) {
@@ -1,7 +1,7 @@
1
1
  const { isToolFailure, toolFailureError } = require('../helpers/toolResultHelper');
2
2
 
3
3
  const { logger } = require('../../utils/logger');
4
- const { safeParse } = require('../../utils/jsonUtils');
4
+ const { safeParse, normalizeModelStrings } = require('../../utils/jsonUtils');
5
5
 
6
6
  const { hasTool, executeTool: registryExecuteTool } = require('../../services/toolRegistryService');
7
7
 
@@ -17,6 +17,11 @@ async function executeFunctionCall(assistant, call, phiProcessor) {
17
17
  } catch (e) {
18
18
  logger.warn('[executeFunctionCall] arg decode produced invalid JSON, falling back to original args', { name, errorType: e?.name || 'Error' });
19
19
  }
20
+ const normalizedArgs = normalizeModelStrings(decodedArgs);
21
+ if (JSON.stringify(normalizedArgs) !== JSON.stringify(decodedArgs)) {
22
+ logger.warn('[executeFunctionCall] decoded literal unicode escapes in tool arguments', { name, call_id: call.call_id });
23
+ decodedArgs = normalizedArgs;
24
+ }
20
25
 
21
26
  logger.info('[executeFunctionCall] Calling', { name, call_id: call.call_id });
22
27
 
@@ -101,6 +101,7 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
101
101
  checkIn = {
102
102
  type,
103
103
  reminderId,
104
+ planId,
104
105
  dueAt: null,
105
106
  question: netQuestion,
106
107
  concern: net.carePlan.concern,
@@ -118,6 +119,7 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
118
119
  checkIn = {
119
120
  type,
120
121
  reminderId,
122
+ planId: null,
121
123
  dueAt: plan.fireAt || null,
122
124
  question: plan.message || question,
123
125
  concern: plan.windowReasoning,
@@ -212,6 +212,20 @@ async function recordPausedThreadMessage({ code, text, alert = OPS_ALERTS.paused
212
212
  return written;
213
213
  }
214
214
 
215
+ const GROUP_MESSAGE_ID_FIELD = 'group_message_id';
216
+
217
+ // The id of the group message notifyEmergency posted for this row, so follow-ups reply to it; null when unknown.
218
+ async function readGroupMessageId(recordId, code) {
219
+ if (!/^rec[A-Za-z0-9]+$/.test(String(recordId ?? ''))) return null;
220
+ try {
221
+ const rows = await airtableService.getRecordByFilter(Monitoreo_ID, 'emergencies', `RECORD_ID() = '${recordId}'`, null, [GROUP_MESSAGE_ID_FIELD]);
222
+ return String(rows?.[0]?.[GROUP_MESSAGE_ID_FIELD] ?? '').trim() || null;
223
+ } catch (error) {
224
+ logger.warn('[clinicalAirtableService] The group message id could not be read; the follow-up goes out unthreaded', { code, recordId, error: error.message });
225
+ return null;
226
+ }
227
+ }
228
+
215
229
  async function readEmergencyRow(recordId, code) {
216
230
  try {
217
231
  const open = await airtableService.getRecordByFilter(Monitoreo_ID, 'emergencies', `RECORD_ID() = '${recordId}'`, null);
@@ -716,6 +730,7 @@ module.exports = {
716
730
  writeUnresolvedRequest,
717
731
  recordPausedThreadMessage,
718
732
  recordEmergency,
733
+ readGroupMessageId,
719
734
  recordClinicalIntake,
720
735
  recordReminder,
721
736
  hasPendingContingencyRow,
@@ -11,12 +11,16 @@ const { isShadowRun } = require('../helpers/shadowHelper');
11
11
  const PATIENT_CONTACT_WINDOW = { timeZone: 'America/Mexico_City', startHour: 8, endHour: 21 };
12
12
  // Net check-ins start an hour later: 08:00–09:00 is when the daily symptom forms reach patients.
13
13
  const CHECK_IN_WINDOW = { ...PATIENT_CONTACT_WINDOW, startHour: 9 };
14
+ // asap check-ins only hold 23:00–08:00: the case is still hot and someone may be awake.
15
+ const ASAP_CHECK_IN_WINDOW = { ...PATIENT_CONTACT_WINDOW, endHour: 23 };
14
16
  const MS_PER_MINUTE = 60 * 1000;
15
17
  const MS_PER_HOUR = 60 * MS_PER_MINUTE;
16
18
  const EXPIRY_WINDOW_MULTIPLIER = 6;
17
19
  const EXPIRY_FLOOR_MS = 48 * MS_PER_HOUR;
18
20
  const EXPIRY_CEILING_MS = 14 * 24 * MS_PER_HOUR;
19
- const ESCALATION_SILENCE_MINUTES = { stat: 120, asap: 180, urgent: 240 };
21
+ const ESCALATION_SILENCE_MINUTES = { stat: null, asap: 60, urgent: 240 };
22
+ // Nets armed before the change keep their level until they expire (stat 120, asap 180).
23
+ const LEGACY_ESCALATION_SILENCE_MINUTES = { stat: 120, asap: 180 };
20
24
  const OPEN_CEILING_SILENCE_MINUTES = 720;
21
25
  const OPEN_CEILING_ORIGIN = 'open_ceiling';
22
26
  const OPEN_CEILING_CHECK_IN = 'Hola, quería saber cómo sigues. ¿Cómo va lo que me contaste?';
@@ -33,14 +37,18 @@ function rawDueAt(createdAt, firesAfterSilenceMinutes) {
33
37
  return new Date(new Date(createdAt).getTime() + (firesAfterSilenceMinutes * MS_PER_MINUTE));
34
38
  }
35
39
 
36
- function dueAt(createdAt, firesAfterSilenceMinutes) {
40
+ function checkInWindowFor(urgencyLevel) {
41
+ return urgencyLevel === 'asap' ? ASAP_CHECK_IN_WINDOW : CHECK_IN_WINDOW;
42
+ }
43
+
44
+ function dueAt(createdAt, firesAfterSilenceMinutes, window = CHECK_IN_WINDOW) {
37
45
  const raw = rawDueAt(createdAt, firesAfterSilenceMinutes);
38
- return (clampToHourWindow(raw, CHECK_IN_WINDOW) || raw).toISOString();
46
+ return (clampToHourWindow(raw, window) || raw).toISOString();
39
47
  }
40
48
 
41
- function quietHoursShiftMinutes(createdAt, firesAfterSilenceMinutes) {
49
+ function quietHoursShiftMinutes(createdAt, firesAfterSilenceMinutes, window = CHECK_IN_WINDOW) {
42
50
  const raw = rawDueAt(createdAt, firesAfterSilenceMinutes);
43
- const clamped = clampToHourWindow(raw, CHECK_IN_WINDOW);
51
+ const clamped = clampToHourWindow(raw, window);
44
52
  if (!clamped) return 0;
45
53
  return Math.round((clamped.getTime() - raw.getTime()) / MS_PER_MINUTE);
46
54
  }
@@ -96,7 +104,7 @@ function computeExpiresAt(createdAt, firesAfterSilenceMinutes) {
96
104
  return new Date(new Date(createdAt).getTime() + clamped).toISOString();
97
105
  }
98
106
 
99
- function stampContingencyPlan({ trace, planId, relatedCaseId, relatedClusterId, concern, awaitingCharacterization, resolvesOn = RESOLVES_ON.REPLY, createdAt, firesAfterSilenceMinutes, windowReasoning = null, extra = null }) {
107
+ function stampContingencyPlan({ trace, planId, relatedCaseId, relatedClusterId, concern, awaitingCharacterization, resolvesOn = RESOLVES_ON.REPLY, createdAt, firesAfterSilenceMinutes, windowReasoning = null, extra = null, checkInWindow = CHECK_IN_WINDOW }) {
100
108
  const existing = Array.isArray(trace?.signals?.contingencyPlans) ? trace.signals.contingencyPlans : [];
101
109
  trace?.setSignals?.({
102
110
  contingencyPlans: [...existing, {
@@ -107,7 +115,7 @@ function stampContingencyPlan({ trace, planId, relatedCaseId, relatedClusterId,
107
115
  awaitingCharacterization,
108
116
  resolvesOn,
109
117
  patientFiresAfterSilenceMinutes: firesAfterSilenceMinutes,
110
- quietHoursShiftMinutes: quietHoursShiftMinutes(createdAt, firesAfterSilenceMinutes),
118
+ quietHoursShiftMinutes: quietHoursShiftMinutes(createdAt, firesAfterSilenceMinutes, checkInWindow),
111
119
  windowReasoning,
112
120
  ...(extra || {}),
113
121
  }],
@@ -241,7 +249,7 @@ function isCeilingNet(net) {
241
249
  return plan?.armedBy === ARMED_BY.OPEN_CEILING || plan?.creationReasoning === OPEN_CEILING_ORIGIN;
242
250
  }
243
251
 
244
- async function retireCeilingNets({ patientCode, trace, isLive, select, context }) {
252
+ async function retireNets({ patientCode, trace, isLive, select, context }) {
245
253
  if (isShadowRun()) return [];
246
254
  if (isLive && !isLive()) return [];
247
255
  const targets = select(await readActiveNets(patientCode));
@@ -259,7 +267,7 @@ async function retireCeilingNets({ patientCode, trace, isLive, select, context }
259
267
  });
260
268
  retired.push(net.carePlan.planId);
261
269
  } catch (error) {
262
- logger.warn(`[contingency] ceiling net not retired ${context}`, { patientCode, planId: net.carePlan.planId, error: error?.message, err: error });
270
+ logger.warn(`[contingency] net not retired ${context}`, { patientCode, planId: net.carePlan.planId, error: error?.message, err: error });
263
271
  }
264
272
  }
265
273
  return retired;
@@ -270,23 +278,39 @@ function orphanCeilingNets(active) {
270
278
  return ceiling.length === active.length ? [] : ceiling;
271
279
  }
272
280
 
273
- const sweepOrphanCeilingNets = ({ patientCode, trace, isLive }) => retireCeilingNets({
281
+ const sweepOrphanCeilingNets = ({ patientCode, trace, isLive }) => retireNets({
274
282
  patientCode, trace, isLive, select: orphanCeilingNets, context: 'while sweeping an orphan',
275
283
  });
276
284
 
277
- const supersedeForEscalation = ({ patientCode, trace, isLive }) => retireCeilingNets({
285
+ const supersedeForEscalation = ({ patientCode, trace, isLive }) => retireNets({
278
286
  patientCode, trace, isLive, select: (active) => active.filter(isCeilingNet), context: 'after the escalation armed',
279
287
  });
280
288
 
289
+ // A patient sent to urgencias gets no later check-in, neither the ceiling one nor one left by a lower escalation.
290
+ const supersedeForStat = ({ patientCode, trace, isLive }) => retireNets({
291
+ patientCode, trace, isLive, select: (active) => active.filter((net) => isCeilingNet(net) || net?.carePlan?.armedBy === ARMED_BY.ESCALATION), context: 'for a stat escalation',
292
+ });
293
+
281
294
  function escalationUrgencyOf(net) {
282
295
  if (net?.carePlan?.armedBy !== ARMED_BY.ESCALATION) return null;
283
296
  const silence = net?.patientReminder?.firesAfterSilenceMinutes;
284
- return Object.keys(ESCALATION_SILENCE_MINUTES).find((level) => ESCALATION_SILENCE_MINUTES[level] === silence) || null;
297
+ const levels = Object.keys(ESCALATION_SILENCE_MINUTES);
298
+ return levels.find((level) => ESCALATION_SILENCE_MINUTES[level] === silence)
299
+ || levels.find((level) => LEGACY_ESCALATION_SILENCE_MINUTES[level] === silence)
300
+ || null;
285
301
  }
286
302
 
287
303
  async function armEscalationNet({ patientCode, urgencyLevel, symptom, suspectedCondition = null, checkIn = null, trace = null, isLive = null }) {
304
+ if (!Object.hasOwn(ESCALATION_SILENCE_MINUTES, urgencyLevel)) return { armed: false, reason: 'urgency_not_covered' };
288
305
  const silence = ESCALATION_SILENCE_MINUTES[urgencyLevel];
289
- if (!silence) return { armed: false, reason: 'urgency_not_covered' };
306
+ // stat gets no check-in of its own; it only clears the check-ins already armed.
307
+ if (!silence) {
308
+ const superseded = await supersedeForStat({ patientCode, trace, isLive }).catch((error) => {
309
+ logger.warn('[contingency] check-ins not retired for a stat escalation', { patientCode, error: error?.message });
310
+ return [];
311
+ });
312
+ return { armed: false, reason: 'level_without_check_in', superseded };
313
+ }
290
314
 
291
315
  await sweepOrphanCeilingNets({ patientCode, trace, isLive });
292
316
  const target = await escalationNetTarget(patientCode, { stepsAside: isCeilingNet, touched: casesTouchedThisTurn(trace) });
@@ -325,6 +349,7 @@ async function armEscalationNet({ patientCode, urgencyLevel, symptom, suspectedC
325
349
  firesAfterSilenceMinutes: silence,
326
350
  windowReasoning: contingency.patientReminder.windowReasoning,
327
351
  extra: { armedBy: 'escalation', escalationUrgency: urgencyLevel },
352
+ checkInWindow: checkInWindowFor(urgencyLevel),
328
353
  });
329
354
 
330
355
  const out = await commitMachineNet({ patientCode, contingency, caseId: null, trace, isLive, planId, stepsAside: isCeilingNet });
@@ -343,7 +368,7 @@ async function armContingency({ contingency, patientCode, trace = null, isLive =
343
368
  isLive,
344
369
  actionType,
345
370
  reminderId: `${carePlan.planId}-patient`,
346
- reminderDateUtc: dueAt(carePlan.createdAt, patientReminder.firesAfterSilenceMinutes),
371
+ reminderDateUtc: dueAt(carePlan.createdAt, patientReminder.firesAfterSilenceMinutes, checkInWindowFor(escalationUrgencyOf(contingency))),
347
372
  reminderType: 'contingency',
348
373
  description: patientReminder.message,
349
374
  firesAfterSilenceMinutes: patientReminder.firesAfterSilenceMinutes,
@@ -468,4 +493,4 @@ async function applyContingencyEvent({ patientCode, planId, stage, event, at = n
468
493
  return { applied: true, status: next, teamStageArmed: handoff.armed, ...(handoff.armed ? {} : { teamStageReason: handoff.reason }) };
469
494
  }
470
495
 
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 };
496
+ module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW, ASAP_CHECK_IN_WINDOW };
@@ -0,0 +1,40 @@
1
+ const { rtContextBlockLive } = require('../flags/clinicalContextFlags');
2
+ const { Estado_General_ID, Symptoms_ID } = require('../../config/airtableConfig');
3
+ const { escapeFormulaValue, fieldEquals } = require('../../helpers/airtableFormulaHelper');
4
+ const { getRecordByFilter } = require('../../services/airtableService');
5
+ const { logger } = require('../../utils/logger');
6
+ const { withTimeout } = require('../../utils/timeoutUtils');
7
+ const { latestCourse, renderRadiotherapyBlock } = require('./radiotherapyPhaseService');
8
+
9
+ const ZONE_FIELDS = ['rt_zona', 'rt_zona_confirmada'];
10
+ const FACT_FIELDS = ['value_text', 'normalized_value', 'report_date'];
11
+ const READ_TIMEOUT_MS = 2000;
12
+
13
+ const courseFacts = (code) => getRecordByFilter(
14
+ Estado_General_ID,
15
+ 'facts',
16
+ `AND({variable}='radiotherapy_summary', ARRAYJOIN({whatsapp_id (from patient)})='${escapeFormulaValue(code)}')`,
17
+ null,
18
+ FACT_FIELDS,
19
+ );
20
+
21
+ async function radiotherapyBlockFor(code, now) {
22
+ try {
23
+ if (!rtContextBlockLive() || !code) return '';
24
+ const [zones, facts] = await withTimeout(Promise.all([
25
+ getRecordByFilter(Symptoms_ID, 'estado_general', fieldEquals('whatsapp_id', code), 'Grid view', ZONE_FIELDS),
26
+ courseFacts(code),
27
+ ]), READ_TIMEOUT_MS, 'radiotherapy context read');
28
+ const row = zones?.[0] || {};
29
+ return renderRadiotherapyBlock({
30
+ zona: row.rt_zona || null, confirmada: Boolean(row.rt_zona_confirmada), curso: latestCourse(facts), now,
31
+ });
32
+ } catch (error) {
33
+ logger.warn('[radiotherapyContext] block left out', { error: error?.message });
34
+ return '';
35
+ }
36
+ }
37
+
38
+ const withRadiotherapyBlock = (block, rtBlock) => (rtBlock ? [block, rtBlock].filter(Boolean).join('\n\n') : block);
39
+
40
+ module.exports = { radiotherapyBlockFor, withRadiotherapyBlock };
@@ -0,0 +1,272 @@
1
+ const {
2
+ addDays, daysBetween, formatDmy, mexicoDay,
3
+ } = require('../../utils/dateUtils');
4
+ const { foldAccents } = require('../../utils/formatUtils');
5
+ const { safeParse } = require('../../utils/jsonUtils');
6
+
7
+ const SKIN = 'enrojecimiento que se extiende fuera de la zona tratada, calor o pus';
8
+ const PELVIC_NEVER = Object.freeze(['no poder orinar', SKIN]);
9
+ const PELVIC_LATE = Object.freeze(['dolor nuevo de cadera, ingle o sacro al caminar']);
10
+
11
+ // Recomendaciones aprobadas el 22-oct-2026 (propuesta para firma de radioterapia); pendiente el visto bueno del servicio
12
+ const RT_DRAFT = Object.freeze({
13
+ ACUTE_DAYS: 90,
14
+ STALE_DAYS: 10,
15
+ SRS_EARLY_DAYS: 7,
16
+ SRS_MAX_FRACTIONS: 5,
17
+ GENERAL_EXPECTED: Object.freeze(['fatiga', 'falta de apetito', 'dolor o molestia en la zona tratada']),
18
+ NEVER_EXPECTED: Object.freeze(['fiebre de 38.0 °C o más', 'síntoma neurológico nuevo (debilidad, convulsión, confusión, dolor de cabeza con vómito)']),
19
+ SEVERITY: 'Esperable describe la causa probable, no la gravedad: no poder beber o tragar, más de 7 evacuaciones al día sobre lo habitual, pérdida de 5 % del peso o piel abierta e infectada no son esperables en ninguna fase.',
20
+ SEQUELAE: 'Secuelas persistentes ya conocidas (boca seca, fibrosis, piel más oscura, linfedema ya conocido) pueden seguir presentes.',
21
+ IMMUNOTHERAPY: 'Si recibe inmunoterapia al mismo tiempo, tos, diarrea o erupción en la piel nuevas no se atribuyen a la radioterapia.',
22
+ PELVIC_BLEEDING: 'Sangrado rectal o en la orina: puede ser un efecto tardío conocido, pero la radioterapia no lo explica sin evaluación.',
23
+ ZONES: Object.freeze({
24
+ 'pelvis femenina': {
25
+ expected: ['diarrea o evacuaciones blandas', 'cólicos o dolor abdominal', 'ardor o urgencia al orinar', 'flujo vaginal', 'irritación de la piel en pliegues de la zona'],
26
+ never: PELVIC_NEVER, late: PELVIC_LATE, pelvic: true,
27
+ },
28
+ 'pelvis masculina': {
29
+ expected: ['diarrea o evacuaciones blandas', 'ardor o urgencia al orinar', 'chorro débil', 'urgencia para evacuar', 'irritación de la piel en pliegues de la zona'],
30
+ never: PELVIC_NEVER, late: PELVIC_LATE, pelvic: true,
31
+ },
32
+ pelvis: {
33
+ expected: ['diarrea o evacuaciones blandas', 'ardor o urgencia al orinar', 'urgencia para evacuar', 'irritación de la piel en pliegues de la zona'],
34
+ never: PELVIC_NEVER, late: PELVIC_LATE, pelvic: true,
35
+ },
36
+ mama: {
37
+ expected: ['reacción de la piel en la zona tratada (enrojecimiento, comezón, descamación)', 'oscurecimiento de la piel', 'hinchazón o sensibilidad de la mama'],
38
+ never: ['hinchazón súbita y dolorosa del brazo', 'si se irradiaron los ganglios: tos o falta de aire nuevas de 1 a 6 meses después del fin', SKIN],
39
+ },
40
+ 'cabeza y cuello': {
41
+ expected: ['dolor al tragar', 'llagas en la boca', 'boca seca o saliva espesa y flema', 'cambios en el gusto', 'ronquera', 'reacción de la piel del cuello', 'pérdida leve de peso'],
42
+ never: ['sangrado por la boca, el cuello o la traqueostomía', 'ruido al respirar o falta de aire', 'no tolerar líquidos ni la alimentación por sonda',
43
+ 'mareo al pararse u orina escasa (deshidratación)', SKIN],
44
+ },
45
+ torax: {
46
+ expected: ['dolor o ardor al tragar', 'acidez'],
47
+ activeOnly: ['tos leve'],
48
+ never: ['falta de aire en reposo', 'dolor en el pecho o tos con sangre', 'tos o falta de aire nuevas de 1 a 6 meses después del fin (hasta 12 meses con SBRT o inmunoterapia)'],
49
+ },
50
+ abdomen: { expected: ['náuseas', 'diarrea'], never: [] },
51
+ 'cerebro holocraneal': {
52
+ expected: ['somnolencia', 'náuseas leves', 'caída del cabello'],
53
+ never: [],
54
+ lateEffects: 'Problemas de memoria o de concentración pueden ser un efecto tardío de la radioterapia al cerebro.',
55
+ },
56
+ radiocirugia: {
57
+ earlyExpected: ['dolor de cabeza leve y náuseas los primeros ~7 días'],
58
+ expected: [],
59
+ never: ['dolor de cabeza nuevo o que empeora después de los primeros ~7 días'],
60
+ },
61
+ 'cerebro sin tecnica': { expected: [], never: [] },
62
+ 'hueso u otra': {
63
+ expected: ['aumento pasajero del dolor en el sitio tratado los primeros días'],
64
+ never: ['debilidad en las piernas, pérdida de control de esfínteres o de sensibilidad (posible compresión medular)', 'fractura del hueso tratado', SKIN],
65
+ },
66
+ }),
67
+ ZONE_ALIASES: Object.freeze({
68
+ prostata: 'pelvis masculina',
69
+ recto: 'pelvis',
70
+ vejiga: 'pelvis',
71
+ cervix: 'pelvis femenina',
72
+ cervicouterino: 'pelvis femenina',
73
+ endometrio: 'pelvis femenina',
74
+ utero: 'pelvis femenina',
75
+ vulva: 'pelvis femenina',
76
+ vagina: 'pelvis femenina',
77
+ laringe: 'cabeza y cuello',
78
+ orofaringe: 'cabeza y cuello',
79
+ nasofaringe: 'cabeza y cuello',
80
+ 'cavidad oral': 'cabeza y cuello',
81
+ esofago: 'torax',
82
+ pulmon: 'torax',
83
+ cerebro: 'cerebro holocraneal',
84
+ holocraneal: 'cerebro holocraneal',
85
+ }),
86
+ });
87
+
88
+ const PHASE = Object.freeze({
89
+ PLANNED: 'planeada',
90
+ START_UNCONFIRMED: 'inicio_por_confirmar',
91
+ ACTIVE: 'en_curso',
92
+ RECENT: 'terminada',
93
+ HISTORY: 'antecedente',
94
+ UNCONFIRMED: 'por_confirmar',
95
+ UNKNOWN: 'sin_fechas',
96
+ });
97
+ const SERVICE_ORIGIN = 'servicio_radioterapia';
98
+ const WORKDAYS_PER_WEEK = 5;
99
+ const STATUS_ALIASES = Object.freeze({
100
+ completed: 'completed', completado: 'completed', terminada: 'completed',
101
+ active: 'active', ongoing: 'active', 'en curso': 'active',
102
+ planned: 'planned', planificado: 'planned', planeada: 'planned',
103
+ });
104
+ const SRS_TECHNIQUE = /radiocirug|\bsrs\b|\bsbrt\b|estereot/i;
105
+ const HEADER = 'Radioterapia';
106
+ const BRAIN_KIND = Object.freeze({
107
+ radiocirugia: ' (radiocirugía)',
108
+ 'cerebro sin tecnica': ` (tipo de tratamiento no registrado; con ${RT_DRAFT.SRS_MAX_FRACTIONS} sesiones o menos puede ser radiocirugía u holocraneal)`,
109
+ });
110
+
111
+ const fold = (text) => foldAccents(text).trim().toLowerCase();
112
+ const isDay = (value) => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value);
113
+ const isWorkday = (day) => ![0, 6].includes(new Date(`${day}T00:00:00Z`).getUTCDay());
114
+
115
+ function shiftWorkdays(day, count) {
116
+ const step = count < 0 ? -1 : 1;
117
+ let at = day;
118
+ for (let left = Math.abs(count); left > 0;) {
119
+ at = addDays(at, step);
120
+ if (isWorkday(at)) left -= 1;
121
+ }
122
+ return at;
123
+ }
124
+
125
+ function workdaysThrough(from, to) {
126
+ let count = 0;
127
+ for (let at = from; at <= to; at = addDays(at, 1)) if (isWorkday(at)) count += 1;
128
+ return count;
129
+ }
130
+
131
+ const normalizeStatus = (status) => STATUS_ALIASES[fold(status)] || null;
132
+
133
+ function courseFromEntry(entry) {
134
+ const sesiones = Number(entry.sessions_planned ?? entry.fractions_planned);
135
+ return {
136
+ inicio: isDay(entry.start_date) ? entry.start_date : null,
137
+ fin: isDay(entry.end_date) ? entry.end_date : null,
138
+ sesiones: Number.isInteger(sesiones) && sesiones > 0 ? sesiones : null,
139
+ estado: normalizeStatus(entry.status),
140
+ tecnica: typeof entry.technique === 'string' ? entry.technique : null,
141
+ };
142
+ }
143
+
144
+ function courseFromFact(fact) {
145
+ const normalized = safeParse(fact?.normalized_value) || {};
146
+ const entry = (Array.isArray(normalized.add) ? normalized.add : []).find((item) => item?.start_date || item?.end_date || item?.status);
147
+ return entry ? courseFromEntry(entry) : null;
148
+ }
149
+
150
+ const originOf = (fact) => safeParse(fact?.normalized_value)?.origin || null;
151
+
152
+ // the unit's register wins over facts extracted from conversation; newest report first within each
153
+ function latestCourse(facts) {
154
+ const rows = (Array.isArray(facts) ? facts : []).filter(Boolean);
155
+ if (!rows.length) return null;
156
+ const newest = (a, b) => String(b.report_date ?? '').localeCompare(String(a.report_date ?? ''));
157
+ const service = rows.filter((fact) => originOf(fact) === SERVICE_ORIGIN).sort(newest);
158
+ return courseFromFact((service.length ? service : [...rows].sort(newest))[0]);
159
+ }
160
+
161
+ function zoneProfile(zona, curso) {
162
+ if (!zona) return null;
163
+ const key = fold(zona);
164
+ let canonical = RT_DRAFT.ZONES[key] ? key : RT_DRAFT.ZONE_ALIASES[key] || null;
165
+ if (canonical === 'cerebro holocraneal' && SRS_TECHNIQUE.test(curso?.tecnica || '')) canonical = 'radiocirugia';
166
+ else if (canonical === 'cerebro holocraneal' && curso?.sesiones && curso.sesiones <= RT_DRAFT.SRS_MAX_FRACTIONS) canonical = 'cerebro sin tecnica';
167
+ return canonical ? { key: canonical, ...RT_DRAFT.ZONES[canonical] } : { key: null, unrecognized: true };
168
+ }
169
+
170
+ function phaseOf(curso, today) {
171
+ const { sesiones, estado } = curso;
172
+ let { inicio } = curso;
173
+ const { fin } = curso;
174
+ if (!inicio && fin && sesiones) inicio = shiftWorkdays(fin, -(sesiones - 1));
175
+ if (inicio && today < inicio) return { phase: PHASE.PLANNED, inicio };
176
+ if (!inicio && !fin) return { phase: estado === 'planned' ? PHASE.PLANNED : PHASE.UNKNOWN };
177
+ if (estado === 'planned') return { phase: PHASE.START_UNCONFIRMED, inicio };
178
+ const finEstimado = !fin && inicio && sesiones ? shiftWorkdays(inicio, sesiones - 1) : null;
179
+ const end = fin || finEstimado;
180
+ if (!end) return { phase: PHASE.UNCONFIRMED, inicio, sinceStart: daysBetween(inicio, today) };
181
+ const estimated = Boolean(finEstimado);
182
+ const graceEnd = estimated && estado !== 'completed' ? addDays(end, RT_DRAFT.STALE_DAYS) : end;
183
+ if (today <= graceEnd) return { phase: PHASE.ACTIVE, inicio, end, estimated };
184
+ const days = daysBetween(end, today);
185
+ if (estimated && estado !== 'completed') return { phase: PHASE.UNCONFIRMED, end, days };
186
+ return { phase: days > RT_DRAFT.ACUTE_DAYS ? PHASE.HISTORY : PHASE.RECENT, end, days, estimated };
187
+ }
188
+
189
+ function phaseLine(state, sesiones) {
190
+ const estimated = state.estimated ? ' estimado (±1–2 semanas)' : '';
191
+ switch (state.phase) {
192
+ case PHASE.PLANNED:
193
+ return `Fase: planeada${state.inicio ? `, inicio previsto el ${formatDmy(state.inicio)}` : ''}. Aún no hay síntomas esperables por la radioterapia.`;
194
+ case PHASE.START_UNCONFIRMED:
195
+ return `Fase: inicio por confirmar: el inicio previsto (${formatDmy(state.inicio)}) ya pasó, pero no hay registro de que haya empezado. No se sabe si recibió radioterapia.`;
196
+ case PHASE.ACTIVE: {
197
+ const total = sesiones ? Math.ceil(sesiones / WORKDAYS_PER_WEEK) : null;
198
+ const elapsed = state.inicio ? Math.max(1, Math.ceil(workdaysThrough(state.inicio, state.today) / WORKDAYS_PER_WEEK)) : null;
199
+ const week = elapsed ? `, semana ~${total ? Math.min(elapsed, total) : elapsed}${total ? ` de ~${total}` : ''}` : '';
200
+ return `Fase: en curso${week}; fin${estimated} el ${formatDmy(state.end)}. ${week ? 'La sesión exacta no se conoce, solo la semana aproximada.' : 'No se conoce la semana del curso.'}`;
201
+ }
202
+ case PHASE.RECENT:
203
+ return `Fase: terminó hace ${state.days} días (fin${estimated} el ${formatDmy(state.end)}); ventana aguda hasta el ${formatDmy(addDays(state.end, RT_DRAFT.ACUTE_DAYS))} (fin + ${RT_DRAFT.ACUTE_DAYS} días). Ya no está en tratamiento de radioterapia.`;
204
+ case PHASE.HISTORY:
205
+ return `Fase: antecedente: terminó hace ${state.days} días (más de ${RT_DRAFT.ACUTE_DAYS}). ${RT_DRAFT.SEQUELAE} Un síntoma de la zona nuevo, que regresa o que empeora ya no se explica como efecto agudo: puede ser un efecto tardío o algo nuevo que el equipo no conoce.`;
206
+ case PHASE.UNCONFIRMED:
207
+ return state.end
208
+ ? `Fase: estado por confirmar: el fin estimado (${formatDmy(state.end)}, ±1–2 semanas) pasó hace ${state.days} días sin registro de término. No se sabe si ya terminó.`
209
+ : `Fase: estado por confirmar: inició el ${formatDmy(state.inicio)}, sin fin ni número de sesiones registrados. No se sabe si sigue en curso ni cuándo terminó.`;
210
+ default:
211
+ return 'Fase: sin fechas del curso registradas.';
212
+ }
213
+ }
214
+
215
+ function inAcuteWindow(state) {
216
+ if ([PHASE.ACTIVE, PHASE.RECENT].includes(state.phase)) return true;
217
+ if (state.phase !== PHASE.UNCONFIRMED) return false;
218
+ return state.end ? state.days <= RT_DRAFT.ACUTE_DAYS : state.sinceStart <= RT_DRAFT.ACUTE_DAYS;
219
+ }
220
+
221
+ const isSrsEarly = (state) => state.phase === PHASE.ACTIVE || (state.phase === PHASE.RECENT && state.days <= RT_DRAFT.SRS_EARLY_DAYS);
222
+
223
+ function courseLine(curso) {
224
+ const parts = [curso.tecnica, curso.sesiones && `${curso.sesiones} ${curso.sesiones === 1 ? 'sesión' : 'sesiones'}`,
225
+ curso.inicio && `inicio ${formatDmy(curso.inicio)}`, curso.fin && `fin ${formatDmy(curso.fin)}`].filter(Boolean);
226
+ return parts.length ? `Curso registrado: ${parts.join(', ')}.` : null;
227
+ }
228
+
229
+ const UNKNOWN_ZONE = 'sin zona confirmada no se sabe qué síntomas explica la radioterapia.';
230
+
231
+ function zoneLine(zona, confirmada, profile) {
232
+ if (!zona) return `Zona tratada: no registrada; ${UNKNOWN_ZONE}`;
233
+ if (profile.unrecognized) return `Zona tratada: ${zona} (zona no reconocida); solo aplican los datos generales.`;
234
+ const kind = BRAIN_KIND[profile.key] || '';
235
+ return confirmada ? `Zona tratada: ${zona}${kind}.` : `Zona tratada: ${zona}${kind} (sin confirmar por el médico); ${UNKNOWN_ZONE}`;
236
+ }
237
+
238
+ function expectedFor(profile, confirmada, state) {
239
+ const zone = confirmada && profile && !profile.unrecognized ? [
240
+ ...(profile.expected || []),
241
+ ...(state.phase === PHASE.ACTIVE ? profile.activeOnly || [] : []),
242
+ ...(isSrsEarly(state) ? profile.earlyExpected || [] : []),
243
+ ] : [];
244
+ return [...RT_DRAFT.GENERAL_EXPECTED, ...zone];
245
+ }
246
+
247
+ function renderRadiotherapyBlock({ zona = null, confirmada = false, curso = null, now = Date.now() } = {}) {
248
+ const zone = typeof zona === 'string' && zona.trim() ? zona.trim() : null;
249
+ if (!zone && !curso) return '';
250
+ const today = mexicoDay(new Date(now));
251
+ const profile = zoneProfile(zone, curso);
252
+ const state = { ...phaseOf(curso || {}, today), today };
253
+ const acute = inAcuteWindow(state);
254
+ const history = state.phase === PHASE.HISTORY;
255
+ const never = [...RT_DRAFT.NEVER_EXPECTED, ...(profile?.never || []), ...(history ? profile?.late || [] : [])];
256
+ const lines = [
257
+ zoneLine(zone, confirmada, profile || {}),
258
+ curso && courseLine(curso),
259
+ phaseLine(state, curso?.sesiones),
260
+ acute && `Esperables en esta fase: ${expectedFor(profile, confirmada, state).join(', ')}.`,
261
+ acute && RT_DRAFT.SEVERITY,
262
+ history && profile?.lateEffects,
263
+ `No se explican por la radioterapia: ${never.join('; ')}.`,
264
+ profile?.pelvic && RT_DRAFT.PELVIC_BLEEDING,
265
+ RT_DRAFT.IMMUNOTHERAPY,
266
+ ].filter(Boolean);
267
+ return `${HEADER}:\n- ${lines.join('\n- ')}`;
268
+ }
269
+
270
+ module.exports = {
271
+ latestCourse, renderRadiotherapyBlock,
272
+ };
@@ -74,6 +74,7 @@ const { prepareSupportAction } = require('./supportActionService');
74
74
  const GENERATION_BACKOFF_MS = 10 * 60 * 1000;
75
75
  const GATE_MAX_ATTEMPTS = 2;
76
76
  const PLAN_MAX_ATTEMPTS = 2;
77
+ const MAX_TRIAGE_CARDS = 10;
77
78
  const PLAN_TRUNCATION_MAX_TOKENS = 16000;
78
79
  const DEFAULT_PROVIDER_RETRY_BACKOFF_MS = [15000, 45000];
79
80
  const DEFAULT_SETTLE_WRITE_BACKOFF_MS = [1000, 5000];
@@ -619,6 +620,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
619
620
  settle.qualityWarnings = [...gateWarnings, ...qualityWarnings];
620
621
  settle.rankReordered = planOutcome.rankReordered;
621
622
  settle.deniedCardsDropped = planOutcome.deniedCardsDropped;
623
+ settle.cardsTruncated = planOutcome.cardsTruncated;
622
624
  settle.deniedTargetsStripped = planOutcome.deniedTargetsStripped;
623
625
 
624
626
  try {
@@ -878,6 +880,14 @@ function issuePaths(issues) {
878
880
  return [...new Set(issues.map((issue) => String(issue.path || '').replace(/\[[^\]]*\]/g, '[]')).filter(Boolean))];
879
881
  }
880
882
 
883
+ function truncateToCardLimit(elements, repairs) {
884
+ const excess = elements.length - MAX_TRIAGE_CARDS;
885
+ if (excess <= 0) return 0;
886
+ const cut = elements.splice(MAX_TRIAGE_CARDS);
887
+ repairs.push(`tarjetas recortadas al máximo del carrusel: ${MAX_TRIAGE_CARDS + excess} -> ${MAX_TRIAGE_CARDS} (rangos ${cut.map((e) => e.rank).join(',')})`);
888
+ return excess;
889
+ }
890
+
881
891
  async function runPlan({ provider, presetId, casoBase, gate, boundary = null, rankContext = {}, rid, code, payload }) {
882
892
  const planInput = `${casoBase}\n\n### Gate de seguridad comprometido (PASO 1)\n${JSON.stringify(buildLegacyStep1(gate))}`;
883
893
  let lastIssues = [];
@@ -908,6 +918,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
908
918
  let rankReordered = 0;
909
919
  let deniedCardsDropped = 0;
910
920
  let deniedTargetsStripped = 0;
921
+ let cardsTruncated = 0;
911
922
  const budget = newTransientBudget();
912
923
  for (let attempt = 1; attempt <= PLAN_MAX_ATTEMPTS; attempt += 1) {
913
924
  const content = attempt === 1 || !lastIssues.length
@@ -967,6 +978,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
967
978
  return outcome({ attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_all_denied', hardRejectIssues: lastIssues } });
968
979
  }
969
980
  rankReordered = applyRankOrder(elements, gate, repairs, rankContext);
981
+ cardsTruncated = truncateToCardLimit(elements, repairs);
970
982
  const issues = validate(elements, { gate, lane: 'triage', urgentReframed });
971
983
  const blocking = blockingIssues(issues);
972
984
  if (blocking.length) {
@@ -991,6 +1003,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
991
1003
  rankReordered,
992
1004
  deniedCardsDropped,
993
1005
  deniedTargetsStripped,
1006
+ cardsTruncated,
994
1007
  modelInput: content,
995
1008
  model: typeof result?.model === 'string' ? result.model : null,
996
1009
  });
@@ -7,7 +7,7 @@ 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 { escalationAssessmentLive, escalationUpdateModeLive, feverPatientTimerLive } = require('../flags/escalationFlags');
10
+ const { escalationAssessmentLive, escalationPatientTimerLive, escalationUpdateModeLive, feverPatientTimerLive } = require('../flags/escalationFlags');
11
11
  const { alertWithoutEmergencyRow, attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
12
12
  const { URGENCY_RANK } = require('../../models/escalationReviewModel');
13
13
  const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
@@ -21,7 +21,7 @@ const FEVER_RULE = 'Fever that is `stat`: ≥38.0 °C within 8 weeks of cytotoxi
21
21
 
22
22
  const definition = {
23
23
  'name': 'reportMedicalEscalation',
24
- 'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; the payload is INTERNAL — the patient never sees it.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate without a further clarifying question: `asap` by default, `stat` if there is an acute deficit (can\'t walk/stand, sphincter loss, bilateral leg weakness → possible cord compression) or any instability.\n\n**When NOT to call:**\n- An open case in `turn_focus.team_cases` already covers this symptom at this level or higher. Read it before calling (load `getRouterContextBundle` first if you have not this turn). Call again, as an update, only for a new symptom, a higher grade, a new red flag, a detail that makes something more serious plausible, or a symptom that persists or worsens while the team has not answered; a characterization detail that changes none of these needs no call. Otherwise tell the patient where the case stands.\n- Unconfirmed/unspecific symptom — ask ONE characterization question via `DeliverPatientMessage` first.\n- Active mental-health crisis — use `reportCrisis`.\n- Patient shared lab/imaging/values/files — use `reportResultsReceived`.\n- Administrative / operative matter (appointments, insurance, authorizations, letters, transport, scheduling, out-of-scope request) or a non-clinical referral (psico-oncología, paliativos, non-oncology medical) — use `reportUnresolvedRequestv2`.\n- Twice in the same turn for the same episode — already committed; a later datum belongs to the same open escalation.\n\n**After the commit:** the escalation does not end the conversation.\n- **Patient message** (`DeliverPatientMessage`, calm, ≤60 words): acknowledge what they told you → \'Ya avisé al equipo médico\' → ONE concrete next step → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside `stat` and the fever rule, no warning signs by default: naming a sign the patient did not mention makes them watch for it and feel it. If one is truly needed, give at most ONE per episode, about the symptom they already reported getting worse or not easing (\'si el dolor no cede con lo que tomas, escríbeme y lo vemos\') — never another body part or symptom, never a list (not even of related symptoms), never the last line. Outside `stat` never write \'de inmediato\', \'con urgencia\', \'máxima urgencia\', \'no esperes\', \'por si acaso\' or \'es poco probable, pero\' — not in \'escríbeme de inmediato\' nor in \'ya avisé con urgencia\': the priority travels to the team, not to the patient. Explain the purpose only in general words (\'para revisar qué está pasando y ver si necesitas algo más\'): never name an organ, a complication, a mechanism or what is being ruled out (\'descartar que sea del corazón\', \'una presión en la columna\') — to an oncology patient that reads as a diagnosis. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` is the ONLY level that sends the patient now — calm and unambiguous: ve a urgencias ahora, acompañado; 911 (or an ambulance) if they are alone with no one to take them, cannot move safely, or are unstable — being alone counts as unsafe transport, and they never drive themselves. ' + FEVER_RULE + '`asap` and `urgent`: no urgencias and no 911 in the message, not even as a condition — the team decides where they are seen (two exceptions: the fever rule, and chest pain with only mild or doubtful shortness of breath, kept at `asap`, where one calm conditional line stays: \'si te cuesta más respirar o el dolor aumenta, ve a urgencias acompañado\'). If they ask whether to go to urgencias or what to watch, answer honestly with 1–2 points about their symptom — the only case where more than one sign is fine. Chest pain alone is not `stat` (anxiety, gastritis, muscle); chest pain WITH clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw IS `stat` (on checkpoint-inhibitor immunotherapy, chest pain is at least `asap`) — even if the patient sounds calm, and even if the two come in different messages of the same episode; otherwise ask ONE question first. `routine`: acknowledgement and when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, after the instruction only confirm they are on their way and accompanied.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and make the fallback explicit to the patient whenever nothing is armed. `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
24
+ 'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; the payload is INTERNAL — the patient never sees it.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate without a further clarifying question: `asap` by default, `stat` if there is an acute deficit (sudden weakness of an arm, a leg or one side — even if they can still move it —, can\'t walk/stand, sphincter loss, bilateral leg weakness → possible cord compression) or any instability; an acute deficit is must-go.\n\n**When NOT to call:**\n- An open case in `turn_focus.team_cases` already covers this symptom at this level or higher. Read it before calling (load `getRouterContextBundle` first if you have not this turn). Call again, as an update, only for a new symptom, a higher grade, a new red flag, a detail that makes something more serious plausible, or a symptom that persists or worsens while the team has not answered; a characterization detail that changes none of these needs no call. Otherwise tell the patient where the case stands.\n- Unconfirmed/unspecific symptom — ask ONE characterization question via `DeliverPatientMessage` first.\n- Active mental-health crisis — use `reportCrisis`.\n- Patient shared lab/imaging/values/files — use `reportResultsReceived`.\n- Administrative / operative matter (appointments, insurance, authorizations, letters, transport, scheduling, out-of-scope request) or a non-clinical referral (psico-oncología, paliativos, non-oncology medical) — use `reportUnresolvedRequestv2`.\n- Twice in the same turn for the same episode — already committed; a later datum belongs to the same open escalation.\n\n**After the commit:** the escalation does not end the conversation.\n- **Patient message** (`DeliverPatientMessage`, calm, ≤60 words): acknowledge what they told you → \'Ya avisé al equipo médico\' → ONE concrete next step (a `stat` that is not must-go has none) → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside a must-go `stat` and the fever rule, no warning signs by default: naming a sign the patient did not mention makes them watch for it and feel it. If one is truly needed, give at most ONE per episode, about the symptom they already reported getting worse or not easing (\'si el dolor no cede con lo que tomas, escríbeme y lo vemos\') — never another body part or symptom, never a list (not even of related symptoms), never the last line. Outside a must-go `stat` never write \'de inmediato\', \'con urgencia\', \'máxima urgencia\', \'no esperes\', \'por si acaso\' or \'es poco probable, pero\' — not in \'escríbeme de inmediato\' nor in \'ya avisé con urgencia\': the priority travels to the team, not to the patient. Explain the purpose only in general words (\'para revisar qué está pasando y ver si necesitas algo más\'): never name an organ, a complication, a mechanism or what is being ruled out (\'descartar que sea del corazón\', \'una presión en la columna\') — to an oncology patient that reads as a diagnosis. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` asks no characterization question (the fever rule keeps its question about the treatment and the last dose; who can take them is part of the urgencias instruction), and it is the ONLY level that may send the patient now — only for fever (the fever rule below) or when it cannot wait for the team (must-go): bleeding that does not stop; fainting or loss of consciousness; INTENSE shortness of breath at rest (mild breathlessness at rest is not must-go); chest pain with CLEAR shortness of breath, cold sweat, or spreading to the arm or jaw; sudden confusion or a seizure; SUDDEN inability to walk or stand, or sudden weakness (a known, long-standing limitation is not sudden); possible cord compression — weakness in both legs or loss of bladder or bowel control, even if it came on over hours or days; anaphylaxis, only once it is well characterized — the patient confirms swelling of the tongue or throat, trouble swallowing, breathing or speaking (hoarse voice, wheezing), or hives all over WITH dizziness or fainting (more likely after an infusion, a new drug or an antibiotic); swollen lips, hives or a "strange" throat on their own are not enough; shock — skin that is cold and sweaty, mottled, or very pale or greyish TOGETHER WITH strong dizziness on standing, marked weakness or drowsiness, a racing heart, or almost no urine (none in 12 hours or more). Not must-go: hives or itching alone, mouth sores or swelling from mucositis, a puffy face from steroids, throat tightness brought on by cold after oxaliplatin, or cold hands or pallor alone. When a sign is only partly described (swollen lips, hives or a strange throat with nothing else; pale and weak), it is not confirmed yet: ask ONE question about the missing part before choosing the level (\'¿Ahorita tienes hinchazón de lengua o garganta, dificultad para tragar o respirar, voz ronca, o mareo?\' / \'¿Te mareas o casi te desmayas al ponerte de pie, y cuándo orinaste por última vez?\'). Confusion or drowsiness that is slowly increasing, or major bleeding that has already stopped, is not must-go. Any confirmed must-go sign is `stat`, never `asap`. Then calm and unambiguous: ve a urgencias ahora, acompañado; 911 (or an ambulance) if they are alone with no one to take them, cannot move safely, or are unstable — being alone counts as unsafe transport, and they never drive themselves. For anaphylaxis, 911 first, whether or not they are alone; if they have an adrenaline autoinjector, use it now; if they feel dizzy, lie down with the legs raised and do not stand up suddenly. Any other `stat` (not must-go, not fever): only the acknowledgement (\'Ya avisé al equipo médico\') and the availability line — no urgencias, no 911, no question; if the patient asks whether to go to urgencias or says it is getting worse, check it again against the must-go list and answer honestly. ' + FEVER_RULE + '`asap` and `urgent`: no urgencias and no 911 in the message, not even as a condition — the team decides where they are seen (two exceptions: the fever rule, and chest pain with only mild or doubtful shortness of breath, kept at `asap`, where one calm conditional line stays: \'si te cuesta más respirar o el dolor aumenta, ve a urgencias acompañado\'). If they ask whether to go to urgencias or what to watch, answer honestly with 1–2 points about their symptom — the only case where more than one sign is fine. Chest pain alone is not `stat` (anxiety, gastritis, muscle); chest pain WITH clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw IS `stat` (on checkpoint-inhibitor immunotherapy, chest pain is at least `asap`) — even if the patient sounds calm, and even if the two come in different messages of the same episode; otherwise ask ONE question first. `routine`: acknowledgement and when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, ask no characterization question: after a must-go instruction only confirm they are on their way and accompanied.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and, unless it says otherwise, make the fallback explicit to the patient whenever nothing is armed. `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
25
25
  'strict': true,
26
26
  'parameters': {
27
27
  'type': 'object',
@@ -34,7 +34,7 @@ const definition = {
34
34
  'urgent',
35
35
  'routine'
36
36
  ],
37
- 'description': 'Tier of medical escalation — the FHIR request-priority code (RequestPriority), a RELATIVE urgency ordered routine < urgent < asap < stat. It encodes priority / speed-of-action, NOT a fixed time window — the per-case clock is safety_gate.max_action_time_hours. 1:1 with the gate route. In urgency_justification say why this level and not the one above or below.\n- `stat` (inmediato, gate emergencia) — acción inmediata, prioridad máxima, flujo de emergencia. Inestabilidad o amenaza vital: ' + FEVER_RUBRIC_STAT + ' disnea severa, dolor de pecho con falta de aire clara, alteración del estado mental, sangrado mayor, compresión medular con déficit agudo.\n- `asap` (lo antes posible, gate urgencias) — máxima prioridad NO inmediata; objetivo interno de valoración en horas (no se le promete al paciente), porque la demora puede crear riesgo; el paciente no va a urgencias; el equipo decide dónde se le valora. Complicación seria sospechada pero aún no claramente inestable: dolor que empeora rápido, ' + FEVER_RUBRIC_ASAP + ' síntoma neurológico nuevo sin déficit agudo.\n- `urgent` (urgente, gate equipo_tratante_hoy) — objetivo interno de revisión en 24 h (no se le promete al paciente), por encima de rutina porque la demora podría importar clínicamente; el paciente puede seguir en casa: síntoma nuevo moderado, anormalidad de laboratorio preocupante pero estable, toxicidad de tratamiento que necesita input oportuno.\n- `routine` (rutina, sin gate o verdict suavizado) — prioridad normal, vía de atención habitual. Sin riesgo por demora: seguimiento, aclaración de medicación, síntoma >72h sin empeorar, contexto clínico desactualizado.'
37
+ 'description': 'Tier of medical escalation — the FHIR request-priority code (RequestPriority), a RELATIVE urgency ordered routine < urgent < asap < stat. It encodes priority / speed-of-action, NOT a fixed time window — the per-case clock is safety_gate.max_action_time_hours. 1:1 with the gate route. In urgency_justification say why this level and not the one above or below.\n- `stat` (inmediato, gate emergencia) — acción inmediata, prioridad máxima, flujo de emergencia. Inestabilidad o amenaza vital: ' + FEVER_RUBRIC_STAT + ' disnea severa, dolor de pecho con falta de aire clara, alteración del estado mental, sangrado mayor, compresión medular con déficit agudo, anafilaxia confirmada (hinchazón de lengua o garganta, dificultad para tragar, respirar o hablar, o ronchas en todo el cuerpo con mareo), choque (piel fría y sudorosa, manchada o grisácea junto con mareo al pararse, mucha debilidad, corazón acelerado o casi no orinar). Cualquier dato confirmado de la lista de ir sí o sí (descrita en la descripción de la herramienta, incluida la posible compresión medular aunque venga en horas o días) es `stat`, nunca `asap`.\n- `asap` (lo antes posible, gate urgencias) — máxima prioridad NO inmediata; objetivo interno de valoración en horas (no se le promete al paciente), porque la demora puede crear riesgo; el paciente no va a urgencias; el equipo decide dónde se le valora. Complicación seria sospechada pero aún no claramente inestable: dolor que empeora rápido, ' + FEVER_RUBRIC_ASAP + ' síntoma neurológico nuevo sin déficit agudo.\n- `urgent` (urgente, gate equipo_tratante_hoy) — objetivo interno de revisión en 24 h (no se le promete al paciente), por encima de rutina porque la demora podría importar clínicamente; el paciente puede seguir en casa: síntoma nuevo moderado, anormalidad de laboratorio preocupante pero estable, toxicidad de tratamiento que necesita input oportuno.\n- `routine` (rutina, sin gate o verdict suavizado) — prioridad normal, vía de atención habitual. Sin riesgo por demora: seguimiento, aclaración de medicación, síntoma >72h sin empeorar, contexto clínico desactualizado.'
38
38
  },
39
39
  'patient_check_in': {
40
40
  'anyOf': [
@@ -155,11 +155,17 @@ const MODE_PROPERTY = {
155
155
 
156
156
  const MODE_DESCRIPTION = '\n\n**mode:** `new` abre un aviso; `update` actualiza la escalación abierta y nunca baja su nivel. Lo que el paciente responde después de escalar va con `update`. El `urgency_level` del recibo es el nivel aplicado: puede ser mayor que el que pediste, nunca menor.';
157
157
 
158
- const FEVER_RULE_TIMER = 'Fever within 6 weeks (42 days) of cytotoxic chemotherapy (or with a hematologic cancer, transplant, known neutropenia) — ≥38.0 °C, ≤36.0 °C, feeling feverish or chills with no thermometer, or malaise while on an antipyretic or steroid — is `asap` with `category: febrile_neutropenia`. It is `stat` only with a clear, confirmed red flag (clear shortness of breath, clear confusion, strong rigors, mottled skin, bleeding), or any fever within 4 weeks of CAR-T or during bispecific step-up dosing — say it calmly: "ve a urgencias ahora y di que estás en tratamiento oncológico" (CAR-T / bispecific: call the treating center first). If you don\'t know the treatment or the last dose date, ask in the same message. 37.5–37.9 °C in that window is `urgent`: remeasure in 30–60 min. ';
158
+ // with the timer the fever rule sends to urgencias only from `stat`, like every other case
159
+ const FEVER_SIGNS = 'Outside a must-go `stat` and the fever rule, no warning signs';
160
+ const FEVER_SIGNS_TIMER = 'Outside a must-go `stat`, no warning signs';
161
+ const FEVER_URGENCIAS = '(two exceptions: the fever rule, and chest pain';
162
+ const FEVER_URGENCIAS_TIMER = '(one exception: chest pain';
163
+
164
+ const FEVER_RULE_TIMER = 'Fever within 6 weeks (42 days) of cytotoxic chemotherapy (or with a hematologic cancer, transplant, known neutropenia) — ≥38.0 °C, feeling feverish or chills with no thermometer, malaise while on an antipyretic or steroid, or ≤36.0 °C with malaise, chills or shivering — is `asap` with `category: febrile_neutropenia`. A low reading (≤36.0 °C) on its own is not fever: ask for an oral re-measure before escalating; still ≤36.0 °C with no other symptom is `urgent`, confirmed ≤35.0 °C is `asap`. Chills or rigors, even strong, are `asap`. It is `stat` only with a very obvious, confirmed red flag (clear shortness of breath at rest, clear confusion, fainting or unable to stand, mottled or cold skin, bleeding that does not stop), or any fever within 4 weeks of CAR-T or during bispecific step-up dosing — say it calmly: "ve a urgencias ahora y di que estás en tratamiento oncológico" (CAR-T / bispecific: call the treating center first). If you don\'t know the treatment or the last dose date, ask in the same message. 37.5–37.9 °C in that window is `urgent`: remeasure in 30–60 min. ';
159
165
 
160
166
  const FEVER_RUBRIC_STAT_TIMER = 'fiebre en la ventana de quimioterapia con una bandera roja confirmada (regla de fiebre),';
161
167
 
162
- const FEVER_RUBRIC_ASAP_TIMER = 'fiebre ≥38.0 °C o ≤36.0 °C en la ventana de quimioterapia sin bandera roja (regla de fiebre),';
168
+ const FEVER_RUBRIC_ASAP_TIMER = 'fiebre ≥38.0 °C, o ≤36.0 °C con malestar o escalofríos, o ≤35.0 °C confirmado, en la ventana de quimioterapia sin bandera roja (regla de fiebre),';
163
169
 
164
170
  const CLINICAL_ASSESSMENT_PROPERTY = nullable({
165
171
  'type': 'object',
@@ -217,7 +223,7 @@ function liveDefinition() {
217
223
  properties.details.required.push('clinical_assessment');
218
224
  }
219
225
  if (feverTimer) {
220
- live.description = live.description.replace(FEVER_RULE, FEVER_RULE_TIMER);
226
+ live.description = live.description.replace(FEVER_RULE, FEVER_RULE_TIMER).replace(FEVER_SIGNS, FEVER_SIGNS_TIMER).replace(FEVER_URGENCIAS, FEVER_URGENCIAS_TIMER);
221
227
  properties.urgency_level.description = properties.urgency_level.description
222
228
  .replace(FEVER_RUBRIC_STAT, FEVER_RUBRIC_STAT_TIMER)
223
229
  .replace(FEVER_RUBRIC_ASAP, FEVER_RUBRIC_ASAP_TIMER);
@@ -262,6 +268,9 @@ function followUpNote(armed, reason) {
262
268
  if (armed === null) {
263
269
  return 'This urgency tier gets NO automatic check-in. Nobody will write again on its own — make the fallback explicit in your message to the patient.';
264
270
  }
271
+ if (reason === 'level_without_check_in' && escalationPatientTimerLive()) {
272
+ return 'This level gets no automatic check-in by design: if nobody takes the case, the patient timer sends the numbers to call. Do not add a timed fallback; keep to the instruction for this level.';
273
+ }
265
274
  if (reason === 'active_net_exists') {
266
275
  return 'No check-in was armed for THIS escalation because one is already open for this patient — it may be tracking a different concern, so do not assume the patient will be asked about this one.';
267
276
  }
@@ -83,6 +83,10 @@ const sendMessageController = async (req, res) => {
83
83
  return res.status(400).json({ success: false, error: 'code is required' });
84
84
  }
85
85
 
86
+ if (!message && !fileUrl && !contentSid) {
87
+ return res.status(400).json({ success: false, error: 'message, fileUrl or contentSid is required' });
88
+ }
89
+
86
90
  try {
87
91
  let contact = {};
88
92
  if (contactCode) {
@@ -106,7 +106,7 @@ class EvalProvider {
106
106
  async _buildContext(numero, beforeCheckpoint) {
107
107
  const messages = await this.memoryManager.buildContext({
108
108
  thread: { code: numero },
109
- config: { beforeCheckpoint, beforeOperator: '$lt' },
109
+ config: { beforeCheckpoint, beforeOperator: '$lt', compactOlderTriage: true },
110
110
  });
111
111
 
112
112
  const lastUserMsg = [...messages].reverse().find(m => m.role === 'user');
@@ -1,3 +1,5 @@
1
+ const { decodeLiteralUnicodeEscapes } = require('../utils/jsonUtils');
2
+
1
3
  const PATIENT_MESSAGE_OPEN = '<patient_message>';
2
4
  const PATIENT_MESSAGE_CLOSE = '</patient_message>';
3
5
  const PATIENT_MESSAGE_BLOCK_RX = /<patient_message(?:\s[^>]*)?>\s*([\s\S]*?)\s*<\/patient_message\s*>/i;
@@ -58,7 +60,7 @@ function stripTurnMarkers(text) {
58
60
  function sanitizeOutput(text) {
59
61
  if (!text || typeof text !== 'string') return text;
60
62
 
61
- let sanitized = text;
63
+ let sanitized = decodeLiteralUnicodeEscapes(text);
62
64
  sanitized = stripTurnMarkers(sanitized);
63
65
  sanitized = removeBracketContent(sanitized);
64
66
  sanitized = formatForWhatsApp(sanitized);
package/lib/index.d.ts CHANGED
@@ -468,7 +468,7 @@ declare module '@peopl-health/nexus' {
468
468
  lastInboundAt?: string | null;
469
469
  lastOutboundAt?: string | null;
470
470
  lastOutreach?: string | null;
471
- checkIn?: { type: string; reminderId?: string | null; dueAt?: string | null; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null; otherPlans?: number | null } | null;
471
+ checkIn?: { type: string; reminderId?: string | null; planId?: string | null; dueAt?: string | null; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null; otherPlans?: number | null } | null;
472
472
  recentCheckIns?: string[];
473
473
  exchange?: { patient: { at: string; text: string } | null; own: { at: string; text: string } | null; ownMessagesToday: number; sessionOpen?: boolean } | null;
474
474
  asOf?: string | null;
@@ -565,7 +565,7 @@ declare module '@peopl-health/nexus' {
565
565
  ultimaAplicacion: { fecha: string; ciclo?: number; sesion?: number; total?: number } | null;
566
566
  esquema: Array<{ farmaco: string; via?: string; tiempo?: string }>;
567
567
  inicioEsquema: { fecha: string; anteriorAlRegistro: boolean } | null;
568
- proximaSesion: { fecha: string; tipo: string; confirmada?: boolean } | null;
568
+ proximaSesion: { fecha: string; tipo: string; confirmada?: boolean; hora?: string | null } | null;
569
569
  esquemaPrevio: { farmacos: string[]; hasta: string } | null;
570
570
  [key: string]: any;
571
571
  }
@@ -44,21 +44,25 @@ const groupConfigured = () => Boolean(runtimeConfig.get('WHAPI_TOKEN') && runtim
44
44
 
45
45
  const teamChannelConfigured = () => groupConfigured() || teamPhones().length > 0;
46
46
 
47
- async function sendToGroup(body) {
47
+ async function postToGroup(body, quoted) {
48
+ const res = await axios({
49
+ url: WHAPI_MESSAGES_URL,
50
+ method: 'POST',
51
+ data: { to: runtimeConfig.get('ESCALATION_TEAM_GROUP_ID'), body, ...(quoted ? { quoted } : {}) },
52
+ timeout: REQUEST_TIMEOUT_MS,
53
+ headers: { authorization: `Bearer ${runtimeConfig.get('WHAPI_TOKEN')}` },
54
+ validateStatus: () => true,
55
+ });
56
+ if (res.status >= 200 && res.status < 300) return { delivered: true, error: null, messageId: res.data?.message?.id || null };
57
+ return { delivered: false, error: `whapi responded ${res.status}` };
58
+ }
59
+
60
+ async function sendToGroup(body, quoted = null) {
48
61
  if (!groupConfigured()) return { delivered: false, error: 'WHAPI_TOKEN or ESCALATION_TEAM_GROUP_ID is not configured' };
49
- const token = runtimeConfig.get('WHAPI_TOKEN');
50
- const group = runtimeConfig.get('ESCALATION_TEAM_GROUP_ID');
51
62
  try {
52
- const res = await axios({
53
- url: WHAPI_MESSAGES_URL,
54
- method: 'POST',
55
- data: { to: group, body },
56
- timeout: REQUEST_TIMEOUT_MS,
57
- headers: { authorization: `Bearer ${token}` },
58
- validateStatus: () => true,
59
- });
60
- if (res.status >= 200 && res.status < 300) return { delivered: true, error: null };
61
- return { delivered: false, error: `whapi responded ${res.status}` };
63
+ const sent = await postToGroup(body, quoted);
64
+ // A quoted message Whapi no longer knows must not cost the alert: it goes out unthreaded.
65
+ return sent.delivered || !quoted ? sent : await postToGroup(body, null);
62
66
  } catch (error) {
63
67
  return { delivered: false, error: redacted(error) };
64
68
  }
@@ -66,9 +70,9 @@ async function sendToGroup(body) {
66
70
 
67
71
  // Alerts the team group and every on-call phone. One failed recipient never stops the others,
68
72
  // and nothing throws: the caller records what reached whom.
69
- async function sendTeamAlert({ message, operator, notice = false }) {
73
+ async function sendTeamAlert({ message, operator, notice = false, quoted = null }) {
70
74
  const templateKey = notice ? NOTICE_TEMPLATE_KEY : ALERT_TEMPLATE_KEY;
71
- const group = await sendToGroup(message.body);
75
+ const group = await sendToGroup(message.body, quoted);
72
76
  const phones = [];
73
77
  for (const code of teamPhones()) {
74
78
  try {
@@ -2,7 +2,7 @@ const { inlineOf } = require('../utils/coercionUtils');
2
2
  const { logger } = require('../utils/logger');
3
3
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
4
4
  const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
5
- const { conversationLink } = require('../clinical/services/clinicalAirtableService');
5
+ const { conversationLink, readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
6
6
  const { escalationGravePendingShadow, escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
7
7
 
8
8
  const { getPatientInformation, logPatientChange } = require('./patientService');
@@ -48,8 +48,15 @@ function untakenClockOf(review, policy) {
48
48
  URGENCY_RANK[appliedLevelOf(alarm)] > (URGENCY_RANK[top] || 0) ? appliedLevelOf(alarm) : top
49
49
  ), null);
50
50
  if (!level) return null;
51
- const since = new Date(alarms.find((alarm) => appliedLevelOf(alarm) === level).raisedAt);
52
- return { level, since, symptom: oneLine(alarms.findLast((alarm) => appliedLevelOf(alarm) === level).symptom), stages: untakenStagesOf(level, since, policy) };
51
+ const atLevel = alarms.filter((alarm) => appliedLevelOf(alarm) === level);
52
+ const since = new Date(atLevel[0].raisedAt);
53
+ return {
54
+ level,
55
+ since,
56
+ symptom: oneLine(atLevel.at(-1).symptom),
57
+ emergencyRecordId: atLevel.find((alarm) => alarm.emergencyRecordId)?.emergencyRecordId ?? null,
58
+ stages: untakenStagesOf(level, since, policy),
59
+ };
53
60
  }
54
61
 
55
62
  const sameStage = (clock, stage) => ({ level: clock.level, stage: stage.stage, since: clock.since });
@@ -141,8 +148,10 @@ async function alertIfUntaken(review, clock, stage, now) {
141
148
  return false;
142
149
  }
143
150
  const message = await untakenMessage(review, clock, stage);
151
+ // Replies to the group message Airtable posted for this alarm, so the case reads as one thread.
152
+ const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
144
153
  if (!await claimStage(review, clock, stage, now)) return false;
145
- const result = await sendTeamAlert({ message, operator: OPERATOR });
154
+ const result = await sendTeamAlert({ message, operator: OPERATOR, quoted });
146
155
  const phonesDelivered = result.phones.filter((phone) => phone.delivered).length;
147
156
  await getEscalationReview().updateOne(
148
157
  { _id: review._id, untakenAlerts: { $elemMatch: sameStage(clock, stage) } },
@@ -155,7 +164,7 @@ async function alertIfUntaken(review, clock, stage, now) {
155
164
  BOOKKEEPING,
156
165
  );
157
166
  await audit(review, {
158
- action: 'untaken_team_alerted', urgencyLevel: clock.level, stage: stage.stage,
167
+ action: 'untaken_team_alerted', urgencyLevel: clock.level, stage: stage.stage, threaded: Boolean(quoted),
159
168
  delivered: result.delivered, groupDelivered: result.group.delivered, phonesDelivered, phones: result.phones.length,
160
169
  });
161
170
  return true;
@@ -57,6 +57,10 @@ const mexicoDay = (value) => {
57
57
  // whole days from one YYYY-MM-DD day to another
58
58
  const daysBetween = (from, to) => Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 86400000);
59
59
 
60
+ const addDays = (day, days) => new Date(Date.parse(`${day}T00:00:00Z`) + days * 86400000).toISOString().slice(0, 10);
61
+
62
+ const formatDmy = (day) => `${day.slice(8, 10)}/${day.slice(5, 7)}/${day.slice(0, 4)}`;
63
+
60
64
  const mexicoIsoWeek = (value) => {
61
65
  if (value === null || value === undefined || value === '') return null;
62
66
  const at = moment.tz(value instanceof Date ? value.toISOString() : value, moment.ISO_8601, MEXICO_TZ);
@@ -101,6 +105,7 @@ const addWorkingMinutes = (start, minutes, { timeZone, days, startHour, endHour
101
105
  };
102
106
 
103
107
  module.exports = {
108
+ addDays,
104
109
  addWorkingMinutes,
105
110
  getCurrentMexicoDateTime,
106
111
  getMexicoDayLabels,
@@ -110,6 +115,7 @@ module.exports = {
110
115
  ageInYears,
111
116
  isoDay,
112
117
  daysBetween,
118
+ formatDmy,
113
119
  mexicoDay,
114
120
  mexicoClock,
115
121
  mexicoIsoWeek,
@@ -9,6 +9,25 @@ function jsonStringifyWithUnicodeEscapes(obj) {
9
9
  });
10
10
  }
11
11
 
12
+ const LITERAL_ESCAPE_RUN = /(?<!\\)(?:\\u[0-9a-fA-F]{4})+/g;
13
+ const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/;
14
+
15
+ // Models sometimes double-escape non-ASCII inside tool arguments, leaving a literal "\u00e9" after JSON.parse.
16
+ function decodeLiteralUnicodeEscapes(value) {
17
+ if (typeof value !== 'string' || !value.includes('\\u')) return value;
18
+ return value.replace(LITERAL_ESCAPE_RUN, (run) => {
19
+ const decoded = String.fromCharCode(...run.match(/[0-9a-fA-F]{4}/g).map((hex) => parseInt(hex, 16)));
20
+ return LONE_SURROGATE.test(decoded) ? run : decoded;
21
+ });
22
+ }
23
+
24
+ function normalizeModelStrings(value) {
25
+ if (typeof value === 'string') return decodeLiteralUnicodeEscapes(value);
26
+ if (Array.isArray(value)) return value.map(normalizeModelStrings);
27
+ if (isPlainObject(value)) return Object.fromEntries(Object.entries(value).map(([key, val]) => [key, normalizeModelStrings(val)]));
28
+ return value;
29
+ }
30
+
12
31
  function isPlainObject(value) {
13
32
  if (value === null || typeof value !== 'object') return false;
14
33
  const proto = Object.getPrototypeOf(value);
@@ -73,6 +92,8 @@ function stableStringify(value) {
73
92
 
74
93
  module.exports = {
75
94
  jsonStringifyWithUnicodeEscapes,
95
+ decodeLiteralUnicodeEscapes,
96
+ normalizeModelStrings,
76
97
  stableStringify,
77
98
  safeParse,
78
99
  safeParseArray,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.0-dev.15993",
3
+ "version": "6.0.0-dev.16255",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",