@peopl-health/nexus 5.72.0-dev.12926 → 5.72.0-dev.13735

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/lib/clinical/flags/escalationFlags.js +10 -0
  2. package/lib/clinical/helpers/chemoContextHelper.js +25 -9
  3. package/lib/clinical/helpers/clinicalContextHelper.js +4 -1
  4. package/lib/clinical/helpers/clinicalProfileHelper.js +18 -4
  5. package/lib/clinical/helpers/drugIdentityHelper.js +60 -0
  6. package/lib/clinical/helpers/gradeEstimateHelper.js +3 -3
  7. package/lib/clinical/helpers/triageCaseBaseHelper.js +16 -3
  8. package/lib/clinical/providers/BaseLLMProvider.js +27 -8
  9. package/lib/clinical/services/clinicalExtractionService.js +12 -5
  10. package/lib/clinical/services/clinicalPatternFloorService.js +3 -2
  11. package/lib/clinical/services/currentRegimenService.js +60 -0
  12. package/lib/clinical/services/dispatcherService.js +11 -6
  13. package/lib/clinical/services/escalationDraftService.js +10 -4
  14. package/lib/clinical/services/gradeAnchorService.js +40 -18
  15. package/lib/clinical/services/gradeClaimService.js +15 -15
  16. package/lib/clinical/services/recommendationRankService.js +1 -1
  17. package/lib/clinical/services/regimenCloserService.js +125 -0
  18. package/lib/clinical/services/supportInvitability.js +6 -1
  19. package/lib/clinical/services/triageGateFloorService.js +1 -1
  20. package/lib/clinical/tools/extractClinicalInfoTool.js +27 -1
  21. package/lib/clinical/tools/openConditionTool.js +4 -2
  22. package/lib/clinical/tools/recordClinicalImpressionTool.js +11 -3
  23. package/lib/clinical/tools/reportMedicalEscalationTool.js +30 -8
  24. package/lib/clinical/tools/setContingencyPlanTool.js +3 -3
  25. package/lib/config/airtableConfig.js +2 -0
  26. package/lib/controllers/escalationReviewController.js +19 -16
  27. package/lib/core/NexusMessaging.js +60 -9
  28. package/lib/fhir/constants/escalationCaseStatus.js +31 -0
  29. package/lib/fhir/constants/projectionSlugs.js +6 -0
  30. package/lib/fhir/index.js +2 -1
  31. package/lib/fhir/projections/contextFactProjection.js +1 -0
  32. package/lib/fhir/resources/CommunicationRequest.js +1 -1
  33. package/lib/fhir/resources/Task.js +42 -1
  34. package/lib/fhir/services/escalationService.js +13 -0
  35. package/lib/index.d.ts +72 -2
  36. package/lib/index.js +6 -0
  37. package/lib/models/escalationReviewModel.js +34 -2
  38. package/lib/services/escalationCaseTaskService.js +35 -0
  39. package/lib/services/escalationReviewService.js +284 -48
  40. package/lib/services/reviewAlertSweepService.js +7 -2
  41. package/lib/services/reviewBoardService.js +2 -0
  42. package/lib/services/threadService.js +2 -1
  43. package/lib/shared/dtos/DispatchedEscalation.js +1 -0
  44. package/lib/utils/dateUtils.js +4 -0
  45. package/lib/utils/retryUtils.js +1 -0
  46. package/package.json +1 -1
@@ -9,17 +9,23 @@ const { armEscalationNet } = require('../services/contingencyDispatchService');
9
9
  const { recordEmergency, writeUnresolvedRequest } = require('../services/clinicalAirtableService');
10
10
  const { activeTriageGateFloor } = require('../services/triageGateFloorService');
11
11
  const { clinicalPatternFloor } = require('../services/clinicalPatternFloorService');
12
- const { escalationAssessmentLive, escalationUpdateModeLive } = require('../flags/escalationFlags');
12
+ const { escalationAssessmentLive, escalationUpdateModeLive, feverPatientTimerLive } = require('../flags/escalationFlags');
13
13
  const { triageGateFloorLive } = require('../flags/triageGateFloorFlags');
14
14
  const { clinicalPatternFloorLive } = require('../flags/clinicalPatternFloorFlags');
15
- const { attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
15
+ const { attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm, setAlarmAppliedLevel } = require('../../services/escalationReviewService');
16
16
  const { URGENCY_RANK } = require('../../models/escalationReviewModel');
17
17
  const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
18
18
  const { logger } = require('../../utils/logger');
19
19
 
20
+ const FEVER_RUBRIC_STAT = 'neutropenia febril CON inestabilidad, fiebre ≥38.0 °C en la ventana de quimioterapia descrita en la regla de fiebre,';
21
+
22
+ const FEVER_RUBRIC_ASAP = 'riesgo de infección sin fiebre ≥38.0 °C en esa ventana (p. ej. 37.5–37.9 °C con el paciente bien),';
23
+
24
+ const FEVER_RULE = 'Fever that is `stat`: ≥38.0 °C within 8 weeks of cytotoxic chemotherapy (or a hematologic cancer, transplant, known neutropenia), any fever within 4 weeks of CAR-T or during bispecific step-up dosing, or sepsis signs with or without fever — say it calmly: "ve a urgencias ahora y di que estás en tratamiento oncológico" (CAR-T / bispecific: call the treating center first). If you don\'t know the treatment or the last dose date, ask in the same message; unknown date on chemo counts as within the window. Fever 37.5–37.9 °C in that window with the patient well is `asap`: remeasure in 30–60 min. ';
25
+
20
26
  const definition = {
21
27
  'name': 'reportMedicalEscalation',
22
- 'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; the payload is INTERNAL — the patient never sees it.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate without a further clarifying question: `asap` by default, `stat` if there is an acute deficit (can\'t walk/stand, sphincter loss, bilateral leg weakness → possible cord compression) or any instability.\n\n**When NOT to call:**\n- 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 safety net specific to THIS case (1–2 observable signs and what to do if they appear) → availability. Explain the purpose in everyday words. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` is the ONLY level that sends the patient now — calm and unambiguous: ve a urgencias ahora, acompañado; 911 (or an ambulance) if they are alone with no one to take them, cannot move safely, or are unstable — being alone counts as unsafe transport, and they never drive themselves. Fever that is `stat`: ≥38.0 °C within 8 weeks of cytotoxic chemotherapy (or a hematologic cancer, transplant, known neutropenia), any fever within 4 weeks of CAR-T or during bispecific step-up dosing, or sepsis signs with or without fever — say it calmly: "ve a urgencias ahora y di que estás en tratamiento oncológico" (CAR-T / bispecific: call the treating center first). If you don\'t know the treatment or the last dose date, ask in the same message; unknown date on chemo counts as within the window. Fever 37.5–37.9 °C in that window with the patient well is `asap`: remeasure in 30–60 min. `asap`: do NOT lead with urgencias — it appears only in the conditional safety net (if [sign] appears or they feel much worse). `urgent`: they can stay home; urgencias only as a worsening-sign safety net. `routine`: acknowledgement, what to watch, when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, after the instruction only confirm they are on their way and accompanied.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and make the fallback explicit to the patient whenever nothing is armed. `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
28
+ 'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; the payload is INTERNAL — the patient never sees it.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate without a further clarifying question: `asap` by default, `stat` if there is an acute deficit (can\'t walk/stand, sphincter loss, bilateral leg weakness → possible cord compression) or any instability.\n\n**When NOT to call:**\n- Unconfirmed/unspecific symptom — ask ONE characterization question via `DeliverPatientMessage` first.\n- Active mental-health crisis — use `reportCrisis`.\n- Patient shared lab/imaging/values/files — use `reportResultsReceived`.\n- Administrative / operative matter (appointments, insurance, authorizations, letters, transport, scheduling, out-of-scope request) or a non-clinical referral (psico-oncología, paliativos, non-oncology medical) — use `reportUnresolvedRequestv2`.\n- Twice in the same turn for the same episode — already committed; a later datum belongs to the same open escalation.\n\n**After the commit:** the escalation does not end the conversation.\n- **Patient message** (`DeliverPatientMessage`, calm, ≤60 words): acknowledge what they told you → \'Ya avisé al equipo médico\' → ONE concrete next step → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside `stat` and the fever rule, no warning signs by default: naming a sign the patient did not mention makes them watch for it and feel it. If one is truly needed, give at most ONE per episode, about the symptom they already reported getting worse or not easing (\'si el dolor no cede con lo que tomas, escríbeme y lo vemos\') — never another body part or symptom, never a list (not even of related symptoms), never the last line. Outside `stat` never write \'de inmediato\', \'con urgencia\', \'máxima urgencia\', \'no esperes\', \'por si acaso\' or \'es poco probable, pero\' — not in \'escríbeme de inmediato\' nor in \'ya avisé con urgencia\': the priority travels to the team, not to the patient. Explain the purpose only in general words (\'para revisar qué está pasando y ver si necesitas algo más\'): never name an organ, a complication, a mechanism or what is being ruled out (\'descartar que sea del corazón\', \'una presión en la columna\') — to an oncology patient that reads as a diagnosis. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` is the ONLY level that sends the patient now — calm and unambiguous: ve a urgencias ahora, acompañado; 911 (or an ambulance) if they are alone with no one to take them, cannot move safely, or are unstable — being alone counts as unsafe transport, and they never drive themselves. ' + FEVER_RULE + '`asap` and `urgent`: no urgencias and no 911 in the message, not even as a condition — the team decides where they are seen (two exceptions: the fever rule, and chest pain with only mild or doubtful shortness of breath, kept at `asap`, where one calm conditional line stays: \'si te cuesta más respirar o el dolor aumenta, ve a urgencias acompañado\'). If they ask whether to go to urgencias or what to watch, answer honestly with 1–2 points about their symptom — the only case where more than one sign is fine. Chest pain alone is not `stat` (anxiety, gastritis, muscle); chest pain WITH clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw IS `stat` (on checkpoint-inhibitor immunotherapy, chest pain is at least `asap`) — even if the patient sounds calm, and even if the two come in different messages of the same episode; otherwise ask ONE question first. `routine`: acknowledgement and when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, after the instruction only confirm they are on their way and accompanied.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and make the fallback explicit to the patient whenever nothing is armed. `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
23
29
  'strict': true,
24
30
  'parameters': {
25
31
  'type': 'object',
@@ -32,13 +38,13 @@ const definition = {
32
38
  'urgent',
33
39
  'routine'
34
40
  ],
35
- 'description': 'Tier of medical escalation — the FHIR request-priority code (RequestPriority), a RELATIVE urgency ordered routine < urgent < asap < stat. It encodes priority / speed-of-action, NOT a fixed time window — the per-case clock is safety_gate.max_action_time_hours. 1:1 with the gate route. In urgency_justification say why this level and not the one above or below.\n- `stat` (inmediato, gate emergencia) — acción inmediata, prioridad máxima, flujo de emergencia. Inestabilidad o amenaza vital: neutropenia febril CON inestabilidad, fiebre ≥38.0 °C en la ventana de quimioterapia descrita en la regla de fiebre, disnea severa, alteración del estado mental, sangrado mayor, compresión medular con déficit agudo.\n- `asap` (lo antes posible, gate urgencias) — máxima prioridad NO inmediata; objetivo interno de valoración en horas (no se le promete al paciente), porque la demora puede crear riesgo; el paciente no va a urgencias salvo que aparezca una señal de la red de seguridad. Complicación seria sospechada pero aún no claramente inestable: dolor que empeora rápido, riesgo de infección sin fiebre ≥38.0 °C en esa ventana (p. ej. 37.5–37.9 °C con el paciente bien), síntoma neurológico nuevo sin déficit agudo.\n- `urgent` (urgente, gate equipo_tratante_hoy) — objetivo interno de revisión en 24 h (no se le promete al paciente), por encima de rutina porque la demora podría importar clínicamente; el paciente puede seguir en casa con una red de seguridad: síntoma nuevo moderado, anormalidad de laboratorio preocupante pero estable, toxicidad de tratamiento que necesita input oportuno.\n- `routine` (rutina, sin gate o verdict suavizado) — prioridad normal, vía de atención habitual. Sin riesgo por demora: seguimiento, aclaración de medicación, síntoma >72h sin empeorar, contexto clínico desactualizado.'
41
+ 'description': 'Tier of medical escalation — the FHIR request-priority code (RequestPriority), a RELATIVE urgency ordered routine < urgent < asap < stat. It encodes priority / speed-of-action, NOT a fixed time window — the per-case clock is safety_gate.max_action_time_hours. 1:1 with the gate route. In urgency_justification say why this level and not the one above or below.\n- `stat` (inmediato, gate emergencia) — acción inmediata, prioridad máxima, flujo de emergencia. Inestabilidad o amenaza vital: ' + FEVER_RUBRIC_STAT + ' disnea severa, dolor de pecho con falta de aire clara, alteración del estado mental, sangrado mayor, compresión medular con déficit agudo.\n- `asap` (lo antes posible, gate urgencias) — máxima prioridad NO inmediata; objetivo interno de valoración en horas (no se le promete al paciente), porque la demora puede crear riesgo; el paciente no va a urgencias; el equipo decide dónde se le valora. Complicación seria sospechada pero aún no claramente inestable: dolor que empeora rápido, ' + FEVER_RUBRIC_ASAP + ' síntoma neurológico nuevo sin déficit agudo.\n- `urgent` (urgente, gate equipo_tratante_hoy) — objetivo interno de revisión en 24 h (no se le promete al paciente), por encima de rutina porque la demora podría importar clínicamente; el paciente puede seguir en casa: síntoma nuevo moderado, anormalidad de laboratorio preocupante pero estable, toxicidad de tratamiento que necesita input oportuno.\n- `routine` (rutina, sin gate o verdict suavizado) — prioridad normal, vía de atención habitual. Sin riesgo por demora: seguimiento, aclaración de medicación, síntoma >72h sin empeorar, contexto clínico desactualizado.'
36
42
  },
37
43
  'patient_check_in': {
38
44
  'anyOf': [
39
45
  {
40
46
  'type': 'string',
41
- 'description': 'Nullable. The check-in this patient receives ONLY IF they go silent for hours after this escalation — the safety net writes to them again so the thread is not lost. Write it now, for delivery later: in their voice and language, short, warm, asking how they are and how the symptom has evolved since. Reference what they told you in their own words. NO diagnosis, NO grades or CTCAE terms, NO internal phrasing — they never see `details`. Always send the key: pass `null` when you have nothing better than the neutral fallback, which is what gets used then — a bad check-in is worse than none.'
47
+ 'description': 'Nullable. The check-in this patient receives ONLY IF they go silent for hours after this escalation — the safety net writes to them again so the thread is not lost. Write it now, for delivery later: in their voice and language, short, warm, asking how they are and how the symptom has evolved since. Never ask whether the care team contacted them or gave an indication — that is not yours to ask, and it may arrive after the team already did. Reference what they told you in their own words. NO diagnosis, NO grades or CTCAE terms, NO internal phrasing — they never see `details`. Always send the key: pass `null` when you have nothing better than the neutral fallback, which is what gets used then — a bad check-in is worse than none.'
42
48
  },
43
49
  {
44
50
  'type': 'null'
@@ -153,6 +159,12 @@ const MODE_PROPERTY = {
153
159
 
154
160
  const MODE_DESCRIPTION = '\n\n**mode:** `new` abre un aviso; `update` actualiza la escalación abierta y nunca baja su nivel. Lo que el paciente responde después de escalar va con `update`. El `urgency_level` del recibo es el nivel aplicado: puede ser mayor que el que pediste, nunca menor.';
155
161
 
162
+ const FEVER_RULE_TIMER = 'Fever within 6 weeks (42 days) of cytotoxic chemotherapy (or with a hematologic cancer, transplant, known neutropenia) — ≥38.0 °C, ≤36.0 °C, feeling feverish or chills with no thermometer, or malaise while on an antipyretic or steroid — is `asap` with `category: febrile_neutropenia`. It is `stat` only with a clear, confirmed red flag (clear shortness of breath, clear confusion, strong rigors, mottled skin, bleeding), or any fever within 4 weeks of CAR-T or during bispecific step-up dosing — say it calmly: "ve a urgencias ahora y di que estás en tratamiento oncológico" (CAR-T / bispecific: call the treating center first). If you don\'t know the treatment or the last dose date, ask in the same message. 37.5–37.9 °C in that window is `urgent`: remeasure in 30–60 min. ';
163
+
164
+ const FEVER_RUBRIC_STAT_TIMER = 'fiebre en la ventana de quimioterapia con una bandera roja confirmada (regla de fiebre),';
165
+
166
+ const FEVER_RUBRIC_ASAP_TIMER = 'fiebre ≥38.0 °C o ≤36.0 °C en la ventana de quimioterapia sin bandera roja (regla de fiebre),';
167
+
156
168
  const CLINICAL_ASSESSMENT_PROPERTY = nullable({
157
169
  'type': 'object',
158
170
  'description': 'Tu razonamiento clínico, estructurado para auditoría. Todos los campos aceptan `null`. No cambia el nivel: el nivel lo decides tú en `urgency_level`.',
@@ -195,7 +207,8 @@ const CLINICAL_ASSESSMENT_PROPERTY = nullable({
195
207
  function liveDefinition() {
196
208
  const updateMode = escalationUpdateModeLive();
197
209
  const assessment = escalationAssessmentLive();
198
- if (!updateMode && !assessment) return definition;
210
+ const feverTimer = feverPatientTimerLive();
211
+ if (!updateMode && !assessment && !feverTimer) return definition;
199
212
  const live = structuredClone(definition);
200
213
  const { properties, required } = live.parameters;
201
214
  if (updateMode) {
@@ -207,6 +220,12 @@ function liveDefinition() {
207
220
  properties.details.properties.clinical_assessment = CLINICAL_ASSESSMENT_PROPERTY;
208
221
  properties.details.required.push('clinical_assessment');
209
222
  }
223
+ if (feverTimer) {
224
+ live.description = live.description.replace(FEVER_RULE, FEVER_RULE_TIMER);
225
+ properties.urgency_level.description = properties.urgency_level.description
226
+ .replace(FEVER_RUBRIC_STAT, FEVER_RUBRIC_STAT_TIMER)
227
+ .replace(FEVER_RUBRIC_ASAP, FEVER_RUBRIC_ASAP_TIMER);
228
+ }
210
229
  return live;
211
230
  }
212
231
 
@@ -317,13 +336,16 @@ async function handler(args, context = {}) {
317
336
  const gateFloor = gateCheck?.floor || null;
318
337
  const raisedByGate = Boolean(gateFloor) && (URGENCY_RANK[gateFloor.level] || 0) > (URGENCY_RANK[agentLevel] || 0);
319
338
  const flooredLevel = raisedByGate ? gateFloor.level : agentLevel;
320
- const patternCheck = clinicalPatternFloorLive() && runtime.patientCode && (URGENCY_RANK[flooredLevel] || 0) < URGENCY_RANK.stat
339
+ const patternCheck = clinicalPatternFloorLive() && runtime.patientCode && flooredLevel === 'routine'
321
340
  ? await clinicalPatternFloor({ code: runtime.patientCode, turnId: runtime.turnId, details, justification: args?.urgency_justification })
322
341
  : null;
323
342
  const patternFloor = patternCheck?.floor || null;
324
343
  const raisedByPattern = Boolean(patternFloor) && (URGENCY_RANK[patternFloor.level] || 0) > (URGENCY_RANK[flooredLevel] || 0);
325
344
  const urgencyLevel = raisedByPattern ? patternFloor.level : flooredLevel;
326
345
  const raisesOpen = !anchor || (URGENCY_RANK[urgencyLevel] || 0) > (URGENCY_RANK[anchor.urgencyLevel] || 0);
346
+ // Recorded on the alarm now, not only with the emergency row, so a floor-raised level is never
347
+ // treated by the review as the level the bot asked for.
348
+ if (review && (raisedByGate || raisedByPattern)) await setAlarmAppliedLevel({ reviewId: review._id, alarmId, appliedLevel: urgencyLevel });
327
349
 
328
350
  trace.setSafetyDecision({ ...(trace.safetyDecision || {}), escalationKind: 'medical_urgent' });
329
351
  trace.setSignals({
@@ -393,7 +415,7 @@ async function handler(args, context = {}) {
393
415
  documentation: [
394
416
  keptOpenLevel ? `Actualización: el bot sugirió ${requestedLevel}; se mantiene ${agentLevel}.` : '',
395
417
  raisedByGate ? `Piso del triaje: el gate de seguridad pidió acción en ${gateFloor.maxActionTimeHours ?? '<24'} h (${gateFloor.escalationRoute}); se aplica ${flooredLevel} aunque el bot sugirió ${agentLevel}.` : '',
396
- raisedByPattern ? `Piso clínico (${patternFloor.pattern}): ${patternFloor.reason || 'patrón de riesgo cumplido'}; se aplica ${urgencyLevel} en lugar de ${flooredLevel}${raisedByGate ? ' (nivel ya elevado por el triaje)' : ''}.` : '',
418
+ raisedByPattern ? `Piso clínico (${patternFloor.pattern}): ${patternFloor.reason || 'patrón de riesgo cumplido'}; se aplica ${urgencyLevel} en lugar de ${flooredLevel}.` : '',
397
419
  args?.urgency_justification || '',
398
420
  details.evidence_quote ? `Evidencia: «${details.evidence_quote}»` : '',
399
421
  assessmentNote(clinicalAssessment),
@@ -12,7 +12,7 @@ const MAX_PATIENT_SILENCE_MIN = 1380;
12
12
 
13
13
  const definition = {
14
14
  name: 'setContingencyPlan',
15
- description: `**Does:** Manages the contingency safety net guarding an open case or cluster, selected via \`action\`. A net is a single promise: if the patient goes quiet, you write to them again.\n- \`arm\` (default): arms a new net — a CarePlan anchor plus the follow-up check-in that goes out to the patient after true silence.\n- \`resolve\`: stands an active net down because this turn's conversation addressed the guarded concern, or it is no longer clinically relevant. Requires \`plan_id\` + \`resolution_reasoning\`.\n- \`rearm\`: replaces the target's active net with this new definition (fresh silence window anchored now) — same required fields as \`arm\`. Use when new information changes the concern, window, or message.\n\n**Required inputs:** \`arm\`/\`rearm\`: \`concern\`, \`awaiting_characterization\`; at least one of \`related_case_id\` / \`related_cluster_id\`; \`patient_followup_reminder\` \`${STEP_SHAPE}\` (message + a positive \`fires_after_silence_minutes\` <= ${MAX_PATIENT_SILENCE_MIN}, plus \`window_reasoning\`: one sentence on why that wait). \`resolve\`: \`plan_id\` + \`resolution_reasoning\`.\n\n**When to call:** \`arm\` when, read against the symptom's CTCAE grade scale, a datum is still missing that could put the case at a grade above your current read. If everything needed to settle the severity is already known, do not arm. The rubric is the test, not how alarming the symptom sounds.\n- Missing information could move it from G1 to G2/G3 → arm, and wait for exactly that datum.\n- Everything needed to rule out the higher grades is already known → do not arm.\n- Serious AND fully assessed → escalate. A finished assessment needs a person, not a check-in.\n\nFind the gap in the \`grade_scale\` you graded against: which clause of the next grade up can you neither confirm nor rule out? Name that datum in \`awaiting_characterization\`, concrete enough that the next turn can tell whether their message addressed it. It is an answer the patient still owes about the symptom as it stands now — what qualifies it is that it moves the grade, not the form it takes. A pending detail that cannot change the grade (an administrative confirmation, a name, an appointment) is not a reason to arm. Neither is a watch that starts after the patient already gave that datum — whether the symptom comes back, crosses a threshold you named, or eases with what you recommended: that is continuity, not uncertainty, so schedule a \`seguimiento\` with \`schedulePatientReminder\` instead, and do not re-arm a net you just resolved to cover it. Set \`resolves_on\` to match: \`reply\` for an answer they owe, \`observation\` for an event their next message may not carry.\n\nWaiting on the care team does NOT satisfy this test — a non-routine escalation normally arms its own net, so team follow-up is not this tool's job. A \`routine\` escalation does not — it routes to the team's ticket lane and leaves no net, so on those turns the ceiling test decides on its own merits. Do not condition it on predicting whether the patient will go quiet: that cannot be known, and a net they turn out not to need never reaches them — it steps aside every time they write. \`resolve\` when the patient's message answered what the net was waiting to observe; \`rearm\` when the net's definition went stale. Resolve a net only when its awaited datum arrived or the concern it guards was addressed. A care-team indication to book or do a visit or test does not by itself address it: if the net still awaits a grade-changing observation, keep the net as it is and also schedule the seguimiento about the visit or test — an open net does not hold it back. When a net is resolved and the team gave an indication, what remains open is the indication: schedule a \`seguimiento\` with \`schedulePatientReminder\` (\`utility_basis: agreed_action\`) at 24–48 h instead of treating the topic as closed — for a medication or measure, to learn whether it works; for a visit or test, to learn whether it was booked or done and when (ask about the result later, once it has happened).\n\n**When NOT to call:** \`arm\` on a target that already has an active plan (fails hard — use \`resolve\` or \`rearm\`) or whose case/cluster is closed/dissolved; \`resolve\` while the concern is still unobserved (closing the case retires its net automatically). This tool does NOT notify the care team — to reach a human, use the escalation tools.\n\n**Returns:** \`arm\`/\`rearm\` → \`{plan_id}\` (\`rearm\` adds \`superseded_plan_ids\` when it replaced a net). \`resolve\` → \`{plan_id}\`, with \`already_resolved: true\` when the net was retired earlier — an idempotent success, not an error. Fails hard with \`case_not_found_or_wrong_patient\` / \`cluster_not_found_or_wrong_patient\`, \`target_not_open\`, \`active_plan_already_exists_for_case\` / \`_for_cluster\` (arm only), \`plan_not_found_or_wrong_patient\`, \`store_failed_retry_next_turn\`, or \`stand_down_failed_retry_next_turn\`.\n\n**Side effects:** records the action on the turn trace; writes the FHIR CarePlan + patient CommunicationRequest + Provenance; arms or deactivates the dispatch row — the check-in goes out over WhatsApp only if the patient stayed silent through its window, and is pushed back each time they write. Nets also stand down when their case closes or cluster dissolves, and expire on their own after a bounded multiple of the check-in window.`,
15
+ description: `**Does:** Manages the contingency safety net guarding an open case or cluster, selected via \`action\`. A net is a single promise: if the patient goes quiet, you write to them again.\n- \`arm\` (default): arms a new net — a CarePlan anchor plus the follow-up check-in that goes out to the patient after true silence.\n- \`resolve\`: stands an active net down because this turn's conversation addressed the guarded concern, or it is no longer clinically relevant. Requires \`plan_id\` + \`resolution_reasoning\`.\n- \`rearm\`: replaces the target's active net with this new definition (fresh silence window anchored now) — same required fields as \`arm\`. Use when new information changes the concern, window, or message.\n\n**Required inputs:** \`arm\`/\`rearm\`: \`concern\`, \`awaiting_characterization\`; at least one of \`related_case_id\` / \`related_cluster_id\`; \`patient_followup_reminder\` \`${STEP_SHAPE}\` (message + a positive \`fires_after_silence_minutes\` <= ${MAX_PATIENT_SILENCE_MIN}, plus \`window_reasoning\`: one sentence on why that wait). \`resolve\`: \`plan_id\` + \`resolution_reasoning\`.\n\n**When to call:** \`arm\` when, read against the symptom's CTCAE grade scale, a datum is still missing that could put the case at a grade above your current read. If everything needed to settle the severity is already known, do not arm. The rubric is the test, not how alarming the symptom sounds.\n- Missing information could move it from G1 to G2/G3 → arm, and wait for exactly that datum.\n- Everything needed to rule out the higher grades is already known → do not arm.\n- Serious AND fully assessed → escalate. A finished assessment needs a person, not a check-in.\n\nFind the gap in the \`grade_scale\` you graded against: which clause of the next grade up can you neither confirm nor rule out? Name that datum in \`awaiting_characterization\`, concrete enough that the next turn can tell whether their message addressed it. It is an answer the patient still owes about the symptom as it stands now — what qualifies it is that it moves the grade, not the form it takes. A pending detail that cannot change the grade (an administrative confirmation, a name, an appointment) is not a reason to arm. Neither is a watch that starts after the patient already gave that datum — whether the symptom comes back, crosses a threshold you named, or eases with what you recommended: that is continuity, not uncertainty, so schedule a \`seguimiento\` with \`schedulePatientReminder\` instead, and do not re-arm a net you just resolved to cover it. Set \`resolves_on\` to match: \`reply\` for an answer they owe, \`observation\` for an event their next message may not carry.\n\nWaiting on the care team does NOT satisfy this test — a non-routine escalation normally arms its own net, so team follow-up is not this tool's job. A \`routine\` escalation does not — it routes to the team's ticket lane and leaves no net, so on those turns the ceiling test decides on its own merits. Do not condition it on predicting whether the patient will go quiet: that cannot be known, and each message they send pushes the check-in back, but it still goes out once they fall silent unless you resolve the net — so resolve it as soon as they give what it waits for. \`resolve\` when the patient's message answered what the net was waiting to observe; \`rearm\` when the net's definition went stale. Resolve a net only when its awaited datum arrived or the concern it guards was addressed. A care-team indication to book or do a visit or test does not by itself address it: if the net still awaits a grade-changing observation, keep the net as it is and also schedule the seguimiento about the visit or test — an open net does not hold it back. When a net is resolved and the team gave an indication, what remains open is the indication: schedule a \`seguimiento\` with \`schedulePatientReminder\` (\`utility_basis: agreed_action\`) at 24–48 h instead of treating the topic as closed — for a medication or measure, to learn whether it works; for a visit or test, to learn whether it was booked or done and when (ask about the result later, once it has happened).\n\n**When NOT to call:** \`arm\` on a target that already has an active plan (fails hard — use \`resolve\` or \`rearm\`) or whose case/cluster is closed/dissolved; \`resolve\` while the concern is still unobserved (closing the case retires its net automatically). This tool does NOT notify the care team — to reach a human, use the escalation tools.\n\n**Returns:** \`arm\`/\`rearm\` → \`{plan_id}\` (\`rearm\` adds \`superseded_plan_ids\` when it replaced a net). \`resolve\` → \`{plan_id}\`, with \`already_resolved: true\` when the net was retired earlier — an idempotent success, not an error. Fails hard with \`case_not_found_or_wrong_patient\` / \`cluster_not_found_or_wrong_patient\`, \`target_not_open\`, \`active_plan_already_exists_for_case\` / \`_for_cluster\` (arm only), \`plan_not_found_or_wrong_patient\`, \`store_failed_retry_next_turn\`, or \`stand_down_failed_retry_next_turn\`.\n\n**Side effects:** records the action on the turn trace; writes the FHIR CarePlan + patient CommunicationRequest + Provenance; arms or deactivates the dispatch row — the check-in goes out over WhatsApp only if the patient stayed silent through its window, and is pushed back each time they write. Nets also stand down when their case closes or cluster dissolves, and expire on their own after a bounded multiple of the check-in window.`,
16
16
  strict: false,
17
17
  parameters: {
18
18
  type: 'object',
@@ -46,7 +46,7 @@ const definition = {
46
46
  resolves_on: {
47
47
  type: 'string',
48
48
  enum: Object.values(RESOLVES_ON),
49
- description: 'How the net stands down. \'reply\' (default): the patient\'s next message retires it, which is right when what you await is an answer they owe. \'observation\': the net keeps waiting through messages that do not carry it, and stands down only when you `resolve` it, its target closes, or it expires — use it when what you await is an event their next message may not contain, such as the result of something you asked them to do, or a threshold you named.',
49
+ description: 'How the net stands down. \'reply\' (default): what you await is an answer they owe — resolve the net when they give it; their other messages only push the check-in back. \'observation\': the net keeps waiting through messages that do not carry it, and stands down only when you `resolve` it, its target closes, or it expires — use it when what you await is an event their next message may not contain, such as the result of something you asked them to do, or a threshold you named.',
50
50
  },
51
51
  related_case_id: {
52
52
  type: 'string',
@@ -58,7 +58,7 @@ const definition = {
58
58
  },
59
59
  patient_followup_reminder: {
60
60
  type: 'object',
61
- description: `Required. ${STEP_SHAPE}: the check-in sent to the patient — message (string, in the patient's voice and language) + fires_after_silence_minutes (> 0 and <= ${MAX_PATIENT_SILENCE_MIN}, ~23h, so it stays inside the WhatsApp session window) + window_reasoning: ONE sentence on why that wait — what you expect to happen in it, and why waiting longer would be unsafe or shorter would be noise. A check-in never goes out between 21:00 and 09:00 patient-local time (08:00–09:00 is when the daily symptom forms arrive) — a window landing in those hours is held until 09:00, so pick the window the concern needs and do not shorten it to dodge the small hours. If a concern cannot wait until morning, it needs an escalation, not a net. priority and action_requested are optional.`,
61
+ description: `Required. ${STEP_SHAPE}: the check-in sent to the patient — message (string, in the patient's voice and language, about the symptom only: never ask whether the care team contacted them or gave an indication — that is not yours to ask, and it may arrive after the team already did) + fires_after_silence_minutes (> 0 and <= ${MAX_PATIENT_SILENCE_MIN}, ~23h, so it stays inside the WhatsApp session window) + window_reasoning: ONE sentence on why that wait — what you expect to happen in it, and why waiting longer would be unsafe or shorter would be noise. A check-in never goes out between 21:00 and 09:00 patient-local time (08:00–09:00 is when the daily symptom forms arrive) — a window landing in those hours is held until 09:00, so pick the window the concern needs and do not shorten it to dodge the small hours. If a concern cannot wait until morning, it needs an escalation, not a net. priority and action_requested are optional.`,
62
62
  },
63
63
  },
64
64
  required: ['action'],
@@ -19,6 +19,7 @@ const Webinars_Leads_ID = runtimeConfig.get('AIRTABLE_WEBINARS_LEADS_ID') || 'ap
19
19
  const Product_ID = runtimeConfig.get('AIRTABLE_PRODUCT_ID') || 'appu2YDW2pKDYLL5H';
20
20
  const Dashboard_ID = runtimeConfig.get('AIRTABLE_DASHBOARD_ID') || 'appg9YUNlfIC82MzR';
21
21
  const Estado_General_ID = runtimeConfig.get('AIRTABLE_ESTADO_GENERAL_ID') || 'appXb7LKgAuZ1d1KI';
22
+ const Quimio_Ops_ID = runtimeConfig.get('AIRTABLE_QUIMIO_OPS_ID') || 'appK0VzrMDcVGyuE9';
22
23
 
23
24
  const DEFAULT_REQUEST_TIMEOUT_MS = 60000;
24
25
 
@@ -78,6 +79,7 @@ module.exports = {
78
79
  Product_ID,
79
80
  Dashboard_ID,
80
81
  Estado_General_ID,
82
+ Quimio_Ops_ID,
81
83
  getBase: (baseKeyOrId = runtimeConfig.get('AIRTABLE_BASE_ID')) => {
82
84
  if (!airtable) {
83
85
  throw new Error('Airtable not configured. Please set AIRTABLE_API_KEY environment variable.');
@@ -22,6 +22,7 @@ const {
22
22
  syncEscalationReviewCase,
23
23
  } = require('../services/escalationReviewService');
24
24
  const { listReviewBoard } = require('../services/reviewBoardService');
25
+ const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
25
26
 
26
27
  const respondWithError = (res, error, action, context) => {
27
28
  logger.error(`Error ${action}:`, {
@@ -32,6 +33,8 @@ const respondWithError = (res, error, action, context) => {
32
33
  res.status(error.statusCode || 500).json({ success: false, error: error.message });
33
34
  };
34
35
 
36
+ const withCaseStatus = (review) => (review ? { ...review, caseStatus: CASE_STATUS_BY_REVIEW_STATUS[review.status] ?? null } : review);
37
+
35
38
  const openEscalationReviewController = async (req, res) => {
36
39
  try {
37
40
  const { code, patientCaseRecordId = null, patientCaseRecordIds = null, triggeredBy } = req.body || {};
@@ -42,7 +45,7 @@ const openEscalationReviewController = async (req, res) => {
42
45
  openedBy: triggeredBy,
43
46
  requestId: req.requestId,
44
47
  });
45
- res.status(created ? 201 : 200).json({ success: true, review });
48
+ res.status(created ? 201 : 200).json({ success: true, review: withCaseStatus(review) });
46
49
  } catch (error) {
47
50
  respondWithError(res, error, 'opening escalation review', { code: redactDirectIdentifiers(String(req.body?.code || '')) });
48
51
  }
@@ -51,7 +54,7 @@ const openEscalationReviewController = async (req, res) => {
51
54
  const getEscalationReviewController = async (req, res) => {
52
55
  try {
53
56
  const { review, isApprover, responseDeadline } = await getEscalationReviewById({ id: req.params.id, requestedBy: req.query.requestedBy });
54
- res.status(200).json({ success: true, review, isApprover, responseDeadline });
57
+ res.status(200).json({ success: true, review: withCaseStatus(review), isApprover, responseDeadline });
55
58
  } catch (error) {
56
59
  respondWithError(res, error, 'reading escalation review', { reviewId: req.params?.id });
57
60
  }
@@ -69,7 +72,7 @@ const getReviewTimelineController = async (req, res) => {
69
72
  const listEscalationReviewsController = async (req, res) => {
70
73
  try {
71
74
  const reviews = await listEscalationReviews({ code: req.params.code });
72
- res.status(200).json({ success: true, reviews });
75
+ res.status(200).json({ success: true, reviews: reviews.map(withCaseStatus) });
73
76
  } catch (error) {
74
77
  respondWithError(res, error, 'listing escalation reviews', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
75
78
  }
@@ -88,7 +91,7 @@ const setEscalationReviewCasesController = async (req, res) => {
88
91
  try {
89
92
  const { patientCaseRecordIds, triggeredBy } = req.body || {};
90
93
  const review = await setReviewCases({ id: req.params.id, patientCaseRecordIds, updatedBy: triggeredBy, requestId: req.requestId });
91
- res.status(200).json({ success: true, review });
94
+ res.status(200).json({ success: true, review: withCaseStatus(review) });
92
95
  } catch (error) {
93
96
  respondWithError(res, error, 'selecting escalation review cases', { reviewId: req.params?.id });
94
97
  }
@@ -98,7 +101,7 @@ const addEscalationReviewCallLogController = async (req, res) => {
98
101
  try {
99
102
  const { outcome, notes, calledAt, triggeredBy } = req.body || {};
100
103
  const review = await addCallLog({ id: req.params.id, outcome, notes, calledAt, loggedBy: triggeredBy, requestId: req.requestId });
101
- res.status(201).json({ success: true, review });
104
+ res.status(201).json({ success: true, review: withCaseStatus(review) });
102
105
  } catch (error) {
103
106
  respondWithError(res, error, 'logging escalation review call', { reviewId: req.params?.id });
104
107
  }
@@ -110,7 +113,7 @@ const confirmEscalationReviewNoteFactsController = async (req, res) => {
110
113
  const review = await confirmNoteFacts({
111
114
  id: req.params.id, accepted, declined, confirmedBy: triggeredBy, requestId: req.requestId,
112
115
  });
113
- res.status(200).json({ success: true, review });
116
+ res.status(200).json({ success: true, review: withCaseStatus(review) });
114
117
  } catch (error) {
115
118
  respondWithError(res, error, 'confirming escalation review note facts', { reviewId: req.params?.id });
116
119
  }
@@ -130,7 +133,7 @@ const requestEscalationReviewDraftController = async (req, res) => {
130
133
  try {
131
134
  const { triggeredBy } = req.body || {};
132
135
  const review = await requestBotDraft({ id: req.params.id, requestedBy: triggeredBy, requestId: req.requestId });
133
- res.status(202).json({ success: true, review });
136
+ res.status(202).json({ success: true, review: withCaseStatus(review) });
134
137
  } catch (error) {
135
138
  respondWithError(res, error, 'requesting an escalation review draft', { reviewId: req.params?.id });
136
139
  }
@@ -150,7 +153,7 @@ const addEscalationReviewDraftController = async (req, res) => {
150
153
  try {
151
154
  const { doctorText, patientMessage, triggeredBy } = req.body || {};
152
155
  const review = await addDraft({ id: req.params.id, doctorText, patientMessage, writtenBy: triggeredBy, requestId: req.requestId });
153
- res.status(201).json({ success: true, review });
156
+ res.status(201).json({ success: true, review: withCaseStatus(review) });
154
157
  } catch (error) {
155
158
  respondWithError(res, error, 'saving escalation review draft', { reviewId: req.params?.id });
156
159
  }
@@ -160,7 +163,7 @@ const handOffEscalationReviewController = async (req, res) => {
160
163
  try {
161
164
  const { mode, physicianEmail = null, triggeredBy } = req.body || {};
162
165
  const { review, caseMirror, caseMirrors } = await handOffToDoctor({ id: req.params.id, mode, physicianEmail, sentBy: triggeredBy, requestId: req.requestId });
163
- res.status(201).json({ success: true, review, caseMirror, caseMirrors });
166
+ res.status(201).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
164
167
  } catch (error) {
165
168
  respondWithError(res, error, 'handing escalation review to doctor', { reviewId: req.params?.id });
166
169
  }
@@ -192,7 +195,7 @@ const recordEscalationReviewDecisionController = async (req, res) => {
192
195
  recordedBy: triggeredBy,
193
196
  requestId: req.requestId,
194
197
  });
195
- res.status(201).json({ success: true, review });
198
+ res.status(201).json({ success: true, review: withCaseStatus(review) });
196
199
  } catch (error) {
197
200
  respondWithError(res, error, 'recording escalation review decision', { reviewId: req.params?.id });
198
201
  }
@@ -202,7 +205,7 @@ const sendEscalationReviewIndicationsController = async (req, res) => {
202
205
  try {
203
206
  const { outsideWindowRoute = null, triggeredBy } = req.body || {};
204
207
  const { review, caseMirror, caseMirrors } = await sendApprovedIndications({ id: req.params.id, outsideWindowRoute, sentBy: triggeredBy, requestId: req.requestId });
205
- res.status(201).json({ success: true, review, caseMirror, caseMirrors });
208
+ res.status(201).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
206
209
  } catch (error) {
207
210
  respondWithError(res, error, 'sending escalation review indications', { reviewId: req.params?.id });
208
211
  }
@@ -218,7 +221,7 @@ const closeEscalationReviewController = async (req, res) => {
218
221
  interruptionNotes,
219
222
  requestId: req.requestId,
220
223
  });
221
- res.status(200).json({ success: true, review, caseMirror, caseMirrors });
224
+ res.status(200).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
222
225
  } catch (error) {
223
226
  respondWithError(res, error, 'closing escalation review', { reviewId: req.params?.id });
224
227
  }
@@ -234,7 +237,7 @@ const reclassifyEscalationReviewUrgencyController = async (req, res) => {
234
237
  reclassifiedBy: triggeredBy,
235
238
  requestId: req.requestId,
236
239
  });
237
- res.status(200).json({ success: true, review, responseDeadline });
240
+ res.status(200).json({ success: true, review: withCaseStatus(review), responseDeadline });
238
241
  } catch (error) {
239
242
  respondWithError(res, error, 'reclassifying escalation review urgency', { reviewId: req.params?.id });
240
243
  }
@@ -249,7 +252,7 @@ const cancelEscalationReviewController = async (req, res) => {
249
252
  reason,
250
253
  requestId: req.requestId,
251
254
  });
252
- res.status(200).json({ success: true, review, caseMirror, caseMirrors });
255
+ res.status(200).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
253
256
  } catch (error) {
254
257
  respondWithError(res, error, 'cancelling escalation review', { reviewId: req.params?.id });
255
258
  }
@@ -260,10 +263,10 @@ const syncEscalationReviewCaseController = async (req, res) => {
260
263
  const { triggeredBy } = req.body || {};
261
264
  const { review, caseMirror, caseMirrors } = await syncEscalationReviewCase({ id: req.params.id, syncedBy: triggeredBy, requestId: req.requestId });
262
265
  if (caseMirror === 'failed' || caseMirror === 'partial') {
263
- res.status(502).json({ success: false, error: 'The patient case could not be updated', review, caseMirror, caseMirrors });
266
+ res.status(502).json({ success: false, error: 'The patient case could not be updated', review: withCaseStatus(review), caseMirror, caseMirrors });
264
267
  return;
265
268
  }
266
- res.status(200).json({ success: true, review, caseMirror, caseMirrors });
269
+ res.status(200).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
267
270
  } catch (error) {
268
271
  respondWithError(res, error, 'syncing escalation review case', { reviewId: req.params?.id });
269
272
  }
@@ -33,12 +33,12 @@ const { beginInstruction, endInstruction } = require('../services/instructionInF
33
33
  const { QueueReconciliationService } = require('../services/queueReconciliationService');
34
34
  const { releaseHeldMessages, sweepHeldMessages } = require('../services/heldMessageService');
35
35
 
36
- const { BatchingManager } = require('../core/BatchingManager');
36
+ const { BatchingManager, DrainingError } = require('../core/BatchingManager');
37
37
  const { ProcessingPipeline } = require('../core/ProcessingPipeline');
38
38
  const { preProcessMessages, configureOpenAIProvider, AssistantProcessor, TURN_KIND } = require('../clinical');
39
39
  const { deliveryOutcome } = require('../clinical/AssistantProcessor');
40
40
  const { UNASSIGNED, alertOpsForClaimedMessage, coverIfUnassigned, coverUnansweredPatient } = require('../clinical/services/pausedSafetyNetService');
41
- const { buildOutreachCarrier } = require('../clinical/services/outreachCarrierService');
41
+ const { buildOutreachCarrier, validateAgentText } = require('../clinical/services/outreachCarrierService');
42
42
  const { routineOutreachCollisionReason, isWithinTriageProtectionWindow } = require('../clinical/services/outreachSweepService');
43
43
  const {
44
44
  readPendingReminderForPatient,
@@ -830,7 +830,13 @@ class NexusMessaging {
830
830
  }, shouldContinue, runId);
831
831
  }
832
832
 
833
- async processInstruction(code, instruction, role = 'developer', { triggeredBy } = {}) {
833
+ /*
834
+ * `beforeRun`, when given, is asked under the chat lock right before the turn (and before every retry);
835
+ * a truthy reason vetoes the turn. Such a gated instruction never rides along in another instruction's
836
+ * batch, and is marked processed when vetoed or refused by a draining instance, so it can only ever
837
+ * run behind its own gate.
838
+ */
839
+ async processInstruction(code, instruction, role = 'developer', { triggeredBy, beforeRun = null } = {}) {
834
840
  const receivedAt = Date.now();
835
841
  const messageData = {
836
842
  pushName: 'Instruction',
@@ -840,33 +846,58 @@ class NexusMessaging {
840
846
  fromMe: true,
841
847
  processed: false,
842
848
  origin: 'instruction',
843
- raw: { role },
849
+ raw: beforeRun ? { role, gated: true } : { role },
844
850
  triggeredBy: triggeredBy || null,
845
851
  silent: true,
846
852
  };
847
853
 
848
854
  beginInstruction(code);
849
855
  try {
850
- await this.phiProcessor.inData(
856
+ return await this.phiProcessor.inData(
851
857
  messageData,
852
858
  this._saveMessageFn,
853
859
  async ({ body, _id }) => {
854
860
  if (this.batchingConfig.instructionSettleMs > 0 && !this.batchingManager.isDraining()) {
855
861
  await new Promise(resolve => setTimeout(resolve, this.batchingConfig.instructionSettleMs));
856
862
  }
863
+ const markOwnProcessed = async () => {
864
+ if (!_id) return;
865
+ try {
866
+ await updateMessage({ _id }, { $set: { processed: true } });
867
+ } catch (err) {
868
+ logger.error('[processInstruction] Could not mark a gated instruction processed', { error: err.message, code });
869
+ }
870
+ };
857
871
  let batchIds = [];
858
872
  let outcome = null;
859
873
  let runId = null;
874
+ let gate = null;
875
+ let alreadyAnswered = false;
860
876
  const answerPending = () => {
861
877
  batchIds = [];
862
878
  outcome = null;
863
879
  runId = null;
880
+ gate = null;
881
+ alreadyAnswered = false;
864
882
  return this._executeWithPipeline(code, 'instruction', 'queue',
865
883
  async (preProcessResult, shouldContinue, currentRunId) => {
866
884
  runId = currentRunId;
885
+ if (beforeRun) {
886
+ try {
887
+ const reason = await beforeRun();
888
+ if (reason) gate = { outcome: 'gated', reason };
889
+ } catch (err) {
890
+ gate = { outcome: 'gate_error', error: err.message };
891
+ }
892
+ if (gate) {
893
+ await markOwnProcessed();
894
+ return null;
895
+ }
896
+ }
867
897
  const batch = await this._pendingInstructionBatch(code, _id, body, receivedAt);
868
898
  if (!batch.length) {
869
899
  logger.info('[processInstruction] Instruction already answered by an earlier run', { code, runId });
900
+ alreadyAnswered = true;
870
901
  return null;
871
902
  }
872
903
  batchIds = batch.map(m => m._id).filter(Boolean);
@@ -899,15 +930,26 @@ class NexusMessaging {
899
930
  const needsAnotherTurn = () => batchIds.length > 0
900
931
  && ((outcome === null && this.batchingManager.isAbandoned(runId)) || outcome === 'known_not_sent');
901
932
 
902
- let runResult = await answerPending();
933
+ const answer = async () => {
934
+ try {
935
+ return await answerPending();
936
+ } catch (err) {
937
+ if (beforeRun && err instanceof DrainingError) await markOwnProcessed();
938
+ throw err;
939
+ }
940
+ };
941
+ await answer();
903
942
  if (needsAnotherTurn()) {
904
943
  logger.warn('[processInstruction] Instruction reply was not sent; queueing one more turn', { code, outcome });
905
- runResult = await answerPending();
944
+ await answer();
906
945
  }
907
946
  if (batchIds.length && outcome !== 'sent' && outcome !== 'unknown') {
908
947
  logger.error('[processInstruction] Instruction left unanswered', { code, outcome, instructionIds: batchIds.map(String) });
909
948
  }
910
- return runResult;
949
+ // Only the send outcome goes back: the turn's output was already delivered, and handing it to
950
+ // the caller would invite a second send.
951
+ if (gate) return gate;
952
+ return { outcome: outcome === null && alreadyAnswered ? 'already_answered' : outcome };
911
953
  },
912
954
  );
913
955
  } finally {
@@ -923,7 +965,7 @@ class NexusMessaging {
923
965
  numero: code,
924
966
  origin: 'instruction',
925
967
  message_id: /^instruction_/,
926
- $or: [{ _id: ownId }, { processed: false, createdAt: { $gte: new Date(receivedAt - PENDING_INSTRUCTION_WINDOW_MS) } }],
968
+ $or: [{ _id: ownId }, { processed: false, 'raw.gated': { $ne: true }, createdAt: { $gte: new Date(receivedAt - PENDING_INSTRUCTION_WINDOW_MS) } }],
927
969
  },
928
970
  { sort: { _id: 1 }, select: '_id body processed' },
929
971
  );
@@ -1037,6 +1079,14 @@ class NexusMessaging {
1037
1079
  }
1038
1080
  const accepted = Boolean(runResult.output) && delivery?.success === true && delivery?.deferred !== true;
1039
1081
  const delivered = ['delivered', 'read'].includes(String(delivery?.status || '').toLowerCase());
1082
+ let carrierRejection = null;
1083
+ if (dryRun && decision.decision === 'write') {
1084
+ try {
1085
+ validateAgentText(runResult.output, firstName);
1086
+ } catch (error) {
1087
+ carrierRejection = error.message;
1088
+ }
1089
+ }
1040
1090
  if (!dryRun && (decision.decision === 'write') !== accepted) {
1041
1091
  logger.warn('[processOutreach] decision and delivery disagree', {
1042
1092
  code, decision: decision.decision, accepted, status: delivery?.status || null,
@@ -1049,6 +1099,7 @@ class NexusMessaging {
1049
1099
  holdReason: decision.holdReason || null,
1050
1100
  nextCheckAt: decision.nextCheckAt || null,
1051
1101
  draft: dryRun ? (runResult.output || '') : null,
1102
+ carrierRejection,
1052
1103
  accepted,
1053
1104
  delivered,
1054
1105
  deferred: Boolean(delivery?.deferred),
@@ -0,0 +1,31 @@
1
+ const CASE = (status, businessStatus, label) => ({ status, businessStatus, label });
2
+
3
+ const POR_REVISAR = CASE('requested', 'por-revisar', 'Por revisar');
4
+ const EN_EVALUACION = CASE('in-progress', 'en-evaluacion', 'En evaluación');
5
+ const CON_MEDICO = CASE('in-progress', 'con-medico', 'Con el médico');
6
+ const POR_ENVIAR = CASE('in-progress', 'indicacion-por-enviar', 'Indicación por enviar');
7
+
8
+ const CASE_STATUS_BY_REVIEW_STATUS = Object.freeze({
9
+ open: POR_REVISAR,
10
+ documenting: EN_EVALUACION,
11
+ draft_ready: EN_EVALUACION,
12
+ returned: EN_EVALUACION,
13
+ handing_off: CON_MEDICO,
14
+ awaiting_doctor: CON_MEDICO,
15
+ approved: POR_ENVIAR,
16
+ sending: POR_ENVIAR,
17
+ needs_intervention: CASE('in-progress', 'requiere-valoracion', 'Requiere valoración'),
18
+ indications_queued: CASE('on-hold', 'esperando-paciente', 'Esperando paciente'),
19
+ indications_sent: CASE('in-progress', 'indicaciones-dadas', 'Indicaciones dadas'),
20
+ monitoring: CASE('in-progress', 'en-vigilancia', 'En vigilancia'),
21
+ closed: CASE('completed', 'cerrado', 'Cerrado'),
22
+ cancelled: CASE('cancelled', 'no-requiere', 'No requiere'),
23
+ });
24
+
25
+ function caseStatusOf(reviewStatus) {
26
+ const caseStatus = CASE_STATUS_BY_REVIEW_STATUS[reviewStatus];
27
+ if (!caseStatus) throw new Error(`no case status for review status ${reviewStatus}`);
28
+ return caseStatus;
29
+ }
30
+
31
+ module.exports = { CASE_STATUS_BY_REVIEW_STATUS, caseStatusOf };
@@ -4,6 +4,9 @@ const MENTION_SLUG = 'clinical-mention';
4
4
  const RESULT_SLUG = 'patient-reported-result';
5
5
  const ESCALATION_SLUG = 'dispatched-escalation';
6
6
  const ESCALATION_KIND_SLUG = 'escalation-kind';
7
+ const ESCALATION_CASE_SLUG = 'escalation-case';
8
+ const ESCALATION_CASE_STATUS_SLUG = 'escalation-case-status';
9
+ const ESCALATION_DECISION_SLUG = 'escalation-decision';
7
10
  const REMINDER_SLUG = 'reminder';
8
11
  const REMINDER_KIND_SLUG = 'reminder-kind';
9
12
  const COMMUNICATION_CHANNEL_SLUG = 'communication-channel';
@@ -36,6 +39,9 @@ module.exports = {
36
39
  RESULT_SLUG,
37
40
  ESCALATION_SLUG,
38
41
  ESCALATION_KIND_SLUG,
42
+ ESCALATION_CASE_SLUG,
43
+ ESCALATION_CASE_STATUS_SLUG,
44
+ ESCALATION_DECISION_SLUG,
39
45
  REMINDER_SLUG,
40
46
  REMINDER_KIND_SLUG,
41
47
  COMMUNICATION_CHANNEL_SLUG,
package/lib/fhir/index.js CHANGED
@@ -15,7 +15,7 @@ const {
15
15
  recordRecommendationReview,
16
16
  } = require('./services/recommendationService');
17
17
  const { storeContingency, readContingencies } = require('./services/contingencyService');
18
- const { readDispatchedEscalations } = require('./services/escalationService');
18
+ const { readDispatchedEscalations, storeEscalationCase } = require('./services/escalationService');
19
19
  const { storeIntervention, readInterventions } = require('./services/interventionService');
20
20
  const { storeCluster, readClusters } = require('./services/clusterService');
21
21
  const { storeRoutingDecision, readRoutingDecisions } = require('./services/routingService');
@@ -70,6 +70,7 @@ module.exports = {
70
70
  storeContingency,
71
71
  readContingencies,
72
72
  readDispatchedEscalations,
73
+ storeEscalationCase,
73
74
  storeIntervention,
74
75
  readInterventions,
75
76
  storeCluster,
@@ -72,6 +72,7 @@ const MEDICATION_ADHERENCE = {
72
72
  finalizado: 'stopped', end: 'stopped', replaced: 'stopped',
73
73
  past: 'stopped', previous: 'stopped', historical: 'stopped', historico: 'stopped',
74
74
  'on-hold': 'on-hold', 'en pausa': 'on-hold', paused: 'on-hold',
75
+ planned: 'not-taking', planificado: 'not-taking', programado: 'not-taking',
75
76
  };
76
77
 
77
78
  const CONTEXT_RESOURCE_TYPES = [...new Set(Object.values(KIND_TO_RESOURCE_TYPE))];
@@ -42,7 +42,7 @@ class CommunicationRequest {
42
42
  identifier: [identifier(ESCALATION_SLUG, notify.eventId)],
43
43
  status: NOTIFY_STATUS_TO_CR_STATUS[notify.status],
44
44
  intent: 'plan',
45
- priority: SEVERITY_TO_PRIORITY[notify.severity] || 'routine',
45
+ priority: notify.priority || SEVERITY_TO_PRIORITY[notify.severity] || 'routine',
46
46
  category: [codeableConcept(notify.kind, { code: notify.kind, system: codeSystemUrl(ESCALATION_KIND_SLUG) })],
47
47
  subject: patientReference(notify.patientId),
48
48
  authoredOn: toIso(notify.createdAt),