@peopl-health/nexus 5.77.0-dev.15992 → 5.77.0-dev.16338

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.
Files changed (31) hide show
  1. package/lib/clinical/AssistantProcessor.js +1 -0
  2. package/lib/clinical/flags/clinicalContextFlags.js +5 -0
  3. package/lib/clinical/flags/flagSnapshot.js +4 -1
  4. package/lib/clinical/helpers/chemoContextHelper.js +2 -1
  5. package/lib/clinical/helpers/triageResultMessageHelper.js +30 -0
  6. package/lib/clinical/memory/DefaultMemoryManager.js +4 -1
  7. package/lib/clinical/models/triageRecommendationEventModel.js +1 -0
  8. package/lib/clinical/providers/BaseLLMProvider.js +28 -14
  9. package/lib/clinical/providers/OpenAIResponsesProviderTools.js +6 -1
  10. package/lib/clinical/services/checkInDueService.js +2 -0
  11. package/lib/clinical/services/outreachCarrierService.js +2 -1
  12. package/lib/clinical/services/outreachSweepService.js +1 -0
  13. package/lib/clinical/services/radiotherapyContextService.js +40 -0
  14. package/lib/clinical/services/radiotherapyPhaseService.js +272 -0
  15. package/lib/clinical/services/triageRecommendationService.js +13 -0
  16. package/lib/clinical/tools/reportMedicalEscalationTool.js +9 -3
  17. package/lib/clinical/tools/schedulePatientReminderTool.js +4 -0
  18. package/lib/clinical/tools/submitOutreachDecisionTool.js +3 -0
  19. package/lib/controllers/messageController.js +4 -0
  20. package/lib/core/NexusMessaging.js +4 -0
  21. package/lib/eval/EvalProvider.js +1 -1
  22. package/lib/helpers/patientMessageHelper.js +3 -1
  23. package/lib/index.d.ts +10 -3
  24. package/lib/index.js +2 -0
  25. package/lib/models/airtableArchiveModel.js +0 -11
  26. package/lib/models/contactGateDecisionModel.js +26 -0
  27. package/lib/services/airtableArchiveService.js +1 -13
  28. package/lib/services/contactGateService.js +115 -0
  29. package/lib/utils/dateUtils.js +6 -0
  30. package/lib/utils/jsonUtils.js +21 -0
  31. package/package.json +1 -1
@@ -108,6 +108,7 @@ class AssistantProcessor {
108
108
  if (ctx) {
109
109
  ctx.outreachReminderType = runOptions.outreachCarrier?.reminderType || null;
110
110
  ctx.outreachReminderPrefix = runOptions.outreachCarrier?.reminderPrefix || null;
111
+ ctx.outreachAllowsFollowUp = runOptions.outreachAllowsFollowUp !== false;
111
112
  ctx.checkInOtherPlans = runOptions.outreachBrief?.checkIn?.otherPlans ?? null;
112
113
  }
113
114
  if (runOptions.turnKind || message) ctx?.setTurnContext?.(turnContext);
@@ -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;
@@ -163,14 +164,15 @@ class BaseLLMProvider {
163
164
  const devContent = this._buildInstructions({ resolvedPrompt, toolSchemas, prePromptResult });
164
165
  const catalogBlock = this._buildSkillCatalogMessage(skillCatalog)[0]?.content || '';
165
166
  const ruleBlock = this._buildContingencyRuleMessage({ toolIds: instructionToolIds, promptVariables })[0]?.content || '';
167
+ const allowFollowUp = assistant?.toolRuntimeContext?.outreachAllowsFollowUp !== false;
166
168
  const auditedPrompt = [
167
169
  devContent,
168
170
  catalogBlock,
169
171
  additionalInstructions ? this._operatorInstructionTurn(additionalInstructions, modelConfig).content : '',
170
- isOutreach ? (this._buildOutreachBriefMessage({ outreachBrief, toolIds: effectiveToolIds })[0]?.content || '') : '',
172
+ isOutreach ? (this._buildOutreachBriefMessage({ outreachBrief, toolIds: effectiveToolIds, allowFollowUp })[0]?.content || '') : '',
171
173
  ruleBlock,
172
174
  ].filter(Boolean).join('\n\n');
173
- const input = this._buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig, interpolatedVariables, skillCatalog, toolIds: instructionToolIds, outreachBrief: isOutreach ? outreachBrief : null });
175
+ const input = this._buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig, interpolatedVariables, skillCatalog, toolIds: instructionToolIds, outreachBrief: isOutreach ? outreachBrief : null, allowFollowUp });
174
176
 
175
177
  if (trace?.setSignals && isPlainObject(prePromptResult?.signals)) {
176
178
  trace.setSignals({ [CONSUMER_SIGNALS_KEY]: prePromptResult.signals });
@@ -305,7 +307,7 @@ class BaseLLMProvider {
305
307
  return { role: 'developer', content: `[DIRECTIVA DEL OPERADOR (prioritaria) para tu próxima respuesta al paciente]: ${additionalInstructions}` };
306
308
  }
307
309
 
308
- _buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig = null, interpolatedVariables = [], skillCatalog = [], toolIds = [], outreachBrief = null }) {
310
+ _buildInput({ context, prePromptResult, additionalInstructions, promptVariables, modelConfig = null, interpolatedVariables = [], skillCatalog = [], toolIds = [], outreachBrief = null, allowFollowUp = true }) {
309
311
  let messages = this._convertItemsToApiFormat(context || []);
310
312
  if (Array.isArray(prePromptResult?.additionalMessages) && prePromptResult.additionalMessages.length > 0) {
311
313
  messages = [...messages, ...this._convertItemsToApiFormat(prePromptResult.additionalMessages)];
@@ -321,10 +323,10 @@ class BaseLLMProvider {
321
323
  ...this._buildFollowUpPolicyMessage(toolIds),
322
324
  ...this._buildFollowUpMessage(promptVariables),
323
325
  ...this._buildFollowUpCheckMessage(toolIds),
324
- ...this._buildContingencyCheckMessage(promptVariables, toolIds),
326
+ ...this._buildContingencyCheckMessage(promptVariables, toolIds, outreachBrief),
325
327
  ...this._buildClockMessage(promptVariables, interpolatedVariables),
326
328
  ...messages,
327
- ...this._buildOutreachBriefMessage({ outreachBrief, toolIds }),
329
+ ...this._buildOutreachBriefMessage({ outreachBrief, toolIds, allowFollowUp }),
328
330
  ...this._buildContingencyRuleMessage({ toolIds, promptVariables }),
329
331
  ]);
330
332
  }
@@ -346,7 +348,7 @@ class BaseLLMProvider {
346
348
 
347
349
  // Rides as a turn-scoped developer block, never as a stored message: a proactive brief is true for
348
350
  // this morning only, and anything persisted into history would still read as a standing rule weeks later.
349
- _buildOutreachBriefMessage({ outreachBrief = null, toolIds = [] }) {
351
+ _buildOutreachBriefMessage({ outreachBrief = null, toolIds = [], allowFollowUp = true }) {
350
352
  if (!outreachBrief || typeof outreachBrief !== 'object') return [];
351
353
  if (!(toolIds || []).includes(OUTREACH_DECISION_TOOL)) return [];
352
354
 
@@ -380,8 +382,13 @@ class BaseLLMProvider {
380
382
  if (since.length) parts.push('', '## Qué ha pasado desde entonces', ...since);
381
383
  parts.push(
382
384
  '',
383
- `Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Decide según su conversación y sus planes activos: escribir ahora, programar cuándo volver a buscarla, o sostener.`,
384
- 'Si una contingencia activa ya cubre la preocupación, no la cruces con otro seguimiento. Si programas, primero usa schedulePatientReminder con reminder_type seguimiento y la misma utility_basis concreta; luego registra hold con el mismo next_check_at.',
385
+ ...(allowFollowUp ? [
386
+ `Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Decide según su conversación y sus planes activos: escribir ahora, programar cuándo volver a buscarla, o sostener.`,
387
+ 'Si una contingencia activa ya cubre la preocupación, no la cruces con otro seguimiento. Si programas, primero usa schedulePatientReminder con reminder_type seguimiento y la misma utility_basis concreta; luego registra hold con el mismo next_check_at.',
388
+ ] : [
389
+ `Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Decide según su conversación y sus planes activos: escribir ahora o sostener.`,
390
+ 'En este turno no programes seguimientos ni recordatorios, aunque otras reglas lo pidan: si te responde, la conversación decide lo que sigue. Si sostienes, deja next_check_at en null.',
391
+ ]),
385
392
  '',
386
393
  'Si escribes, que sea para ELLA: lo que te contó, lo que quedó abierto, lo que quieres saber ahora.',
387
394
  'Tu texto llega dentro de una plantilla que ya empieza con «Hola {su nombre},»: no saludes ni escribas su nombre, entra directo a lo que quieres decirle, breve (menos de 500 caracteres) y con un emoji como máximo. Es un contacto sobre su cuidado: no le sumes invitaciones a charlas, sesiones ni actividades.',
@@ -494,12 +501,16 @@ class BaseLLMProvider {
494
501
  // Rides behind the history like the follow-up check: the nets block above lists the nets, the decision lives here,
495
502
  // because an unresolved net later asks the patient a question they had already answered.
496
503
  // Only answers given after the net was armed count: an escalation net waits for how the reported symptom evolved.
497
- _buildContingencyCheckMessage(promptVariables, toolIds = []) {
504
+ // 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.
505
+ _buildContingencyCheckMessage(promptVariables, toolIds = [], outreachBrief = null) {
498
506
  if (!(toolIds || []).includes('setContingencyPlan')) return [];
499
507
  const active = Array.isArray(promptVariables?.active_contingencies) ? promptVariables.active_contingencies : [];
500
508
  if (!active.length) return [];
509
+ const dueNet = outreachBrief?.checkIn?.planId || null;
501
510
  const waiting = active.map(({ carePlan: plan = {} } = {}) => {
502
- const fired = plan.status === 'fired_reminder' ? ' Su check-in ya se envió.' : '';
511
+ let fired = '';
512
+ if (dueNet && plan.planId === dueNet) fired = ' Su check-in es el de este turno: todavía no le ha llegado.';
513
+ else if (plan.status === 'fired_reminder') fired = ' Su check-in ya se envió.';
503
514
  return `- ${plan.planId} (armada ${localFireTime(plan.createdAt)}) espera: ${sanitizeInlineText(plan.awaitingCharacterization)}.${fired}`;
504
515
  });
505
516
  return [{
@@ -621,6 +632,7 @@ class BaseLLMProvider {
621
632
  ...config,
622
633
  threadId: conversationId,
623
634
  assistantId,
635
+ compactOlderTriage: true,
624
636
  }
625
637
  });
626
638
 
@@ -633,6 +645,7 @@ class BaseLLMProvider {
633
645
 
634
646
  logger.info('[executeRun] Context built', { conversationId, messageCount: context?.length || 0 });
635
647
 
648
+ const radiotherapyBlock = radiotherapyBlockFor(thread.code, Date.now());
636
649
  const override = config.clinicalData;
637
650
  const hasOverride = override && typeof override === 'object' && Object.keys(override).length > 0;
638
651
  const clinicalData = hasOverride ? override : await this.conversationManager.getClinicalData(thread.code);
@@ -656,8 +669,9 @@ class BaseLLMProvider {
656
669
  patientId: thread.code,
657
670
  legacyBlock: promptVariables.clinical_context,
658
671
  });
659
- promptVariables.clinical_context = withHospitalization(block, thread?.hospitalizedAt);
660
- assistant?.toolRuntimeContext?.trace?.setSignals?.({ contextSource: source });
672
+ const rtBlock = await radiotherapyBlock;
673
+ promptVariables.clinical_context = withRadiotherapyBlock(withHospitalization(block, thread?.hospitalizedAt), rtBlock);
674
+ assistant?.toolRuntimeContext?.trace?.setSignals?.({ contextSource: source, rtBlockPresent: Boolean(rtBlock) });
661
675
 
662
676
  const result = await this.runConversation({
663
677
  threadId: conversationId,
@@ -859,7 +873,7 @@ class BaseLLMProvider {
859
873
  _bridgeFrom(calls) {
860
874
  const pick = (name, field) => {
861
875
  const value = calls.find(call => call.name === name)?.input?.[field];
862
- return typeof value === 'string' && value.trim() ? value : null;
876
+ return typeof value === 'string' && value.trim() ? decodeLiteralUnicodeEscapes(value) : null;
863
877
  };
864
878
  const extraction = calls.find(call => call.name === EXTRACTION_TOOL)?.input;
865
879
  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,
@@ -3,6 +3,7 @@ const { escapeRegExp } = require('../../utils/textMatchUtils');
3
3
 
4
4
  const MAX_CARRIER_TEXT_LENGTH = 600;
5
5
  const MAX_HYDRATED_BODY_LENGTH = 1024;
6
+ const GRAPHEME_SEGMENTER = new Intl.Segmenter('es', { granularity: 'grapheme' });
6
7
  const FOLLOW_UP_TYPES = new Set(['seguimiento']);
7
8
  const CONTINGENCY_TYPES = new Set(['contingencia']);
8
9
  const REMINDER_TYPES = new Set(['cita', 'examen', 'medicamento', 'otros']);
@@ -50,7 +51,7 @@ function validateAgentText(messageText, firstName) {
50
51
  throw new Error('OUTREACH_CARRIER_TEXT_REPEATS_NAME');
51
52
  }
52
53
 
53
- const emojiCount = [...text.matchAll(/\p{Extended_Pictographic}/gu)].length;
54
+ const emojiCount = [...GRAPHEME_SEGMENTER.segment(text)].filter(({ segment }) => /\p{Extended_Pictographic}/u.test(segment)).length;
54
55
  if (emojiCount > 1) throw new Error('OUTREACH_CARRIER_TEXT_TOO_MANY_EMOJI');
55
56
  return { text, name };
56
57
  }
@@ -583,6 +583,7 @@ async function runOutreachSweep({
583
583
  dryRun,
584
584
  reminderType: 'seguimiento',
585
585
  reminderPrefix: mode === 'monday_triage_recovery' ? 'recovery' : null,
586
+ allowFollowUp: mode === 'monday_triage_recovery',
586
587
  triggeredBy: `seguimiento:${candidate.recordId}`,
587
588
  });
588
589
  counts.run++;
@@ -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
  });
@@ -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 `stat` and the fever rule, no warning signs';
160
+ const FEVER_SIGNS_TIMER = 'Outside `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);
@@ -59,6 +59,7 @@ const MAX_PAUSE_DAYS = 30;
59
59
  const ROUTINE_OUTREACH_START_HOUR = 11;
60
60
  const ROUTINE_OUTREACH_END_HOUR = 21;
61
61
  const PAUSED_ERROR = 'thread_paused — do not schedule a seguimiento in this turn.';
62
+ const NO_FOLLOW_UP_ERROR = 'follow_up_not_allowed — this proactive contact cannot schedule a reminder: if she replies, the conversation decides what comes next. Close with write, or hold with next_check_at null.';
62
63
 
63
64
  const ISO_DATETIME = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,6})?)?$/;
64
65
  const FIRE_AT_FORMATS = ['YYYY-MM-DDTHH:mm:ss', 'YYYY-MM-DDTHH:mm', 'YYYY-MM-DD HH:mm:ss', 'YYYY-MM-DD HH:mm'];
@@ -88,6 +89,9 @@ async function handler(args = {}, context = {}) {
88
89
  const requestedAction = (args?.reminder_action_type || '').toLowerCase();
89
90
  if (requestedAction === 'cancel') return await cancelSeguimiento(args, runtime);
90
91
  if (requestedAction === 'pause_checkins') return await pauseCheckIns(args, runtime);
92
+ if (runtime.outreachAllowsFollowUp === false) {
93
+ return JSON.stringify({ success: false, error: NO_FOLLOW_UP_ERROR, data: {} });
94
+ }
91
95
 
92
96
  const reminderDate = (args?.reminder_date || '').trim();
93
97
  const description = sanitizeVariable(args?.reminder_description || '');
@@ -87,6 +87,9 @@ async function handler(args = {}, context = {}) {
87
87
  }
88
88
 
89
89
  const { value: nextCheckAt, rejected } = normalizeNextCheck(args?.next_check_at);
90
+ if (rawDecision === 'hold' && nextCheckAt && runtime.outreachAllowsFollowUp === false) {
91
+ return JSON.stringify({ success: false, error: 'next_check_at must be null: this proactive contact cannot plan a later check. Write now, or hold with next_check_at null.', data: {} });
92
+ }
90
93
  if (holdReason === 'contingency_already_armed' && !nextCheckAt && runtime.checkInOtherPlans === 0) {
91
94
  return JSON.stringify({ success: false, error: 'contingency_already_armed needs another active net or pending seguimiento, and this check-in has none: write now, or schedule a seguimiento and hold with rescheduled_for_cadence.', data: {} });
92
95
  }
@@ -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) {
@@ -26,6 +26,7 @@ const { isStaffSend } = require('../helpers/staffSendHelper');
26
26
 
27
27
  const { createMessagingProvider } = require('../adapters/registry');
28
28
  const { ensureThreadExists } = require('../services/threadService');
29
+ const { observeSend } = require('../services/contactGateService');
29
30
 
30
31
  const { hasPreprocessingHandler, runPreprocessingHandler } = require('../services/preprocessingService');
31
32
  const { getMessages, updateMessage } = require('../services/messageService');
@@ -243,6 +244,7 @@ class NexusMessaging {
243
244
  }
244
245
 
245
246
  if (messageData.code) ensureThreadExists(messageData.code);
247
+ if (result?.success === true) observeSend(messageData);
246
248
 
247
249
  return result;
248
250
  }
@@ -1038,6 +1040,7 @@ class NexusMessaging {
1038
1040
  reminderType = 'seguimiento',
1039
1041
  reminderPrefix = null,
1040
1042
  replyToContact = false,
1043
+ allowFollowUp = true,
1041
1044
  dryRun = false,
1042
1045
  } = {}) {
1043
1046
  const outreachStartedAt = new Date().toISOString();
@@ -1069,6 +1072,7 @@ class NexusMessaging {
1069
1072
  outreachBrief: brief,
1070
1073
  preemptiveWindowRoute: true,
1071
1074
  outreachCarrier: { reminderType, reminderPrefix, firstName, replyToContact },
1075
+ outreachAllowsFollowUp: allowFollowUp,
1072
1076
  outreachStartedAt,
1073
1077
  // Stamped on the outbound so a delivered message joins back to the row that surfaced her.
1074
1078
  triggeredBy: triggeredBy || null,
@@ -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
@@ -274,7 +274,7 @@ declare module '@peopl-health/nexus' {
274
274
  getWorkflowRunner(): WorkflowRunner;
275
275
  processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string; beforeRun?: () => Promise<string | null | undefined> | string | null | undefined; dedupeWithinMs?: number }): 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
- processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean; replyToContact?: boolean }): Promise<OutreachDecision>;
277
+ processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean; replyToContact?: boolean; allowFollowUp?: boolean }): Promise<OutreachDecision>;
278
278
  processCheckInDue(code: string, options: { reminderId: string; type: 'contingencia' | 'seguimiento'; question?: string; firstName?: string | null }): Promise<CheckInDueResult>;
279
279
  processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
280
280
  isConnected(): boolean;
@@ -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
  }
@@ -942,6 +942,13 @@ declare module '@peopl-health/nexus' {
942
942
  provider: (context: { now: Date }) => SupportDashboardSnapshot | Promise<SupportDashboardSnapshot>
943
943
  ): void;
944
944
 
945
+ export type ContactCategory = 'clinical' | 'triage' | 'sessions' | 'followup' | 'invitations' | 'unclassified';
946
+
947
+ export function registerContactCategories(categories: {
948
+ contentSids?: Record<string, ContactCategory>;
949
+ triggeredBy?: Record<string, ContactCategory>;
950
+ }): void;
951
+
945
952
  export const supportCandidateService: {
946
953
  updateSupportOperationalReview(request: {
947
954
  patientId: string;
package/lib/index.js CHANGED
@@ -54,6 +54,7 @@ const { registerTool, hasTool, getToolSchemas, clearRegistry } = require('./serv
54
54
  const { MapCache } = require('./utils/MapCache');
55
55
  const supportCandidateService = require('./clinical/services/supportCandidateService');
56
56
  const { registerDashboardProvider } = require('./services/dashboard-provider-registry');
57
+ const { registerContactCategories } = require('./services/contactGateService');
57
58
  const supportActionService = require('./clinical/services/supportActionService');
58
59
  const supportLightService = require('./clinical/services/supportLightService');
59
60
  const supportInvitability = require('./clinical/services/supportInvitability');
@@ -395,6 +396,7 @@ module.exports = {
395
396
  MapCache,
396
397
  supportCandidateService,
397
398
  registerDashboardProvider,
399
+ registerContactCategories,
398
400
  supportActionService,
399
401
  supportLightService,
400
402
  supportInvitability,
@@ -55,16 +55,6 @@ const tableCountsSchema = new mongoose.Schema({
55
55
  failed: { type: Number, default: 0 },
56
56
  }, { _id: false });
57
57
 
58
- // One eligible group as the plan saw it, so a later delete can name exactly the groups that were reviewed.
59
- const plannedGroupSchema = new mongoose.Schema({
60
- groupId: { type: String, required: true },
61
- // Every patient of the group's records: a shared questionnaire can join two patients.
62
- patientRecordIds: { type: [String], default: [] },
63
- // None of them has a patient-linked questionnaire or triage since the cutoff.
64
- inactive: { type: Boolean, required: true },
65
- records: { type: Map, of: Number, default: {} },
66
- }, { _id: false });
67
-
68
58
  const airtableArchiveRunSchema = new mongoose.Schema({
69
59
  runId: { type: String, required: true },
70
60
  baseId: { type: String, required: true },
@@ -79,7 +69,6 @@ const airtableArchiveRunSchema = new mongoose.Schema({
79
69
  kept: { type: Map, of: Number, default: {} },
80
70
  },
81
71
  tables: { type: Map, of: tableCountsSchema, default: {} },
82
- eligibleGroups: { type: [plannedGroupSchema], default: [] },
83
72
  errorCode: { type: String, default: null },
84
73
  }, { collection: 'airtable_archive_runs', minimize: false, timestamps: true });
85
74
 
@@ -0,0 +1,26 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ const CONTACT_GATE_TTL_SECONDS = 90 * 24 * 60 * 60;
4
+
5
+ const contactGateDecisionSchema = new mongoose.Schema({
6
+ code: { type: String, required: true },
7
+ contactCode: { type: String, default: null },
8
+ kind: { type: String, enum: ['operator', 'reply', 'proactive'], required: true },
9
+ category: { type: String, default: null },
10
+ mode: { type: String, enum: ['shadow'], required: true },
11
+ wouldAllow: { type: Boolean, required: true },
12
+ reason: { type: String, default: null },
13
+ dayCount: { type: Number, default: 0 },
14
+ weekCount: { type: Number, default: 0 },
15
+ sendKind: { type: String, default: null },
16
+ triggeredBy: { type: String, default: null },
17
+ contentSid: { type: String, default: null },
18
+ createdAt: { type: Date, default: Date.now }
19
+ });
20
+
21
+ contactGateDecisionSchema.index({ code: 1, kind: 1, createdAt: -1 }, { name: 'contact_gate_code_kind_idx' });
22
+ contactGateDecisionSchema.index({ createdAt: 1 }, { name: 'contact_gate_ttl_idx', expireAfterSeconds: CONTACT_GATE_TTL_SECONDS });
23
+
24
+ const ContactGateDecision = mongoose.model('ContactGateDecision', contactGateDecisionSchema);
25
+
26
+ module.exports = { ContactGateDecision, CONTACT_GATE_TTL_SECONDS };
@@ -297,14 +297,6 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
297
297
  }
298
298
  }
299
299
 
300
- function plannedGroup(group, patientsWithRecent) {
301
- const patientRecordIds = [...new Set(group.records.map(({ patient }) => patient?.recordId).filter(Boolean))];
302
- const records = {};
303
- group.records.forEach(({ table }) => { records[table] = (records[table] || 0) + 1; });
304
- const isInactive = (patientId) => Object.values(patientsWithRecent).every((patients) => !patients.has(patientId));
305
- return { groupId: group.groupId, patientRecordIds, inactive: patientRecordIds.length > 0 && patientRecordIds.every(isInactive), records };
306
- }
307
-
308
300
  // Batches never split a group, so a changed record holds back its whole group.
309
301
  function groupBatches(groups) {
310
302
  const batches = [];
@@ -356,17 +348,13 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
356
348
  }
357
349
  }
358
350
 
359
- // Only a plan stores its groups: a copy run's list would include groups it held back, so slices are picked from plans.
360
- const eligibleGroups = mode === 'plan' ? plan.eligible.map((group) => plannedGroup(group, patientsWithRecent)) : [];
361
351
  const failed = Object.values(counts).reduce((sum, c) => sum + c.failed, 0);
362
352
  const summary = {
363
353
  runId, mode, cutoff, status: failed ? 'failed' : 'succeeded',
364
354
  components: { eligible: plan.eligible.length, kept: plan.keptByReason }, tables: counts,
365
355
  };
366
356
  const finished = await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, {
367
- $set: {
368
- status: summary.status, finishedAt: new Date(), components: summary.components, tables: counts, eligibleGroups, errorCode: failed ? 'records_failed' : null,
369
- },
357
+ $set: { status: summary.status, finishedAt: new Date(), components: summary.components, tables: counts, errorCode: failed ? 'records_failed' : null },
370
358
  });
371
359
  if (!finished?.matchedCount) throw archiveError('archive_lease_lost');
372
360
  logger.info('[airtableArchive] Run finished', summary);
@@ -0,0 +1,115 @@
1
+ const moment = require('moment-timezone');
2
+
3
+ const runtimeConfig = require('../config/runtimeConfig');
4
+ const { logger } = require('../utils/logger');
5
+
6
+ const { ContactGateDecision } = require('../models/contactGateDecisionModel');
7
+ const { isStaffSend } = require('../helpers/staffSendHelper');
8
+ const { getMessages } = require('./messageService');
9
+
10
+ const CATEGORIES = ['clinical', 'triage', 'sessions', 'followup', 'invitations', 'unclassified'];
11
+ const EXEMPT_CATEGORIES = ['clinical'];
12
+ const DAILY_CAP = 2;
13
+ const WEEKLY_CAP = 6;
14
+ const CONTACT_TIMEZONE = 'America/Mexico_City';
15
+ const CONTACT_HOURS = { start: 9, end: 21 };
16
+ const REPLY_WINDOW_MS = 30 * 60 * 1000;
17
+ const NEXUS_TRIGGER_CATEGORIES = {
18
+ paused_safety_net: 'clinical',
19
+ seguimiento: 'followup',
20
+ followup: 'followup',
21
+ send_reminder: 'followup'
22
+ };
23
+
24
+ const registered = { contentSids: {}, triggeredBy: {} };
25
+
26
+ function registerContactCategories({ contentSids = {}, triggeredBy = {} } = {}) {
27
+ const unknown = [...Object.values(contentSids), ...Object.values(triggeredBy)].find(value => !CATEGORIES.includes(value));
28
+ if (unknown !== undefined) throw new Error(`Unknown contact category: ${unknown}`);
29
+ Object.assign(registered.contentSids, contentSids);
30
+ Object.assign(registered.triggeredBy, triggeredBy);
31
+ }
32
+
33
+ function contactGateMode() {
34
+ return runtimeConfig.get('CONTACT_GATE_MODE') === 'shadow' ? 'shadow' : 'off';
35
+ }
36
+
37
+ function triggerSource(triggeredBy) {
38
+ const trigger = String(triggeredBy || '');
39
+ return trigger.startsWith('followup_') ? 'followup' : trigger.split(':')[0];
40
+ }
41
+
42
+ function categoryOf({ contentSid, triggeredBy }) {
43
+ const source = triggerSource(triggeredBy);
44
+ return registered.contentSids[contentSid] || registered.triggeredBy[source] || NEXUS_TRIGGER_CATEGORIES[source] || 'unclassified';
45
+ }
46
+
47
+ // A released or recovery send carries no trigger of its own; it inherits the one of the message it delivers.
48
+ async function triggerOf({ triggeredBy, parentMessageId }) {
49
+ if (triggeredBy || !parentMessageId) return triggeredBy || null;
50
+ const [parent] = await getMessages({ _id: parentMessageId }, { select: 'triggeredBy', limit: 1 });
51
+ return parent?.triggeredBy || null;
52
+ }
53
+
54
+ async function classify(messageData, now) {
55
+ if (isStaffSend(messageData.triggeredBy)) return { kind: 'operator', category: null };
56
+ const [inbound] = await getMessages(
57
+ {
58
+ numero: messageData.code,
59
+ contact_code: messageData.contactCode || null,
60
+ from_me: false,
61
+ createdAt: { $gte: new Date(now.getTime() - REPLY_WINDOW_MS) }
62
+ },
63
+ { select: '_id', limit: 1 }
64
+ );
65
+ return { kind: inbound ? 'reply' : 'proactive', category: categoryOf(messageData) };
66
+ }
67
+
68
+ const isCounted = ({ kind, category }) => kind === 'proactive' && !EXEMPT_CATEGORIES.includes(category);
69
+
70
+ async function priorCounts(code, now) {
71
+ const local = moment(now).tz(CONTACT_TIMEZONE);
72
+ const counted = { code, kind: 'proactive', category: { $nin: EXEMPT_CATEGORIES } };
73
+ const [dayCount, weekCount] = await Promise.all([
74
+ ContactGateDecision.countDocuments({ ...counted, createdAt: { $gte: local.clone().startOf('day').toDate() } }),
75
+ ContactGateDecision.countDocuments({ ...counted, createdAt: { $gte: local.clone().startOf('isoWeek').toDate() } })
76
+ ]);
77
+ return { dayCount, weekCount };
78
+ }
79
+
80
+ function verdict(classified, { dayCount, weekCount }, now) {
81
+ if (!isCounted(classified)) return { wouldAllow: true, reason: null };
82
+ const hour = moment(now).tz(CONTACT_TIMEZONE).hour();
83
+ if (hour < CONTACT_HOURS.start || hour >= CONTACT_HOURS.end) return { wouldAllow: false, reason: 'outside_hours' };
84
+ if (dayCount >= DAILY_CAP) return { wouldAllow: false, reason: 'daily_cap' };
85
+ if (weekCount >= WEEKLY_CAP) return { wouldAllow: false, reason: 'weekly_cap' };
86
+ return { wouldAllow: true, reason: null };
87
+ }
88
+
89
+ // Shadow mode only records what the gate would have decided about a send that already went out; it never blocks one.
90
+ async function observeSend(messageData, now = new Date()) {
91
+ const code = messageData?.code;
92
+ try {
93
+ if (contactGateMode() !== 'shadow' || !code) return null;
94
+ const triggeredBy = await triggerOf(messageData);
95
+ const classified = await classify({ ...messageData, triggeredBy }, now);
96
+ const counts = isCounted(classified) ? await priorCounts(code, now) : { dayCount: 0, weekCount: 0 };
97
+ return await ContactGateDecision.create({
98
+ code,
99
+ ...classified,
100
+ mode: 'shadow',
101
+ ...verdict(classified, counts, now),
102
+ ...counts,
103
+ contactCode: messageData.contactCode || null,
104
+ sendKind: messageData.kind || null,
105
+ triggeredBy,
106
+ contentSid: messageData.contentSid || null,
107
+ createdAt: now
108
+ });
109
+ } catch (error) {
110
+ logger.warn('[contactGate] Shadow decision was not recorded', { code, error: error.message });
111
+ return null;
112
+ }
113
+ }
114
+
115
+ module.exports = { registerContactCategories, observeSend };
@@ -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": "5.77.0-dev.15992",
3
+ "version": "5.77.0-dev.16338",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",