@peopl-health/nexus 6.6.0-dev.20938 → 6.6.0-dev.21349

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.
@@ -104,10 +104,10 @@ function regimenText(context) {
104
104
 
105
105
  function statusLine(last, active, days) {
106
106
  const cycle = [last.ciclo ? `ciclo ${last.ciclo}` : '', last.sesion ? `sesión ${last.sesion}${last.total ? `/${last.total}` : ''}` : ''].filter(Boolean).join(', ');
107
- const when = days === null ? `última aplicación registrada ${dmy(last.fecha)}` : `última aplicación ${dmy(last.fecha)} (hace ${days} días)`;
107
+ const when = days === null ? `última aplicación registrada ${weekdayDmy(last.fecha)}` : `última aplicación ${weekdayDmy(last.fecha)} (hace ${days} días)`;
108
108
  return active
109
109
  ? `Estado: en quimioterapia activa; ${when}${cycle ? `, ${cycle}` : ''}`
110
- : `Estado: sin aplicaciones registradas en la unidad desde ${dmy(last.fecha)} (hace ${days} días); confirma con el paciente si sigue en tratamiento`;
110
+ : `Estado: sin aplicaciones registradas en la unidad desde ${weekdayDmy(last.fecha)} (hace ${days} días); confirma con el paciente si sigue en tratamiento`;
111
111
  }
112
112
 
113
113
  function chemoLines(context, today) {
@@ -121,7 +121,7 @@ function chemoLines(context, today) {
121
121
  if (context.vigilancia.length) lines.push(`Vigilar por sus fármacos: ${context.vigilancia.join('; ')}`);
122
122
  if (active && days !== null && context.nadirDias && days <= context.nadirDias[1]) {
123
123
  const [from, to] = context.nadirDias;
124
- lines.push(`Mayor riesgo de defensas bajas: días ${from} a ${to} después de la aplicación (${dmy(addDays(last.fecha, from))} al ${dmy(addDays(last.fecha, to))}); hoy es el día ${days}. Fiebre de 38 °C o más es urgente cualquier día`);
124
+ lines.push(`Mayor riesgo de defensas bajas: días ${from} a ${to} después de la aplicación (${weekdayDmy(addDays(last.fecha, from))} al ${weekdayDmy(addDays(last.fecha, to))}); hoy es el día ${days}. Fiebre de 38 °C o más es urgente cualquier día`);
125
125
  }
126
126
  }
127
127
  if (context.enCasa.length) {
@@ -143,7 +143,7 @@ function chemoLines(context, today) {
143
143
  const care = texts(support.detalle);
144
144
  lines.push(`Próxima visita a la unidad sin quimioterapia: ${weekdayDmy(support.fecha)} (${[care.join(', '), confirmation(support)].filter(Boolean).join('; ')})`);
145
145
  }
146
- if (context.noAplicadas.length) lines.push(`Sesiones no aplicadas en los últimos 90 días: ${context.noAplicadas.map(dmy).join(', ')}`);
146
+ if (context.noAplicadas.length) lines.push(`Sesiones no aplicadas en los últimos 90 días: ${context.noAplicadas.map(weekdayDmy).join(', ')}`);
147
147
  if (text(context.reaccionInfusion?.texto)) lines.push(`Reacción durante la infusión registrada: ${text(context.reaccionInfusion.texto)} (${dmy(context.reaccionInfusion.fecha)})`);
148
148
  if (context.acceso) lines.push(`Acceso venoso: ${context.acceso}`);
149
149
  if (Number.isFinite(context.peso?.kg)) {
@@ -3,8 +3,7 @@ const { getCurrentMexicoDateTime, getMexicoDayLabels, getMexicoUpcomingDayLabels
3
3
  const ANCHOR_SPAN_DAYS = 7;
4
4
  const UPCOMING_SPAN_DAYS = 14;
5
5
 
6
- function buildDateAnchor() {
7
- const at = Date.now();
6
+ function buildDateAnchor(at = Date.now()) {
8
7
  const labels = getMexicoDayLabels({ days: ANCHOR_SPAN_DAYS, at });
9
8
  const week = labels.map((label, i) => (i === labels.length - 1 ? `${label} (hoy)` : label));
10
9
  const upcoming = getMexicoUpcomingDayLabels({ days: UPCOMING_SPAN_DAYS, at });
@@ -42,9 +42,18 @@ function gradeFor(todayGrades, catalog, term) {
42
42
  return key ? todayGrades.get(key) : null;
43
43
  }
44
44
 
45
+ const cardTerms = (element) => [...new Set([
46
+ ...element.targetedCtcaeTerms, ...element.symptoms.map((symptom) => symptom.ctcaeTerm),
47
+ ].filter(Boolean))];
48
+
49
+ function cardTodayGrade(element, { catalog, todayGrades }) {
50
+ const grades = cardTerms(element).map((term) => gradeFor(todayGrades, catalog, term)).filter((grade) => grade !== null);
51
+ return grades.length ? Math.max(...grades) : null;
52
+ }
53
+
45
54
  // Every term on the card needs today's grade and a current anchor: on a mixed card the question may be about the other term.
46
55
  function anchorsCover(element, { known, catalog, todayGrades }) {
47
- const terms = [...new Set([...element.targetedCtcaeTerms, ...element.symptoms.map((symptom) => symptom.ctcaeTerm)].filter(Boolean))];
56
+ const terms = cardTerms(element);
48
57
  if (!terms.length) return false;
49
58
  return terms.every((term) => {
50
59
  const todayGrade = gradeFor(todayGrades, catalog, term);
@@ -70,4 +79,4 @@ function dropKnownFunctionalAsks(elements, { known, catalog, todayGrades } = {},
70
79
  return dropped;
71
80
  }
72
81
 
73
- module.exports = { asksFunctionalImpact, dropKnownFunctionalAsks, todayGradesByTerm };
82
+ module.exports = { asksFunctionalImpact, cardTodayGrade, dropKnownFunctionalAsks, todayGradesByTerm };
@@ -1,6 +1,7 @@
1
1
  const { recommendationId } = require('../../fhir/helpers/recommendationIds');
2
+ const { cardTodayGrade } = require('./knownCharacterizationHelper');
2
3
 
3
- function buildLegacyRecommendations({ plan, gate = null }) {
4
+ function buildLegacyRecommendations({ plan, gate = null, grades = { todayGrades: new Map() } }) {
4
5
  const ranked = [...plan.elements].sort((a, b) => a.rank - b.rank);
5
6
  return ranked.map((element) => {
6
7
  const { patient } = element.recommendation;
@@ -27,6 +28,8 @@ function buildLegacyRecommendations({ plan, gate = null }) {
27
28
  urgent_under_24h: isUrgent,
28
29
  // Gate enum only; element routes carry the palliative vocabulary.
29
30
  escalation_route: isUrgent ? (gate?.escalationRoute ?? null) : null,
31
+ // The Airtable triage directive opens on the highest-grade card.
32
+ max_reported_grade: cardTodayGrade(element, grades),
30
33
  };
31
34
  });
32
35
  }
@@ -85,7 +88,7 @@ function buildLegacyStep2(plan) {
85
88
  }
86
89
 
87
90
  // The explode trigger REGEX_EXTRACTs `recommendations` end-anchored: it must stay the last key.
88
- function buildLegacyStep3({ plan, gate = null }) {
91
+ function buildLegacyStep3({ plan, gate = null, grades }) {
89
92
  return {
90
93
  step3_careplan: {
91
94
  careplan_takeaways: {
@@ -94,7 +97,7 @@ function buildLegacyStep3({ plan, gate = null }) {
94
97
  careplan_summary_patient_facing: plan.takeaways.summaryPatientFacing,
95
98
  careplan_summary_internal: plan.takeaways.summaryInternal,
96
99
  },
97
- recommendations: buildLegacyRecommendations({ plan, gate }),
100
+ recommendations: buildLegacyRecommendations({ plan, gate, grades }),
98
101
  },
99
102
  };
100
103
  }
@@ -364,7 +364,7 @@ async function recordClinicalIntake({ code, trace, messageRaw, source = 'self',
364
364
  return written;
365
365
  }
366
366
 
367
- async function recordReminder({ code, trace, actionType, reminderId, reminderDateUtc, reminderType, description: rawDescription, firesAfterSilenceMinutes = null, expiresAtUtc = null, concern = null, windowReasoning = null, isLive = null }) {
367
+ async function recordReminder({ code, trace, actionType, reminderId, reminderDateUtc, reminderType, description: rawDescription, firesAfterSilenceMinutes = null, expiresAtUtc = null, concern = null, windowReasoning = null, templateSid = null, templateVariables = null, isLive = null }) {
368
368
  const description = decodeUnicodeEscapes(rawDescription);
369
369
  const type = REMINDER_TYPE_TO_AIRTABLE[reminderType] || reminderType;
370
370
  if (actionType === 'update') {
@@ -416,6 +416,7 @@ async function recordReminder({ code, trace, actionType, reminderId, reminderDat
416
416
  // written once at arm time and never read back into the system, so it cannot feed drift.
417
417
  ...(concern ? { concern } : {}),
418
418
  ...(windowReasoning ? { window_reasoning: windowReasoning } : {}),
419
+ ...(templateSid && templateVariables ? { template_sid: templateSid, template_variables: JSON.stringify(templateVariables) } : {}),
419
420
  },
420
421
  {
421
422
  referenceTable: 'estado_general',
@@ -1,6 +1,7 @@
1
1
  const { getEscalationDraft } = require('../config/subAgentsConfig');
2
2
 
3
3
  const { composeDoctorBody, flagsByStatus } = require('../helpers/doctorReviewMessageHelper');
4
+ const { buildDateAnchor } = require('../helpers/dateAnchorHelper');
4
5
  const { readStructuredText } = require('../helpers/structuredTextHelper');
5
6
  const { createLLMProvider } = require('../providers/createLLMProvider');
6
7
  const { FORMULARY_VERSION, TREATMENT_FORMULARY, findDrug, formularyFor } = require('../protocols/treatmentFormulary');
@@ -9,6 +10,7 @@ const { getEscalationContext } = require('../../services/escalationContextServic
9
10
 
10
11
  const { inlineOf, normalizedKeyOf } = require('../../utils/coercionUtils');
11
12
  const { logger } = require('../../utils/logger');
13
+ const { getCurrentMexicoDateTime } = require('../../utils/dateUtils');
12
14
  const { arrayArg, safeParse } = require('../../utils/jsonUtils');
13
15
  const { withTiming } = require('../../utils/tracingDecorator');
14
16
 
@@ -84,7 +86,9 @@ function suggestCallOf(value) {
84
86
  return { value: value.value, reason: trimmed(value.reason) || null };
85
87
  }
86
88
 
87
- function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharacterization = null }) {
89
+ const localStampOf = (at) => (at ? getCurrentMexicoDateTime(at) : null);
90
+
91
+ function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharacterization = null, now = Date.now() }) {
88
92
  const conversation = Array.isArray(context?.conversation)
89
93
  ? context.conversation.slice(-CONVERSATION_TURNS)
90
94
  : context?.conversation ?? null;
@@ -95,8 +99,9 @@ function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharac
95
99
 
96
100
  return {
97
101
  protocolVersion: FORMULARY_VERSION,
102
+ currentDate: buildDateAnchor(now),
98
103
  protocol,
99
- alarms,
104
+ alarms: alarms.map((alarm) => ({ ...alarm, raisedAtLocal: localStampOf(alarm.raisedAt) })),
100
105
  agentCharacterization,
101
106
  patient: {
102
107
  clinicalContext: context?.agentContext ?? null,
@@ -109,6 +114,7 @@ function buildDraftInput({ context, callLogs, protocol, alarms = [], agentCharac
109
114
  outcome: log?.outcome ?? null,
110
115
  notes: trimmed(log?.notes) || null,
111
116
  calledAt: log?.calledAt ?? null,
117
+ calledAtLocal: localStampOf(log?.calledAt),
112
118
  })),
113
119
  sectionsUnavailable: context?.degradedSections ?? [],
114
120
  };
@@ -157,7 +163,7 @@ async function generateEscalationDraft({
157
163
  }
158
164
 
159
165
  const context = await getEscalationContext({ code, now });
160
- const input = buildDraftInput({ context, callLogs, protocol: MODEL_FORMULARY, alarms, agentCharacterization });
166
+ const input = buildDraftInput({ context, callLogs, protocol: MODEL_FORMULARY, alarms, agentCharacterization, now });
161
167
 
162
168
  // Past this point a generation run was issued. Whether the request actually left the process is
163
169
  // not knowable here — the provider resolves the preset and validates the schema before it calls
@@ -694,7 +694,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
694
694
  triageRecordId: payload.triageRecordId,
695
695
  step1: buildLegacyStep1(gate),
696
696
  step2: buildLegacyStep2(plan),
697
- step3: buildLegacyStep3({ plan, gate }),
697
+ step3: buildLegacyStep3({ plan, gate, grades: { catalog, todayGrades: boundary.todayGrades } }),
698
698
  };
699
699
  return finish({ status: 'success', reason: null }, mirrorPayload);
700
700
  } catch (err) {
@@ -13,6 +13,8 @@ const { URGENCY_RANK } = require('../../models/escalationReviewModel');
13
13
  const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
14
14
  const { logger } = require('../../utils/logger');
15
15
 
16
+ const ABSENT_ONLY_IF_DENIED = 'Escribe como ausente solo lo que el paciente negó cuando se le preguntó por eso en este episodio; lo que nadie preguntó va como «no preguntado» ("debilidad en piernas: no preguntado"), nunca como «sin debilidad» ni «descartado». Los equipos y los borradores leen tu texto como dato del paciente. ';
17
+
16
18
  const FEVER_RUBRIC_STAT = 'fiebre en la ventana de quimioterapia con una bandera roja confirmada (regla de fiebre),';
17
19
 
18
20
  const FEVER_RUBRIC_ASAP = 'fiebre ≥38.0 °C, o temperatura baja (menos de 36.0 °C) confirmada al volver a medir con malestar o escalofríos, o ≤35.0 °C confirmado, en la ventana de quimioterapia sin bandera roja (regla de fiebre),';
@@ -24,7 +26,7 @@ const FEVER_RULE = 'Fever within 6 weeks (42 days) of cytotoxic chemotherapy (or
24
26
 
25
27
  const definition = {
26
28
  'name': 'reportMedicalEscalation',
27
- '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 now, with no question that invites a downgrade: `asap` by default, `stat` if there is an acute deficit (new, sudden weakness of an arm, a leg or one side, numbness of the face or a whole side, a drooping face or new trouble speaking — even if they can still move it —; new loss of bladder or bowel control; new or worsening leg weakness with back or neck pain, known spine disease or bone metastases (or, with bone status unknown, a cancer that often spreads to the spine), or groin numbness, or sudden weakness of both legs → possible cord compression) or any instability; an acute deficit is must-go and asks nothing, except the one onset question when it is not yet known whether it came on suddenly. In `asap`, ask the short neuro checklist in the same message as ONE question on one line, not a numbered list (\'¿Sabes dónde estás y qué día es, puedes hablar bien, ves bien, sientes debilidad de un lado, has vomitado o convulsionado?\'), keeping the message ≤60 words — the one exception to asking about a single sign and to no lists.\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`, 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, or vomiting blood or black, tarry stool together with dizziness or near-fainting on standing (even without the skin signs of shock); fainting or loss of consciousness; INTENSE shortness of breath at rest (mild breathlessness at rest is not must-go, except with the checkpoint-inhibitor signs below); chest pain with CLEAR shortness of breath, cold sweat, or spreading to the arm or jaw; sudden confusion or a seizure; NEW, SUDDEN weakness of one arm, one leg or one side, numbness of the face or of a whole side (face, arm and leg), a drooping face or new trouble speaking, even if they can still move it (a known, long-standing limitation is not sudden; general weakness or tiredness, or not getting up from fatigue, is not must-go: `asap`, or `urgent` if it is gradual and they are eating, drinking and passing urine; if they cannot stand because they feel faint, check it against fainting and shock); possible cord compression — NEW or WORSENING weakness in the legs TOGETHER WITH back or neck pain, known spine disease or bone metastases (or, with bone status unknown, a cancer that often spreads to the spine: breast, prostate, lung, kidney, myeloma), or numbness in the groin or buttocks, even if it came on over hours or days; or SUDDEN weakness of both legs (it came on within hours), even without back pain; or new loss of bladder or bowel control on its own (not feeling or not holding urine or stool, or not being able to pass urine; urgency from diarrhea is not this) — tingling or numbness in hands and feet from neuropathy, or long-standing leg weakness without back pain, is not must-go, and new back pain with no neurologic sign is `asap`; on active or recent checkpoint-inhibitor immunotherapy, drooping eyelids, double vision, new trouble swallowing or leg weakness getting worse over days is at least `asap`, and must-go with shortness of breath at rest or when they cannot swallow; 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, or mottled, or grey or bluish lips, TOGETHER WITH at least one of: near-fainting on standing, new confusion or drowsiness, a racing heart at rest, or almost no urine (none in 12 hours or more); pallor, tiredness or weakness without those skin signs is not must-go (`asap`). 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, pallor or tiredness alone. When a sign is only partly described (swollen lips, hives or a strange throat with nothing else; cold or mottled skin with nothing else; weakness without knowing whether it is one side; leg weakness or numbness without knowing when it started — «sudden» means within minutes or hours, as the patient says, never assumed; numbness or tingling alone, without weakness, is not must-go unless it is of the face, of a whole side, or of the groin with leg weakness; numbness of one arm or one leg alone gets the onset question first), it is not confirmed yet: ask ONE question about the missing part before choosing the level; when leg weakness or numbness has no stated onset, that question MUST ask when it started (walking or back pain may go in the same question, never instead of it) (\'¿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?\' / \'¿La debilidad es de todo el cuerpo, como cansancio, o de un brazo, una pierna o un lado?\' / \'¿Desde cuándo lo sientes, fue de golpe o poco a poco, y puedes caminar?\'). 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, and they never drive themselves; if they are alone: \'pide que alguien venga por ti o toma un taxi; si no puedes moverte o te sientes peor, llama al 911\'. 911 (or an ambulance) FIRST, alone or not and even if they can move, for: anaphylaxis; fainting they have not fully recovered from; a seizure or sudden confusion; a possible stroke (sudden weakness of one side, an arm or a leg, sudden numbness of the face or a whole side, a drooping face, sudden trouble speaking); chest pain with clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw; INTENSE shortness of breath at rest; shock; heavy bleeding (vomiting blood, a lot of black or bloody stool, or bleeding that soaks through cloths or towels; a nosebleed or other bleed that keeps going despite pressure without soaking through is must-go, not 911-first); and cord compression when they cannot walk. For anaphylaxis, 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\'), the availability line and, as in `asap` and `urgent`, at most the one conditional urgencias line below — no direct 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`: never 911 and never an instruction to go now, unless an internal instruction from the system (the patient timer) asks you to — the team decides where they are seen. The one warning sign allowed above may point to urgencias, as a single calm conditional line about ONE symptom they already reported getting clearly worse (\'si el dolor aumenta mucho, ve a urgencias con alguien que te acompañe\'): one condition, no list of signs and no \'si alguno de estos…\', no other symptom or body part, and never 911 in it (one exception: chest pain with only mild or doubtful shortness of breath, kept at `asap`, where that line is always: \'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: accompanied, someone or a taxi coming, or the ambulance called.\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 (an invitation to write again if it changes or worries them — never a time, and no urgencias beyond the one conditional line `asap` and `urgent` allow). `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`).',
29
+ '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; `details` and the justification are INTERNAL — the patient never sees them. Only `patient_check_in` and `patient_symptom_label` reach the patient.\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 now, with no question that invites a downgrade: `asap` by default, `stat` if there is an acute deficit (new, sudden weakness of an arm, a leg or one side, numbness of the face or a whole side, a drooping face or new trouble speaking — even if they can still move it —; new loss of bladder or bowel control; new or worsening leg weakness with back or neck pain, known spine disease or bone metastases (or, with bone status unknown, a cancer that often spreads to the spine), or groin numbness, or sudden weakness of both legs → possible cord compression) or any instability; an acute deficit is must-go and asks nothing, except the one onset question when it is not yet known whether it came on suddenly. In `asap`, ask the short neuro checklist in the same message as ONE question on one line, not a numbered list (\'¿Sabes dónde estás y qué día es, puedes hablar bien, ves bien, sientes debilidad de un lado, has vomitado o convulsionado?\'), keeping the message ≤60 words — the one exception to asking about a single sign and to no lists.\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`, 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, or vomiting blood or black, tarry stool together with dizziness or near-fainting on standing (even without the skin signs of shock); fainting or loss of consciousness; INTENSE shortness of breath at rest (mild breathlessness at rest is not must-go, except with the checkpoint-inhibitor signs below); chest pain with CLEAR shortness of breath, cold sweat, or spreading to the arm or jaw; sudden confusion or a seizure; NEW, SUDDEN weakness of one arm, one leg or one side, numbness of the face or of a whole side (face, arm and leg), a drooping face or new trouble speaking, even if they can still move it (a known, long-standing limitation is not sudden; general weakness or tiredness, or not getting up from fatigue, is not must-go: `asap`, or `urgent` if it is gradual and they are eating, drinking and passing urine; if they cannot stand because they feel faint, check it against fainting and shock); possible cord compression — NEW or WORSENING weakness in the legs TOGETHER WITH back or neck pain, known spine disease or bone metastases (or, with bone status unknown, a cancer that often spreads to the spine: breast, prostate, lung, kidney, myeloma), or numbness in the groin or buttocks, even if it came on over hours or days; or SUDDEN weakness of both legs (it came on within hours), even without back pain; or new loss of bladder or bowel control on its own (not feeling or not holding urine or stool, or not being able to pass urine; urgency from diarrhea is not this) — tingling or numbness in hands and feet from neuropathy, or long-standing leg weakness without back pain, is not must-go, and new back pain with no neurologic sign is `asap`; on active or recent checkpoint-inhibitor immunotherapy, drooping eyelids, double vision, new trouble swallowing or leg weakness getting worse over days is at least `asap`, and must-go with shortness of breath at rest or when they cannot swallow; 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, or mottled, or grey or bluish lips, TOGETHER WITH at least one of: near-fainting on standing, new confusion or drowsiness, a racing heart at rest, or almost no urine (none in 12 hours or more); pallor, tiredness or weakness without those skin signs is not must-go (`asap`). 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, pallor or tiredness alone. When a sign is only partly described (swollen lips, hives or a strange throat with nothing else; cold or mottled skin with nothing else; weakness without knowing whether it is one side; leg weakness or numbness without knowing when it started — «sudden» means within minutes or hours, as the patient says, never assumed; numbness or tingling alone, without weakness, is not must-go unless it is of the face, of a whole side, or of the groin with leg weakness; numbness of one arm or one leg alone gets the onset question first), it is not confirmed yet: ask ONE question about the missing part before choosing the level; when leg weakness or numbness has no stated onset, that question MUST ask when it started (walking or back pain may go in the same question, never instead of it) (\'¿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?\' / \'¿La debilidad es de todo el cuerpo, como cansancio, o de un brazo, una pierna o un lado?\' / \'¿Desde cuándo lo sientes, fue de golpe o poco a poco, y puedes caminar?\'). 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, and they never drive themselves; if they are alone: \'pide que alguien venga por ti o toma un taxi; si no puedes moverte o te sientes peor, llama al 911\'. 911 (or an ambulance) FIRST, alone or not and even if they can move, for: anaphylaxis; fainting they have not fully recovered from; a seizure or sudden confusion; a possible stroke (sudden weakness of one side, an arm or a leg, sudden numbness of the face or a whole side, a drooping face, sudden trouble speaking); chest pain with clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw; INTENSE shortness of breath at rest; shock; heavy bleeding (vomiting blood, a lot of black or bloody stool, or bleeding that soaks through cloths or towels; a nosebleed or other bleed that keeps going despite pressure without soaking through is must-go, not 911-first); and cord compression when they cannot walk. For anaphylaxis, 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\'), the availability line and, as in `asap` and `urgent`, at most the one conditional urgencias line below — no direct 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`: never 911 and never an instruction to go now, unless an internal instruction from the system (the patient timer) asks you to — the team decides where they are seen. The one warning sign allowed above may point to urgencias, as a single calm conditional line about ONE symptom they already reported getting clearly worse (\'si el dolor aumenta mucho, ve a urgencias con alguien que te acompañe\'): one condition, no list of signs and no \'si alguno de estos…\', no other symptom or body part, and never 911 in it (one exception: chest pain with only mild or doubtful shortness of breath, kept at `asap`, where that line is always: \'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: accompanied, someone or a taxi coming, or the ambulance called.\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 (an invitation to write again if it changes or worries them — never a time, and no urgencias beyond the one conditional line `asap` and `urgent` allow). `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`).',
28
30
  'strict': true,
29
31
  'parameters': {
30
32
  'type': 'object',
@@ -50,10 +52,21 @@ const definition = {
50
52
  }
51
53
  ]
52
54
  },
55
+ 'patient_symptom_label': {
56
+ 'anyOf': [
57
+ {
58
+ 'type': 'string',
59
+ 'description': 'Nullable. What the patient is going through, in the patient\'s own words, 2 to 6 words with the article (\'la visión borrosa y los mareos\', \'el dolor de la rodilla\'). The patient reads it verbatim days later in the case follow-up, so it is patient-facing, unlike `details`: NO grades, scales, numbers, lab values, drugs, diagnoses, CTCAE or medical terms, dates or names. On an update about the same episode, repeat the label you gave it. Pass `null` only when you cannot name it that way — the neutral question is used then.'
60
+ },
61
+ {
62
+ 'type': 'null'
63
+ }
64
+ ]
65
+ },
53
66
  'urgency_justification': {
54
67
  'type': 'string',
55
68
  'description': 'Por qué ESTE nivel — y explícitamente por qué no el inmediato superior ni el inferior (qué dato objetivo define el tier). Es el registro auditable de la decisión. Una o dos frases. INTERNO; el paciente nunca lo ve. '
56
- + MEDICATION_NAMING_RULE
69
+ + ABSENT_ONLY_IF_DENIED + MEDICATION_NAMING_RULE
57
70
  },
58
71
  'details': {
59
72
  'type': 'object',
@@ -72,7 +85,7 @@ const definition = {
72
85
  'persistent_symptom_72h',
73
86
  'stale_clinical_context'
74
87
  ],
75
- 'description': 'Rama clínica que motiva la escalación. Elige la que describe el motivo, no la más frecuente.\n- `febrile_neutropenia`: fiebre o sospecha de infección en ventana de quimioterapia.\n- `neuro_constellation`: DOS O MÁS de — cambio visual, mareo/vértigo/pérdida de equilibrio, incapacidad de caminar o mantenerse en pie, debilidad o adormecimiento focal, confusión aguda, cefalea súbita intensa — en este turno o en los últimos 2-3. Cuenta los que el paciente reporta, no los que descartas. Esta rama fuerza `asap` como mínimo.\n- `spinal_cord_compression`: debilidad de piernas nueva o en aumento con dolor de espalda o cuello, enfermedad de columna o metástasis óseas (o, si no se sabe, un cáncer que suele ir a la columna), o adormecimiento en ingle o glúteos; debilidad de las dos piernas de golpe; o pérdida nueva del control de orina o excremento.\n- `treatment_concern`: duda o efecto atribuible al tratamiento en curso.\n- `persistent_symptom_72h`: síntoma que lleva MÁS DE 72 HORAS sin resolverse. No es el cajón por defecto: un síntoma de hoy o de ayer no entra aquí.\n- `stale_clinical_context`: el expediente no refleja la situación real del paciente.'
88
+ 'description': 'Rama clínica que motiva la escalación. Elige la que describe el motivo, no la más frecuente.\n- `febrile_neutropenia`: un dato de temperatura en ventana de quimioterapia: 38.0 °C o más, se siente con fiebre o calentura sin termómetro, escalofríos o temblores, malestar tras paracetamol, antiinflamatorio o corticoide en las últimas 6 h, o menos de 36.0 °C confirmado al volver a medir con malestar. No lo es un síntoma de la semana de defensas bajas sin ese dato (sangrado, diarrea, dolor de garganta, sudoración, hinchazón): eso es `treatment_concern`. Una lectura de 36.0 a 37.4 °C no es fiebre, y un antipirético de hace más de 6 h no sostiene la etiqueta: una temperatura medida después, normal y sin escalofríos, descarta la fiebre. En una actualización, si la fiebre quedó descartada, cambia a `treatment_concern` aunque la alarma anterior fuera `febrile_neutropenia`.\n- `neuro_constellation`: DOS O MÁS de — cambio visual, mareo/vértigo/pérdida de equilibrio, incapacidad de caminar o mantenerse en pie, debilidad o adormecimiento focal, confusión aguda, cefalea súbita intensa — en este turno o en los últimos 2-3. Cuenta los que el paciente reporta, no los que descartas. Esta rama fuerza `asap` como mínimo.\n- `spinal_cord_compression`: debilidad de piernas nueva o en aumento con dolor de espalda o cuello, enfermedad de columna o metástasis óseas (o, si no se sabe, un cáncer que suele ir a la columna), o adormecimiento en ingle o glúteos; debilidad de las dos piernas de golpe; o pérdida nueva del control de orina o excremento.\n- `treatment_concern`: duda o efecto atribuible al tratamiento en curso.\n- `persistent_symptom_72h`: síntoma que lleva MÁS DE 72 HORAS sin resolverse. No es el cajón por defecto: un síntoma de hoy o de ayer no entra aquí.\n- `stale_clinical_context`: el expediente no refleja la situación real del paciente.'
76
89
  },
77
90
  {
78
91
  'type': 'null'
@@ -105,7 +118,7 @@ const definition = {
105
118
  'anyOf': [
106
119
  {
107
120
  'type': 'string',
108
- 'description': 'Sospecha operativa interna para triage. NUNCA se menciona al paciente.'
121
+ 'description': 'Sospecha operativa interna para triage. NUNCA se menciona al paciente. ' + ABSENT_ONLY_IF_DENIED
109
122
  },
110
123
  {
111
124
  'type': 'null'
@@ -139,6 +152,7 @@ const definition = {
139
152
  'required': [
140
153
  'urgency_level',
141
154
  'patient_check_in',
155
+ 'patient_symptom_label',
142
156
  'urgency_justification',
143
157
  'details',
144
158
  'reasoning'
@@ -310,6 +324,7 @@ async function handler(args, context = {}) {
310
324
  urgencyLevel: requestedLevel,
311
325
  category,
312
326
  symptom: details.symptom || null,
327
+ patientLabel: typeof args?.patient_symptom_label === 'string' ? args.patient_symptom_label : null,
313
328
  evidenceQuote: details.evidence_quote || null,
314
329
  suspectedCondition: details.suspected_condition || null,
315
330
  recommendedAction: details.recommended_action || null,
@@ -4,10 +4,12 @@ const { handle24HourWindowError } = require('./templateRecoveryHelper');
4
4
  const { handleBlockedDelivery, handleRetryableChannelError } = require('./channelRetryHelper');
5
5
 
6
6
  const BLOCKED_DELIVERY = { name: 'blocked_delivery', handle: handleBlockedDelivery };
7
+ const CONTENT_RETRY = { name: 'content_retry', handle: (message, twilioSid, errorCode) => handleRetryableChannelError(message, twilioSid, errorCode) };
7
8
 
8
9
  const CHANNEL_ERROR_STRATEGIES = {
9
10
  63016: { name: 'window_recovery', handle: (message, twilioSid) => handle24HourWindowError(message, twilioSid) },
10
- 63021: { name: 'content_retry', handle: (message, twilioSid, errorCode) => handleRetryableChannelError(message, twilioSid, errorCode) },
11
+ 63007: CONTENT_RETRY,
12
+ 63021: CONTENT_RETRY,
11
13
  63032: BLOCKED_DELIVERY,
12
14
  63049: BLOCKED_DELIVERY
13
15
  };
@@ -7,6 +7,7 @@ const { isAtOrBefore } = require('../utils/dateUtils');
7
7
  const { Message } = require('../models/messageModel');
8
8
  const { ScheduledMessage } = require('../models/agendaMessageModel');
9
9
  const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES: LANDED_STATUSES } = require('../models/deliveryAttemptModel');
10
+ const { freeformRetryBlockedReason } = require('../services/channelRetryService');
10
11
  const { formatOpsAlert, recordUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
11
12
  const { closeExpiredRecovery, fixedTemplateFor, recoverySendData } = require('./templateRecoveryHelper');
12
13
  const { patientIsDeceased } = require('./pausedThreadHelper');
@@ -17,6 +18,7 @@ const getMessaging = () => require('../core/NexusMessaging');
17
18
 
18
19
  const REFUSED_ON_PURPOSE = new Set(['patient_deceased', 'outbound_blocked']);
19
20
 
21
+ const FREEFORM_RETRYABLE_CODES = new Set(['63007']);
20
22
  const DEFAULT_RETRY_DELAYS_MS = [2 * 60 * 1000, 10 * 60 * 1000, 30 * 60 * 1000];
21
23
  const SIGNED_MEDIA_PATH = /^\d+\/\d+\/(\d{13})\//;
22
24
 
@@ -79,7 +81,7 @@ function earliestMediaExpiry(variables) {
79
81
  }
80
82
 
81
83
  function alertUndeliverable(payload) {
82
- logger.error('[ChannelRetry] Message undeliverable, no retries left', payload);
84
+ logger.error('[ChannelRetry] Message undeliverable, not retrying', payload);
83
85
  try {
84
86
  const eventBus = getMessaging().getEventBus();
85
87
  safeEmit(eventBus, 'message:undeliverable', createEvent('message:undeliverable', payload));
@@ -88,24 +90,44 @@ function alertUndeliverable(payload) {
88
90
  }
89
91
  }
90
92
 
91
- async function handleRetryableChannelError(messageDoc, twilioSid, errorCode) {
92
- const messageId = messageDoc?._id;
93
- const code = messageDoc?.numero;
94
- if (!messageId || !code) return { retried: false, reason: 'incomplete_message' };
93
+ async function scheduleRetry(messageDoc, retry, logCtx) {
94
+ const scheduled = await ScheduledMessage.create({
95
+ code: messageDoc.numero,
96
+ ...retry,
97
+ parentMessageId: messageDoc._id,
98
+ triggeredBy: 'channel_retry',
99
+ expiresAt: messageDoc.expiresAt
100
+ });
95
101
 
96
- const logCtx = { twilioSid, errorCode, messageId: String(messageId) };
102
+ try {
103
+ await getMessaging().sendScheduledMessage(scheduled);
104
+ } catch (err) {
105
+ await ScheduledMessage.deleteOne({ _id: scheduled._id }).catch(cleanupErr =>
106
+ logger.error('[ChannelRetry] Could not remove the unqueued retry', {
107
+ ...logCtx, scheduledMessageId: String(scheduled._id), error: cleanupErr.message
108
+ })
109
+ );
110
+ alertUndeliverable({ ...logCtx, reason: 'enqueue_failed', error: err.message });
111
+ return null;
112
+ }
113
+ return scheduled;
114
+ }
97
115
 
98
- const attempt = await DeliveryAttempt.findOne({ twilioSid }, 'contentSid variables').lean();
116
+ async function expiresBeforeRetry(messageDoc, delay, logCtx) {
117
+ if (!isAtOrBefore(messageDoc.expiresAt, new Date(Date.now() + (delay ?? 0)))) return false;
118
+ logger.info('[ChannelRetry] Message expires before the retry, skipping', { ...logCtx, expiresAt: messageDoc.expiresAt });
119
+ await closeExpiredRecovery(messageDoc);
120
+ return true;
121
+ }
99
122
 
100
- if (!attempt?.contentSid) {
101
- logger.info('[ChannelRetry] Not a template send, skipping retry', logCtx);
102
- return { retried: false, reason: 'not_a_template' };
103
- }
123
+ async function retryTemplate(messageDoc, attempt, logCtx) {
124
+ const messageId = messageDoc._id;
125
+ logCtx = { ...logCtx, contentSid: attempt.contentSid };
104
126
 
105
127
  // An attempt written before the variables field existed omits the key entirely, and there the
106
128
  // payload is genuinely unknown. A recorded null means the send carried no contentVariables.
107
129
  if (!Object.prototype.hasOwnProperty.call(attempt, 'variables')) {
108
- alertUndeliverable({ ...logCtx, contentSid: attempt.contentSid, reason: 'variables_not_recorded' });
130
+ alertUndeliverable({ ...logCtx, reason: 'variables_not_recorded' });
109
131
  return { retried: false, reason: 'variables_not_recorded' };
110
132
  }
111
133
 
@@ -122,14 +144,10 @@ async function handleRetryableChannelError(messageDoc, twilioSid, errorCode) {
122
144
  : await DeliveryAttempt.countDocuments({ messageId, kind: 'template' });
123
145
  const delay = retryDelays()[priorAttempts - 1];
124
146
 
125
- if (isAtOrBefore(messageDoc.expiresAt, new Date(Date.now() + (delay ?? 0)))) {
126
- logger.info('[ChannelRetry] Message expires before the retry, skipping', { ...logCtx, expiresAt: messageDoc.expiresAt });
127
- await closeExpiredRecovery(messageDoc);
128
- return { retried: false, reason: 'expires_before_retry' };
129
- }
147
+ if (await expiresBeforeRetry(messageDoc, delay, logCtx)) return { retried: false, reason: 'expires_before_retry' };
130
148
 
131
149
  if (delay === undefined) {
132
- alertUndeliverable({ ...logCtx, contentSid: attempt.contentSid, attempts: priorAttempts, reason: 'max_attempts' });
150
+ alertUndeliverable({ ...logCtx, attempts: priorAttempts, reason: 'max_attempts' });
133
151
  return { retried: false, reason: 'max_attempts' };
134
152
  }
135
153
 
@@ -138,39 +156,86 @@ async function handleRetryableChannelError(messageDoc, twilioSid, errorCode) {
138
156
 
139
157
  if (mediaExpiry !== null && mediaExpiry <= sendTime.getTime()) {
140
158
  alertUndeliverable({
141
- ...logCtx, contentSid: attempt.contentSid, reason: 'media_expires_before_retry',
159
+ ...logCtx, reason: 'media_expires_before_retry',
142
160
  mediaExpiry: new Date(mediaExpiry).toISOString(), sendTime: sendTime.toISOString()
143
161
  });
144
162
  return { retried: false, reason: 'media_expires_before_retry' };
145
163
  }
146
164
 
147
- const scheduled = await ScheduledMessage.create({
148
- code,
149
- contentSid: attempt.contentSid,
150
- variables,
151
- sendTime,
152
- parentMessageId: messageId,
153
- triggeredBy: 'channel_retry',
154
- expiresAt: messageDoc.expiresAt
155
- });
165
+ const scheduled = await scheduleRetry(messageDoc, { contentSid: attempt.contentSid, variables, sendTime }, logCtx);
166
+ if (!scheduled) return { retried: false, reason: 'enqueue_failed' };
156
167
 
157
- try {
158
- await getMessaging().sendScheduledMessage(scheduled);
159
- } catch (err) {
160
- await ScheduledMessage.deleteOne({ _id: scheduled._id }).catch(cleanupErr =>
161
- logger.error('[ChannelRetry] Could not remove the unqueued retry', {
162
- ...logCtx, scheduledMessageId: String(scheduled._id), error: cleanupErr.message
163
- })
164
- );
165
- alertUndeliverable({ ...logCtx, contentSid: attempt.contentSid, reason: 'enqueue_failed', error: err.message });
166
- return { retried: false, reason: 'enqueue_failed' };
168
+ logger.warn('[ChannelRetry] Retry scheduled', { ...logCtx, attempts: priorAttempts, delayMs: delay });
169
+ return { retried: true, attempt: priorAttempts, delayMs: delay, scheduledMessageId: String(scheduled._id) };
170
+ }
171
+
172
+ const hasMedia = media => Boolean(media && Object.values(media).some(value => value != null));
173
+
174
+ async function retryFreeform(messageDoc, attempt, logCtx) {
175
+ if (hasMedia(messageDoc.media)) {
176
+ alertUndeliverable({ ...logCtx, reason: 'media_not_recorded' });
177
+ return { retried: false, reason: 'media_not_recorded' };
167
178
  }
168
179
 
169
- logger.warn('[ChannelRetry] Retry scheduled', { ...logCtx, attempts: priorAttempts, delayMs: delay });
180
+ if (!attempt.body) {
181
+ alertUndeliverable({ ...logCtx, reason: 'body_not_recorded' });
182
+ return { retried: false, reason: 'body_not_recorded' };
183
+ }
184
+
185
+ if (!messageDoc.createdAt) return { retried: false, reason: 'incomplete_message' };
186
+
187
+ if (await DeliveryAttempt.exists({ messageId: messageDoc._id, kind: 'freeform', body: { $ne: attempt.body } })) {
188
+ alertUndeliverable({ ...logCtx, reason: 'chunked_message' });
189
+ return { retried: false, reason: 'chunked_message' };
190
+ }
191
+
192
+ const blocked = await freeformRetryBlockedReason(messageDoc, attempt.body);
193
+ if (blocked === 'already_sent') {
194
+ logger.info('[ChannelRetry] Same text already landed for this number, skipping retry', logCtx);
195
+ return { retried: false, reason: blocked };
196
+ }
197
+ if (blocked) {
198
+ alertUndeliverable({ ...logCtx, reason: blocked });
199
+ return { retried: false, reason: blocked };
200
+ }
201
+
202
+ const priorAttempts = await DeliveryAttempt.countDocuments({ messageId: messageDoc._id, kind: 'freeform', body: attempt.body });
203
+ const delay = retryDelays()[priorAttempts - 1];
204
+
205
+ if (await expiresBeforeRetry(messageDoc, delay, logCtx)) return { retried: false, reason: 'expires_before_retry' };
170
206
 
207
+ if (delay === undefined) {
208
+ alertUndeliverable({ ...logCtx, attempts: priorAttempts, reason: 'max_attempts' });
209
+ return { retried: false, reason: 'max_attempts' };
210
+ }
211
+
212
+ const scheduled = await scheduleRetry(messageDoc, { message: attempt.body, sendTime: new Date(Date.now() + delay) }, logCtx);
213
+ if (!scheduled) return { retried: false, reason: 'enqueue_failed' };
214
+
215
+ logger.warn('[ChannelRetry] Freeform retry scheduled', { ...logCtx, attempts: priorAttempts, delayMs: delay });
171
216
  return { retried: true, attempt: priorAttempts, delayMs: delay, scheduledMessageId: String(scheduled._id) };
172
217
  }
173
218
 
219
+ async function handleRetryableChannelError(messageDoc, twilioSid, errorCode) {
220
+ const messageId = messageDoc?._id;
221
+ if (!messageId || !messageDoc?.numero) return { retried: false, reason: 'incomplete_message' };
222
+
223
+ const logCtx = { twilioSid, errorCode, messageId: String(messageId) };
224
+
225
+ if (messageDoc.contact_code) {
226
+ alertUndeliverable({ ...logCtx, reason: 'caregiver_recipient' });
227
+ return { retried: false, reason: 'caregiver_recipient' };
228
+ }
229
+
230
+ const attempt = await DeliveryAttempt.findOne({ twilioSid }, 'kind contentSid variables body').lean();
231
+
232
+ if (attempt?.contentSid) return retryTemplate(messageDoc, attempt, logCtx);
233
+ if (attempt?.kind === 'freeform' && FREEFORM_RETRYABLE_CODES.has(String(errorCode))) return retryFreeform(messageDoc, attempt, logCtx);
234
+
235
+ logger.info('[ChannelRetry] No retryable attempt recorded, skipping retry', logCtx);
236
+ return { retried: false, reason: 'not_retryable' };
237
+ }
238
+
174
239
  async function reportBlockedDelivery(messageDoc, logCtx) {
175
240
  alertUndeliverable({ ...logCtx, reason: 'blocked_by_meta' });
176
241
  const sender = isStaffSend(messageDoc.triggeredBy) ? `de ${messageDoc.triggeredBy}` : 'del asistente';
@@ -1,6 +1,8 @@
1
1
  const { logger } = require('../utils/logger');
2
2
  const { isRetryableError } = require('../utils/retryUtils');
3
3
  const { ScheduledMessage } = require('../models/agendaMessageModel');
4
+ const { alertUndeliverable } = require('../helpers/channelRetryHelper');
5
+ const { scheduledRetryBlockedReason } = require('../services/channelRetryService');
4
6
  const { BaseJob } = require('./BaseJob');
5
7
 
6
8
  const QUEUE_NAME = 'scheduled-messages';
@@ -63,6 +65,20 @@ class ScheduledMessageJob extends BaseJob {
63
65
  return `scheduled-msg-${scheduledMessageId}`;
64
66
  }
65
67
 
68
+ async _cancelUnwantedRetry(msg) {
69
+ const reason = await scheduledRetryBlockedReason(msg);
70
+ if (!reason) return null;
71
+ await ScheduledMessage.updateOne(
72
+ { _id: msg._id },
73
+ { $set: { status: 'cancelled', errorCode: reason, errorMessage: 'Channel retry no longer wanted' } }
74
+ );
75
+ logger.info('[ScheduledMessageJob] Channel retry cancelled', { scheduledMessageId: String(msg._id), reason });
76
+ if (reason !== 'already_sent') {
77
+ alertUndeliverable({ scheduledMessageId: String(msg._id), messageId: String(msg.parentMessageId), code: msg.code, reason });
78
+ }
79
+ return { success: false, reason };
80
+ }
81
+
66
82
  async _process({ scheduledMessageId }) {
67
83
  const msg = await ScheduledMessage.findById(scheduledMessageId);
68
84
 
@@ -99,6 +115,11 @@ class ScheduledMessageJob extends BaseJob {
99
115
  }
100
116
 
101
117
  try {
118
+ if (msg.triggeredBy === 'channel_retry' && msg.message && !msg.contentSid) {
119
+ const cancelled = await this._cancelUnwantedRetry(msg);
120
+ if (cancelled) return cancelled;
121
+ }
122
+
102
123
  const parentMessageId = msg.parentMessageId || null;
103
124
 
104
125
  const result = await this.sendMessage({
@@ -23,6 +23,7 @@ const alarmSchema = new mongoose.Schema({
23
23
  urgencyLevel: { type: String, enum: URGENCY_LEVELS, required: true },
24
24
  category: { type: String, default: null },
25
25
  symptom: { type: String, default: null },
26
+ patientLabel: { type: String, default: null },
26
27
  evidenceQuote: { type: String, default: null },
27
28
  suspectedCondition: { type: String, default: null },
28
29
  recommendedAction: { type: String, default: null },
@@ -4,6 +4,7 @@ const { logger } = require('../utils/logger');
4
4
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
5
5
  const { inlineOf, oneLineOf } = require('../utils/coercionUtils');
6
6
  const { DEFAULT_TIMEZONE, clampToHourWindow } = require('../utils/scheduleUtils');
7
+ const { getMexicoDayLabel } = require('../utils/dateUtils');
7
8
  const { getEscalationReview } = require('../models/escalationReviewModel');
8
9
  const { recordReminder, cancelFollowUp } = require('../clinical/services/clinicalAirtableService');
9
10
  const { escalationCaseFollowUpLive } = require('../clinical/flags/escalationFlags');
@@ -21,8 +22,15 @@ const SEND_WINDOW = { timeZone: DEFAULT_TIMEZONE, startHour: 11, endHour: 21 };
21
22
  const FOLLOW_UP_STATUSES = ['indications_sent', 'monitoring'];
22
23
  const BOOKKEEPING = { timestamps: false };
23
24
  const PLAN_EXCERPT = 400;
25
+ const PATIENT_LABEL_MAX = 40;
24
26
  // The follow-up template the send_reminder automation uses past the 24 h window (Airtable Monitoreo).
25
27
  const FOLLOW_UP_TEMPLATE_SID = 'HX182fee522708bdb43db5ea614f538369';
28
+ // Meta-approved UTILITY templates, by try and by whether she has a label: {{1}} name, {{2}} day she told us, {{3}} label.
29
+ const CASE_TEMPLATES = {
30
+ first: { label: 'HXe9ee7b7cdb018ca78970cd919342de4e', plain: 'HXb079b8c9892d963d1851addcce8b3c6e' },
31
+ retry: { label: 'HXb92572f8516f448c95257b933b123ab0', plain: 'HX6f19d545f6298f97c9d578a62ee2520c' },
32
+ };
33
+ const SENT_TEMPLATE_SIDS = [FOLLOW_UP_TEMPLATE_SID, ...Object.values(CASE_TEMPLATES).flatMap(Object.values)];
26
34
  // send_reminder fires up to 6 min before the row's time.
27
35
  const SEND_LEAD_MS = 10 * 60 * 1000;
28
36
 
@@ -38,34 +46,60 @@ function followUpOf(decision) {
38
46
  return { kind: 'auto', hours: AUTO_HOURS };
39
47
  }
40
48
 
41
- const symptomOf = (review) => inlineOf([...(review.alarms ?? [])].reverse().find((alarm) => inlineOf(alarm.symptom))?.symptom) || null;
49
+ const caseAlarmOf = (review) => [...(review.alarms ?? [])].reverse().find((alarm) => inlineOf(alarm.symptom)) || null;
50
+ const symptomOf = (review) => inlineOf(caseAlarmOf(review)?.symptom) || null;
51
+ const isPatientLabel = (label) => label.length > 0 && label.length <= PATIENT_LABEL_MAX && !/[\d():;+/%=<>≈→—–_]/.test(label);
52
+ const patientLabelOf = (review) => {
53
+ const label = oneLineOf(caseAlarmOf(review)?.patientLabel).replace(/^[¿¡\s]+|[.,¿?¡!\s]+$/g, '').toLowerCase();
54
+ return isPatientLabel(label) ? label : null;
55
+ };
42
56
  const dayOf = (value) => moment(value).tz(DEFAULT_TIMEZONE).format('DD/MM');
43
57
 
44
58
  function questionFor(review, attempt) {
45
- const about = symptomOf(review) ? ` con ${symptomOf(review).toLowerCase()}` : '';
46
- return attempt === 1
47
- ? `¿Cómo has seguido${about}? Cuéntame si vas mejor, igual o peor.`
48
- : `Quería saber cómo vas${about}. ¿Vas mejor, igual o peor?`;
59
+ const label = patientLabelOf(review);
60
+ if (attempt === 1) {
61
+ return label
62
+ ? `${label}. ¿Cómo te has sentido con eso estos días?`
63
+ : 'queremos saber cómo estás. ¿Cómo te has sentido desde entonces?';
64
+ }
65
+ return label
66
+ ? `${label}. Seguimos pendientes de ti. ¿Cómo sigues con eso?`
67
+ : 'seguimos pendientes de ti. ¿Cómo sigues?';
68
+ }
69
+
70
+ function templateFor(review, attempt, sendAt) {
71
+ const label = patientLabelOf(review);
72
+ const templates = attempt === 1 ? CASE_TEMPLATES.first : CASE_TEMPLATES.retry;
73
+ return {
74
+ templateSid: label ? templates.label : templates.plain,
75
+ templateVariables: { 2: getMexicoDayLabel(caseAlarmOf(review)?.raisedAt ?? review.createdAt, sendAt), ...(label && { 3: label }) },
76
+ };
49
77
  }
50
78
 
51
79
  function decisionContext(decision) {
52
80
  const what = decision.decision === 'monitor' ? 'el médico indicó vigilarlo en casa' : 'el médico le dio indicaciones';
53
81
  const sent = decision.plan ? oneLineOf(planSummary(decision.plan)) : oneLineOf(decision.finalText);
54
82
  const excerpt = sent && sent.length > PLAN_EXCERPT ? `${sent.slice(0, PLAN_EXCERPT)}…` : sent;
55
- return `el ${dayOf(decision.createdAt)} ${what}${excerpt ? ` («${excerpt}»)` : ''}`;
83
+ return `El ${dayOf(decision.createdAt)} ${what}${excerpt ? ` («${excerpt}»)` : ''}.`;
56
84
  }
57
85
 
58
86
  function caseInstruction(review, firstName) {
59
87
  const name = firstName || 'la paciente';
60
- const symptom = symptomOf(review)?.toLowerCase() || 'lo que te contó';
61
- const context = decisionContext(review.decisions.at(-1));
88
+ const about = patientLabelOf(review) || 'lo que te contó';
89
+ const note = symptomOf(review);
90
+ const internal = note ? `\n\nNota interna del equipo, solo para ti: «${note}». No la cites ni le pases sus grados, cifras, diagnósticos ni términos clínicos.` : '';
91
+ const how = 'Un solo mensaje breve, cálido y natural, de dos o tres frases. Nombra lo que siente con sus propias palabras de la conversación, nunca con las de la nota. Como mucho una frase de apoyo (por ejemplo «seguimos pendientes de ti»), sin dar por hecho que mejoró, sin prometer nada ni sugerir gravedad. Haz una sola pregunta abierta sobre cómo ha cambiado; no le des opciones como en una encuesta (nada de «mejor, igual o peor»). Tutéala con lenguaje neutro en género.';
92
+ const read = 'Con lo que conteste, entiende tú si va mejor, igual o peor; si no queda claro, repregúntale una sola vez de forma natural, comparando con hace unos días. Si va peor o cuenta algo nuevo, retómalo como cualquier síntoma.';
62
93
  const quiet = 'No menciones alertas, revisiones, el sistema ni que este mensaje estaba programado.';
94
+ const context = `${decisionContext(review.decisions.at(-1))}${internal}`;
63
95
  if (review.caseFollowUp.attempt > 1) {
64
- return `Le preguntaste a ${name} cómo seguía con ${symptom} (${context}) y no ha contestado. Escríbele una vez más, con un mensaje distinto al anterior, breve y cálido, para saber si va mejor, igual o peor. No le reproches que no contestó. ${quiet}`;
96
+ return `Le preguntaste a ${name} cómo seguía con ${about} y no ha contestado. ${context}
97
+
98
+ Escríbele una vez más, distinto al mensaje anterior y más corto. ${how} No le reproches que no contestó. ${read} ${quiet}`;
65
99
  }
66
- return `Toca darle seguimiento a ${name} por ${symptom}: ${context}.
100
+ return `Toca darle seguimiento a ${name} por ${about}. ${context}
67
101
 
68
- Revisa la conversación desde entonces. Si ya te contó cómo va, no se lo vuelvas a preguntar: si dijo que va peor, retómalo; si no, cierra en una línea breve y cálida. Si no lo ha dicho, pregúntale una sola vez, en un mensaje breve y natural, cómo ha seguido con ${symptom}: si va mejor, igual o peor. Si contesta algo poco claro, aclara eso antes de cerrar. ${quiet}`;
102
+ Revisa la conversación desde entonces. Si ya te contó cómo va, no se lo vuelvas a preguntar: si va peor, retómalo; si no, cierra en una línea breve y cálida. Si no lo ha dicho, pregúntaselo una sola vez. ${how} ${read} ${quiet}`;
69
103
  }
70
104
 
71
105
  async function standDown(code, reminderId, reason) {
@@ -77,9 +111,10 @@ async function standDown(code, reminderId, reason) {
77
111
  }
78
112
 
79
113
  async function writeRow(review, caseFollowUp) {
114
+ const template = templateFor(review, caseFollowUp.attempt, caseFollowUp.dueAt);
80
115
  const isRecorded = await recordReminder({
81
116
  code: review.patientCode, trace: null, actionType: 'create', reminderId: caseFollowUp.reminderId, reminderDateUtc: new Date(caseFollowUp.dueAt).toISOString(),
82
- reminderType: 'seguimiento', description: questionFor(review, caseFollowUp.attempt), expiresAtUtc: new Date(new Date(caseFollowUp.dueAt).getTime() + ROW_LIFETIME_MS).toISOString(),
117
+ reminderType: 'seguimiento', description: questionFor(review, caseFollowUp.attempt), ...template, expiresAtUtc: new Date(new Date(caseFollowUp.dueAt).getTime() + ROW_LIFETIME_MS).toISOString(),
83
118
  }).catch((error) => {
84
119
  logger.error('[CaseFollowUp] The follow-up row was not written', { escalationReviewId: String(review._id), error: errorOf(error) });
85
120
  return false;
@@ -167,7 +202,7 @@ async function askedAt(review, now = new Date()) {
167
202
  numero: review.patientCode,
168
203
  from_me: true,
169
204
  createdAt: { $gte: since, $lte: now },
170
- $or: [{ triggeredBy: { $regex: `^send_reminder:${PREFIX}${review._id}_` } }, { triggeredBy: 'send_reminder', content_sid: FOLLOW_UP_TEMPLATE_SID }],
205
+ $or: [{ triggeredBy: { $regex: `^send_reminder:${PREFIX}${review._id}_` } }, { triggeredBy: 'send_reminder', content_sid: { $in: SENT_TEMPLATE_SIDS } }],
171
206
  },
172
207
  { sort: { createdAt: 1 }, limit: 1, select: 'createdAt' },
173
208
  ) || [];
@@ -0,0 +1,45 @@
1
+ const { Message } = require('../models/messageModel');
2
+ const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES: LANDED_STATUSES } = require('../models/deliveryAttemptModel');
3
+ const { botIsPaused } = require('../helpers/pausedThreadHelper');
4
+
5
+ async function freeformLandedElsewhere(messageDoc, body) {
6
+ const siblingMessages = await Message.find({
7
+ numero: messageDoc.numero,
8
+ _id: { $ne: messageDoc._id },
9
+ createdAt: { $gte: messageDoc.createdAt },
10
+ 'statusInfo.status': { $in: LANDED_STATUSES }
11
+ }, '_id').lean();
12
+
13
+ const landed = await DeliveryAttempt.findOne({
14
+ kind: 'freeform',
15
+ status: { $in: LANDED_STATUSES },
16
+ body,
17
+ messageId: { $in: [messageDoc._id, ...siblingMessages.map(m => m._id)] }
18
+ }, '_id').lean();
19
+
20
+ return Boolean(landed);
21
+ }
22
+
23
+ async function patientWroteSince(messageDoc) {
24
+ const inbound = await Message.findOne({
25
+ numero: messageDoc.numero,
26
+ from_me: false,
27
+ createdAt: { $gt: messageDoc.createdAt }
28
+ }, '_id').lean();
29
+ return Boolean(inbound);
30
+ }
31
+
32
+ async function freeformRetryBlockedReason(messageDoc, body) {
33
+ if (await freeformLandedElsewhere(messageDoc, body)) return 'already_sent';
34
+ if (await patientWroteSince(messageDoc)) return 'superseded_by_patient';
35
+ if (messageDoc.origin === 'assistant' && await botIsPaused(messageDoc.numero, { label: '[ChannelRetry]' })) return 'bot_paused';
36
+ return null;
37
+ }
38
+
39
+ async function scheduledRetryBlockedReason(scheduled) {
40
+ const parent = await Message.findById(scheduled.parentMessageId).lean();
41
+ if (!parent?.createdAt) return 'parent_missing';
42
+ return freeformRetryBlockedReason(parent, scheduled.message);
43
+ }
44
+
45
+ module.exports = { freeformRetryBlockedReason, scheduledRetryBlockedReason };
@@ -11,7 +11,7 @@ const { logPatientChange } = require('./patientService');
11
11
  const { getThreadInfo } = require('./threadService');
12
12
  const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES, PRE_DECISION_STATUSES, appliedLevelOf, caseTakenReason, currentAlarms, handOffToDoctor, teamAlertIdentity } = require('./escalationReviewService');
13
13
  const { graveMissingOf, isDraftCurrent, pendingFlagsOf, stillDocumented } = require('./gravePendingService');
14
- const { BUSINESS_HOURS_LEVELS, levelsOf, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
14
+ const { BUSINESS_HOURS_LEVELS, HANDOFF_TAKES_LEVELS, levelsOf, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
15
15
  const { sendGroupNotice, sendTeamAlert } = require('./teamAlertService');
16
16
  const { digestRecipient, digestTimeOf, urgentDigestLive } = require('./doctorDigestService');
17
17
 
@@ -22,7 +22,8 @@ const LEVEL_LABELS = { asap: 'ASAP', urgent: 'URGENT' };
22
22
  const HANDOFF_RETRY_MS = 10 * 60 * 1000;
23
23
  const MAX_HANDOFF_ATTEMPTS = 4;
24
24
  const MAX_NOTE_LENGTH = 200;
25
- const UPDATE_NOTE = 'Actualización: la paciente contestó';
25
+ // A redraft also follows a call note or the agent's own update, so the note does not say the patient answered.
26
+ const UPDATE_NOTE = 'Actualización del caso';
26
27
  const GRAVE_RETRY_MS = 5 * 60 * 1000;
27
28
  const GRAVE_REASONS = { unobtainable: 'no lo puede dar', unanswered: 'no contestó', not_said: 'no lo ha dicho' };
28
29
  const QUIET_REMINDER_TEXT = '¿Pudiste ver lo que te pregunté? Cuando puedas, respóndeme por aquí.';
@@ -63,8 +64,8 @@ function teamGraveOf(review, clock, grave, now) {
63
64
  .filter((ask) => timeOf(ask.draftAt) >= timeOf(firstSeenAt) && (ask.flags ?? []).map(normalizedKeyOf).includes(flag))
64
65
  .map((ask) => timeOf(ask.sentAt)),
65
66
  );
66
- const dueAt = (entry) => (entry.reason === 'unobtainable' ? -Infinity : askedAt(entry) + waitMs);
67
- // A datum the bot never asked about calls no one: it reaches the doctor in the note.
67
+ const dueAt = (entry) => (entry.reason === 'unobtainable' ? Infinity : askedAt(entry) + waitMs);
68
+ // A datum the bot never asked about, or one the patient cannot give, calls no one: it reaches the doctor in the note.
68
69
  const asked = grave.filter((entry) => dueAt(entry) < Infinity);
69
70
  if (asked.some((entry) => dueAt(entry) <= now.getTime())) return { due: asked, waiting: [] };
70
71
  return { due: [], waiting: asked };
@@ -112,7 +113,7 @@ function outcomeOf(review, clock, now) {
112
113
  const teamFirst = !update && !present.length && grave.length + waiting.length > 0;
113
114
  const held = teamFirst && (waiting.length > 0 || grave.some(({ flag }) => now.getTime() < graveDueAt(review, clock, flag) + wait * 60000));
114
115
  if (graveFlags.length || present.length) {
115
- const lacking = graveFlags.length && `Falta dato grave: ${graveFlags.map(({ flag }) => flag).join(', ')}${teamFirst && !held ? ' (no se consiguió)' : ''}`;
116
+ const lacking = graveFlags.length && `Falta dato grave: ${graveFlags.map(({ flag, reason }) => (reason === 'unobtainable' ? `${flag} (${GRAVE_REASONS.unobtainable})` : flag)).join(', ')}${teamFirst && !held ? ' (no se consiguió)' : ''}`;
116
117
  // A grave datum still inside its wait goes in the note too, so the doctor knows it is still open.
117
118
  const pending = pendingFlagsOf(review, clock.since).flags.map(({ flag }) => flag).filter((flag) => !graveFlags.some((entry) => entry.flag === flag));
118
119
  const note = [present.length && `Bandera grave presente: ${present.join(', ')}`, lacking, pending.length && `Pendiente: ${pending.join(', ')}`];
@@ -247,7 +248,7 @@ async function sendGaveUpNotice(review, clock) {
247
248
 
248
249
  async function postHandoffNotice(review, clock, { note }, queuedAt) {
249
250
  const { patient, doctor, link } = await teamAlertIdentity(review);
250
- const taken = await takenOf(review, clock);
251
+ const taken = (HANDOFF_TAKES_LEVELS.includes(clock.level) && !queuedAt) || await takenOf(review, clock);
251
252
  const passed = queuedAt ? `📋 Va al médico en el resumen de urgentes (a más tardar ${digestTimeOf(review, queuedAt)})` : '📋 Pasó al médico';
252
253
  const header = taken ? passed : `${passed} · todavía sin tomar`;
253
254
  const action = !taken && 'Qué hacer: escribir o llamar a la paciente si nadie lo ha hecho';
@@ -4,7 +4,7 @@ const { FOLLOWUP_STATUSES } = require('../models/escalationReviewModel');
4
4
  const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
5
5
  const { escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
6
6
 
7
- const { DRAFT_OPERATOR, PRE_DECISION_STATUSES, caseTakenReason } = require('./escalationReviewService');
7
+ const { DRAFT_OPERATOR, PRE_DECISION_STATUSES, caseTakenBy, caseTakenReason } = require('./escalationReviewService');
8
8
  const { graveMissingOf, isDraftCurrent } = require('./gravePendingService');
9
9
  const { pendingWaitMinutes } = require('./reviewDeadlineService');
10
10
  const { dueStageOf, untakenClockOf } = require('./untakenAlertService');
@@ -14,7 +14,7 @@ const DONE_STATUSES = ['closed', 'cancelled'];
14
14
  const ANSWERABLE_OUTCOMES = ['sent', 'unknown'];
15
15
  const timeOf = (value) => new Date(value).getTime();
16
16
 
17
- const state = (key, label, fields = {}) => ({ key, label, since: null, dueAt: null, nextAlert: null, takenReason: null, graveFlags: [], ...fields });
17
+ const state = (key, label, fields = {}) => ({ key, label, since: null, dueAt: null, nextAlert: null, takenReason: null, takenBy: null, graveFlags: [], ...fields });
18
18
 
19
19
  // The stage the sweep sends on its next tick, else the next one still to come; none while untaken alerts are off.
20
20
  function nextAlertOf(review, clock, now) {
@@ -37,7 +37,13 @@ function waitingOn(review, clock, now) {
37
37
 
38
38
  async function takenOf(review, clock) {
39
39
  try {
40
- return await caseTakenReason(review, clock.since, clock.level);
40
+ const reason = await caseTakenReason(review, clock.since, clock.level);
41
+ if (!reason) return null;
42
+ const by = await caseTakenBy(review, clock.since, reason).catch((error) => {
43
+ logger.warn('[EscalationCaseState] Could not tell who took the case', { escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)) });
44
+ return null;
45
+ });
46
+ return { reason, by };
41
47
  } catch (error) {
42
48
  logger.warn('[EscalationCaseState] Could not tell whether the case was taken', {
43
49
  escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
@@ -56,7 +62,7 @@ async function caseStateOf(review, { now = new Date(), policy } = {}) {
56
62
 
57
63
  const nextAlert = nextAlertOf(review, clock, now);
58
64
  const taken = await takenOf(review, clock);
59
- if (taken) return state('taken', 'Tomado', { since: clock.since, takenReason: taken });
65
+ if (taken) return state('taken', 'Tomado', { since: clock.since, takenReason: taken.reason, takenBy: taken.by });
60
66
  const grave = graveMissingOf(review, clock, now).map(({ flag }) => flag);
61
67
  if (grave.length) return state('grave_missing', 'Falta dato grave', { since: clock.since, nextAlert, graveFlags: grave });
62
68
  if (WITH_DOCTOR_STATUSES.includes(review.status)) return state('with_doctor', label, { since: clock.since, nextAlert });
@@ -57,7 +57,7 @@ const { armCaseFollowUp, cancelCaseFollowUp } = require('./caseFollowUpService')
57
57
 
58
58
  const { getPatientInformation, logPatientChange } = require('./patientService');
59
59
  const { MAX_NOTE_LENGTH, openCaseIds, readPatientCases, updatePatientTask } = require('./patientTaskService');
60
- const { countMessages } = require('./messageService');
60
+ const { countMessages, getMessages } = require('./messageService');
61
61
  const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
62
62
  const { createPrescription } = require('./prescriptionService');
63
63
  const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
@@ -1105,29 +1105,54 @@ async function takenReason(review, since, timer, ownStart = null) {
1105
1105
  return caseTakenReason(review, from, timer.level);
1106
1106
  }
1107
1107
 
1108
+ const levelsAtOf = (review) => {
1109
+ const changes = review.urgencyReclassifications ?? [];
1110
+ return (at) => levelsOf(currentAlarms(review).filter((alarm) => new Date(alarm.raisedAt) <= new Date(at)), changes.filter((change) => new Date(change.at) < new Date(at)), appliedLevelOf);
1111
+ };
1112
+
1113
+ // A lowering means someone looked at the case; a raise restarts the clock instead.
1114
+ const isLoweringOf = (review) => {
1115
+ const levelsAt = levelsAtOf(review);
1116
+ return (change) => (URGENCY_RANK[change.toLevel] || 0) < Math.max(0, ...levelsAt(change.at).map((entry) => URGENCY_RANK[entry.level] || 0));
1117
+ };
1118
+
1119
+ // Staff sign with their email; automations (the timer itself included) sign with a name and never count.
1120
+ const staffReplyFilter = (review, from) => ({ ...humanReplyFilter(review.patientCode, from), origin: { $in: STAFF_ORIGINS }, $and: [{ triggeredBy: /@/ }] });
1121
+
1122
+ const atOrAfterOf = (from) => (at) => at != null && new Date(at).getTime() >= from.getTime();
1123
+
1124
+ const takingDecisionOf = (review, from) => (review.decisions ?? []).find((decision) => atOrAfterOf(from)(decision.createdAt));
1125
+ const takingLoweringOf = (review, from) => {
1126
+ const isLowering = isLoweringOf(review);
1127
+ return (review.urgencyReclassifications ?? []).find((change) => atOrAfterOf(from)(change.at) && isLowering(change));
1128
+ };
1129
+ const takingCallOf = (review, from) => (review.callLogs ?? []).find((call) => call.outcome === 'contacted' && atOrAfterOf(from)(call.calledAt));
1130
+
1108
1131
  // What says the team took the case from `from` on, for a case timed at `level`.
1109
1132
  async function caseTakenReason(review, from, level) {
1110
- const atOrAfter = (at) => at != null && new Date(at).getTime() >= from.getTime();
1111
- if ((review.decisions ?? []).some((decision) => atOrAfter(decision.createdAt))) return 'decision';
1112
- const changes = review.urgencyReclassifications ?? [];
1113
- const levelsAt = (at) => levelsOf(currentAlarms(review).filter((alarm) => new Date(alarm.raisedAt) <= new Date(at)), changes.filter((change) => new Date(change.at) < new Date(at)), appliedLevelOf);
1114
- if (level !== 'stat' && levelsAt(new Date(8.64e15)).some((entry) => entry.level === 'stat')) return 'stat_alarm';
1115
- // A lowering means someone looked at the case; a raise restarts the clock instead.
1116
- const lowered = (change) => (URGENCY_RANK[change.toLevel] || 0) < Math.max(0, ...levelsAt(change.at).map((entry) => URGENCY_RANK[entry.level] || 0));
1117
- if (changes.some((change) => atOrAfter(change.at) && lowered(change))) return 'reclassified';
1118
- if ((review.callLogs ?? []).some((call) => call.outcome === 'contacted' && atOrAfter(call.calledAt))) return 'call_contacted';
1133
+ if (takingDecisionOf(review, from)) return 'decision';
1134
+ if (level !== 'stat' && levelsAtOf(review)(new Date(8.64e15)).some((entry) => entry.level === 'stat')) return 'stat_alarm';
1135
+ if (takingLoweringOf(review, from)) return 'reclassified';
1136
+ if (takingCallOf(review, from)) return 'call_contacted';
1119
1137
  // A read error goes back to the sweep to retry; only a thread that does not exist (no turn to run
1120
1138
  // anyway) skips the prompt.
1121
1139
  const thread = await getThreadInfo(review.patientCode, { rethrow: true });
1122
1140
  if (!thread) return 'thread_missing';
1123
1141
  if (thread.stopped === true) return 'thread_paused';
1124
1142
  if (thread.hospitalizedAt) return 'patient_hospitalized';
1125
- // Staff write from the platform or act through add-instruction / add-msg, always under their email;
1126
- // automations (the timer itself included) sign with a name and never count.
1127
- const staffMessages = await countMessages({ ...humanReplyFilter(review.patientCode, from), origin: { $in: STAFF_ORIGINS }, $and: [{ triggeredBy: /@/ }] });
1143
+ const staffMessages = await countMessages(staffReplyFilter(review, from));
1128
1144
  return staffMessages ? 'staff_message' : null;
1129
1145
  }
1130
1146
 
1147
+ async function caseTakenBy(review, from, reason) {
1148
+ if (reason === 'decision') return takingDecisionOf(review, from)?.recordedBy ?? null;
1149
+ if (reason === 'reclassified') return takingLoweringOf(review, from)?.reclassifiedBy ?? null;
1150
+ if (reason === 'call_contacted') return takingCallOf(review, from)?.loggedBy ?? null;
1151
+ if (reason !== 'staff_message') return null;
1152
+ const [first] = await getMessages(staffReplyFilter(review, from), { select: 'triggeredBy', sort: { createdAt: 1 }, limit: 1 });
1153
+ return first?.triggeredBy ?? null;
1154
+ }
1155
+
1131
1156
  async function armPatientTimerOnJoin(review, alarm, now) {
1132
1157
  try {
1133
1158
  const level = appliedLevelOf(alarm);
@@ -2545,6 +2570,7 @@ module.exports = {
2545
2570
  _resetEscalationReviewIndexes,
2546
2571
  addCallLog,
2547
2572
  remindDoctorOfCase,
2573
+ caseTakenBy,
2548
2574
  caseTakenReason,
2549
2575
  promptedSince,
2550
2576
  currentAlarms,
@@ -5,6 +5,7 @@ const { FOLLOWUP_STATUSES, URGENCY_RANK } = require('../models/escalationReviewM
5
5
  const RESPONSE_MINUTES = { stat: 15, asap: 60, urgent: 240, routine: 720 };
6
6
  const MAX_RESPONSE_MINUTES = 7 * 24 * 60;
7
7
  const BUSINESS_HOURS_LEVELS = ['urgent', 'routine'];
8
+ const HANDOFF_TAKES_LEVELS = ['urgent'];
8
9
  const TEAM_TIMEZONE = 'America/Mexico_City';
9
10
  const DEFAULT_TEAM_HOURS = { days: [1, 2, 3, 4, 5, 6, 7], startHour: 9, endHour: 22 };
10
11
  const UNTAKEN_STAGES = { stat: ['early', 'deadline'], asap: ['early', 'half', 'deadline'], urgent: ['half', 'deadline'] };
@@ -119,6 +120,7 @@ function responseDeadlineOf(review, policy) {
119
120
 
120
121
  module.exports = {
121
122
  BUSINESS_HOURS_LEVELS,
123
+ HANDOFF_TAKES_LEVELS,
122
124
  doctorReminderAt,
123
125
  effectiveUrgencyOf,
124
126
  levelsOf,
@@ -8,16 +8,17 @@ const { readGroupMessageId } = require('../clinical/services/clinicalAirtableSer
8
8
  const { escalationAutoHandoffLive, escalationPatientTimerLive, escalationUntakenAlertsLive, feverPatientTimerLive } = require('../clinical/flags/escalationFlags');
9
9
 
10
10
  const { logPatientChange } = require('./patientService');
11
- const { BUSINESS_HOURS_LEVELS, doctorReminderAt, levelsOf, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
11
+ const { BUSINESS_HOURS_LEVELS, HANDOFF_TAKES_LEVELS, doctorReminderAt, levelsOf, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
12
12
  const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, FEVER_CATEGORY, PRE_DECISION_STATUSES, appliedLevelOf, caseTakenReason, currentAlarms, doctorLink, promptedSince, remindDoctorOfCase, teamAlertIdentity } = require('./escalationReviewService');
13
13
  const { settleCharacterization } = require('./characterizationOutcomeService');
14
14
  const { sendTeamAlert } = require('./teamAlertService');
15
- const { digestStillDue, sendDueDoctorDigests } = require('./doctorDigestService');
15
+ const { digestDueAt, digestStillDue, sendDueDoctorDigests } = require('./doctorDigestService');
16
16
 
17
17
  const UNTAKEN_LEVELS = ['stat', 'asap', 'urgent'];
18
18
  const LOOKBACK_MS = 7 * 24 * 60 * 60 * 1000;
19
19
  // A stage reached this late (an outage, a deploy) is not sent.
20
20
  const STALE_MS = 30 * 60 * 1000;
21
+ const DIGEST_GRACE_MS = 10 * 60 * 1000;
21
22
  const SWEEP_LIMIT = 200;
22
23
  const OPERATOR = 'bot:untakenAlert';
23
24
  const AUDIT_SOURCE = 'escalation_review';
@@ -174,8 +175,13 @@ async function claimStage(review, clock, stage, now, skippedReason = null) {
174
175
  const doctorRangSince = (review, since) => (review.doctorHandoffs ?? [])
175
176
  .some((handoff) => (handoff.transport || handoff.mode === 'copied') && new Date(handoff.createdAt).getTime() >= since.getTime());
176
177
 
177
- async function alertIfUntaken(review, clock, stage, now) {
178
- const taken = await caseTakenReason(review, clock.since, clock.level);
178
+ async function alertIfUntaken(review, clock, stage, now, policy) {
179
+ const digestAt = HANDOFF_TAKES_LEVELS.includes(clock.level) && review.status === 'awaiting_doctor' && digestStillDue(review)
180
+ && new Date(review.digestQueuedAt) >= clock.stagesFrom && digestDueAt([review], policy).getTime();
181
+ if (digestAt && digestAt <= stage.dueAt.getTime() + DIGEST_GRACE_MS && now.getTime() < digestAt + DIGEST_GRACE_MS) return false;
182
+ const withDoctor = HANDOFF_TAKES_LEVELS.includes(clock.level) && review.status === 'awaiting_doctor'
183
+ && (doctorRangSince(review, clock.stagesFrom) || new Date(review.digestSentAt ?? 0) >= clock.stagesFrom);
184
+ const taken = withDoctor ? 'with_doctor' : await caseTakenReason(review, clock.since, clock.level);
179
185
  if (taken) {
180
186
  await claimStage(review, clock, stage, now, taken);
181
187
  return false;
@@ -260,7 +266,7 @@ async function remindDoctorIfDue(review, clock, now, policy) {
260
266
  return !delivery.error;
261
267
  }
262
268
 
263
- // Alerts the team at each stage of a case nobody took (being with the doctor is not taken) and settles the bot's characterization.
269
+ // Alerts the team at each stage of a case nobody took (being with the doctor takes only an urgent case) and settles the bot's characterization.
264
270
  async function sweepUntakenAlerts({ now = new Date() } = {}) {
265
271
  const alerts = escalationUntakenAlertsLive();
266
272
  const autoHandoff = escalationAutoHandoffLive();
@@ -290,7 +296,7 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
290
296
  // A failed team alert must not keep the case from the doctor, so each step fails on its own.
291
297
  try {
292
298
  const stage = alerts && clock && dueStageOf(review, clock, now);
293
- if (stage && await alertIfUntaken(review, clock, stage, now)) sent += 1;
299
+ if (stage && await alertIfUntaken(review, clock, stage, now, policy)) sent += 1;
294
300
  } catch (error) {
295
301
  failed('[UntakenAlert] Could not check a review for an untaken alert', review, error);
296
302
  }
@@ -8,6 +8,8 @@ const getCurrentMexicoDateTime = (at) => nowInMexico(at).format(MEXICO_STAMP);
8
8
 
9
9
  const dayLabel = (day, now) => (day.year() === now.year() ? day.format('dddd D [de] MMMM') : day.format('dddd D [de] MMMM [de] YYYY'));
10
10
 
11
+ const getMexicoDayLabel = (day, at) => dayLabel(nowInMexico(day), nowInMexico(at));
12
+
11
13
  const getMexicoDayLabels = ({ days, at }) => {
12
14
  const now = nowInMexico(at);
13
15
  const labels = [];
@@ -113,6 +115,7 @@ module.exports = {
113
115
  addDays,
114
116
  addWorkingMinutes,
115
117
  getCurrentMexicoDateTime,
118
+ getMexicoDayLabel,
116
119
  getMexicoDayLabels,
117
120
  getMexicoUpcomingDayLabels,
118
121
  parseDate,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.6.0-dev.20938",
3
+ "version": "6.6.0-dev.21349",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",