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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -212,6 +212,20 @@ async function recordPausedThreadMessage({ code, text, alert = OPS_ALERTS.paused
212
212
  return written;
213
213
  }
214
214
 
215
+ const GROUP_MESSAGE_ID_FIELD = 'group_message_id';
216
+
217
+ // The id of the group message notifyEmergency posted for this row, so follow-ups reply to it; null when unknown.
218
+ async function readGroupMessageId(recordId, code) {
219
+ if (!/^rec[A-Za-z0-9]+$/.test(String(recordId ?? ''))) return null;
220
+ try {
221
+ const rows = await airtableService.getRecordByFilter(Monitoreo_ID, 'emergencies', `RECORD_ID() = '${recordId}'`, null, [GROUP_MESSAGE_ID_FIELD]);
222
+ return String(rows?.[0]?.[GROUP_MESSAGE_ID_FIELD] ?? '').trim() || null;
223
+ } catch (error) {
224
+ logger.warn('[clinicalAirtableService] The group message id could not be read; the follow-up goes out unthreaded', { code, recordId, error: error.message });
225
+ return null;
226
+ }
227
+ }
228
+
215
229
  async function readEmergencyRow(recordId, code) {
216
230
  try {
217
231
  const open = await airtableService.getRecordByFilter(Monitoreo_ID, 'emergencies', `RECORD_ID() = '${recordId}'`, null);
@@ -716,6 +730,7 @@ module.exports = {
716
730
  writeUnresolvedRequest,
717
731
  recordPausedThreadMessage,
718
732
  recordEmergency,
733
+ readGroupMessageId,
719
734
  recordClinicalIntake,
720
735
  recordReminder,
721
736
  hasPendingContingencyRow,
@@ -11,12 +11,16 @@ const { isShadowRun } = require('../helpers/shadowHelper');
11
11
  const PATIENT_CONTACT_WINDOW = { timeZone: 'America/Mexico_City', startHour: 8, endHour: 21 };
12
12
  // Net check-ins start an hour later: 08:00–09:00 is when the daily symptom forms reach patients.
13
13
  const CHECK_IN_WINDOW = { ...PATIENT_CONTACT_WINDOW, startHour: 9 };
14
+ // asap check-ins only hold 23:00–08:00: the case is still hot and someone may be awake.
15
+ const ASAP_CHECK_IN_WINDOW = { ...PATIENT_CONTACT_WINDOW, endHour: 23 };
14
16
  const MS_PER_MINUTE = 60 * 1000;
15
17
  const MS_PER_HOUR = 60 * MS_PER_MINUTE;
16
18
  const EXPIRY_WINDOW_MULTIPLIER = 6;
17
19
  const EXPIRY_FLOOR_MS = 48 * MS_PER_HOUR;
18
20
  const EXPIRY_CEILING_MS = 14 * 24 * MS_PER_HOUR;
19
- const ESCALATION_SILENCE_MINUTES = { stat: 120, asap: 180, urgent: 240 };
21
+ const ESCALATION_SILENCE_MINUTES = { stat: null, asap: 60, urgent: 240 };
22
+ // Nets armed before the change keep their level until they expire (stat 120, asap 180).
23
+ const LEGACY_ESCALATION_SILENCE_MINUTES = { stat: 120, asap: 180 };
20
24
  const OPEN_CEILING_SILENCE_MINUTES = 720;
21
25
  const OPEN_CEILING_ORIGIN = 'open_ceiling';
22
26
  const OPEN_CEILING_CHECK_IN = 'Hola, quería saber cómo sigues. ¿Cómo va lo que me contaste?';
@@ -33,14 +37,18 @@ function rawDueAt(createdAt, firesAfterSilenceMinutes) {
33
37
  return new Date(new Date(createdAt).getTime() + (firesAfterSilenceMinutes * MS_PER_MINUTE));
34
38
  }
35
39
 
36
- function dueAt(createdAt, firesAfterSilenceMinutes) {
40
+ function checkInWindowFor(urgencyLevel) {
41
+ return urgencyLevel === 'asap' ? ASAP_CHECK_IN_WINDOW : CHECK_IN_WINDOW;
42
+ }
43
+
44
+ function dueAt(createdAt, firesAfterSilenceMinutes, window = CHECK_IN_WINDOW) {
37
45
  const raw = rawDueAt(createdAt, firesAfterSilenceMinutes);
38
- return (clampToHourWindow(raw, CHECK_IN_WINDOW) || raw).toISOString();
46
+ return (clampToHourWindow(raw, window) || raw).toISOString();
39
47
  }
40
48
 
41
- function quietHoursShiftMinutes(createdAt, firesAfterSilenceMinutes) {
49
+ function quietHoursShiftMinutes(createdAt, firesAfterSilenceMinutes, window = CHECK_IN_WINDOW) {
42
50
  const raw = rawDueAt(createdAt, firesAfterSilenceMinutes);
43
- const clamped = clampToHourWindow(raw, CHECK_IN_WINDOW);
51
+ const clamped = clampToHourWindow(raw, window);
44
52
  if (!clamped) return 0;
45
53
  return Math.round((clamped.getTime() - raw.getTime()) / MS_PER_MINUTE);
46
54
  }
@@ -96,7 +104,7 @@ function computeExpiresAt(createdAt, firesAfterSilenceMinutes) {
96
104
  return new Date(new Date(createdAt).getTime() + clamped).toISOString();
97
105
  }
98
106
 
99
- function stampContingencyPlan({ trace, planId, relatedCaseId, relatedClusterId, concern, awaitingCharacterization, resolvesOn = RESOLVES_ON.REPLY, createdAt, firesAfterSilenceMinutes, windowReasoning = null, extra = null }) {
107
+ function stampContingencyPlan({ trace, planId, relatedCaseId, relatedClusterId, concern, awaitingCharacterization, resolvesOn = RESOLVES_ON.REPLY, createdAt, firesAfterSilenceMinutes, windowReasoning = null, extra = null, checkInWindow = CHECK_IN_WINDOW }) {
100
108
  const existing = Array.isArray(trace?.signals?.contingencyPlans) ? trace.signals.contingencyPlans : [];
101
109
  trace?.setSignals?.({
102
110
  contingencyPlans: [...existing, {
@@ -107,7 +115,7 @@ function stampContingencyPlan({ trace, planId, relatedCaseId, relatedClusterId,
107
115
  awaitingCharacterization,
108
116
  resolvesOn,
109
117
  patientFiresAfterSilenceMinutes: firesAfterSilenceMinutes,
110
- quietHoursShiftMinutes: quietHoursShiftMinutes(createdAt, firesAfterSilenceMinutes),
118
+ quietHoursShiftMinutes: quietHoursShiftMinutes(createdAt, firesAfterSilenceMinutes, checkInWindow),
111
119
  windowReasoning,
112
120
  ...(extra || {}),
113
121
  }],
@@ -241,7 +249,7 @@ function isCeilingNet(net) {
241
249
  return plan?.armedBy === ARMED_BY.OPEN_CEILING || plan?.creationReasoning === OPEN_CEILING_ORIGIN;
242
250
  }
243
251
 
244
- async function retireCeilingNets({ patientCode, trace, isLive, select, context }) {
252
+ async function retireNets({ patientCode, trace, isLive, select, context }) {
245
253
  if (isShadowRun()) return [];
246
254
  if (isLive && !isLive()) return [];
247
255
  const targets = select(await readActiveNets(patientCode));
@@ -259,7 +267,7 @@ async function retireCeilingNets({ patientCode, trace, isLive, select, context }
259
267
  });
260
268
  retired.push(net.carePlan.planId);
261
269
  } catch (error) {
262
- logger.warn(`[contingency] ceiling net not retired ${context}`, { patientCode, planId: net.carePlan.planId, error: error?.message, err: error });
270
+ logger.warn(`[contingency] net not retired ${context}`, { patientCode, planId: net.carePlan.planId, error: error?.message, err: error });
263
271
  }
264
272
  }
265
273
  return retired;
@@ -270,23 +278,39 @@ function orphanCeilingNets(active) {
270
278
  return ceiling.length === active.length ? [] : ceiling;
271
279
  }
272
280
 
273
- const sweepOrphanCeilingNets = ({ patientCode, trace, isLive }) => retireCeilingNets({
281
+ const sweepOrphanCeilingNets = ({ patientCode, trace, isLive }) => retireNets({
274
282
  patientCode, trace, isLive, select: orphanCeilingNets, context: 'while sweeping an orphan',
275
283
  });
276
284
 
277
- const supersedeForEscalation = ({ patientCode, trace, isLive }) => retireCeilingNets({
285
+ const supersedeForEscalation = ({ patientCode, trace, isLive }) => retireNets({
278
286
  patientCode, trace, isLive, select: (active) => active.filter(isCeilingNet), context: 'after the escalation armed',
279
287
  });
280
288
 
289
+ // A patient sent to urgencias gets no later check-in, neither the ceiling one nor one left by a lower escalation.
290
+ const supersedeForStat = ({ patientCode, trace, isLive }) => retireNets({
291
+ patientCode, trace, isLive, select: (active) => active.filter((net) => isCeilingNet(net) || net?.carePlan?.armedBy === ARMED_BY.ESCALATION), context: 'for a stat escalation',
292
+ });
293
+
281
294
  function escalationUrgencyOf(net) {
282
295
  if (net?.carePlan?.armedBy !== ARMED_BY.ESCALATION) return null;
283
296
  const silence = net?.patientReminder?.firesAfterSilenceMinutes;
284
- return Object.keys(ESCALATION_SILENCE_MINUTES).find((level) => ESCALATION_SILENCE_MINUTES[level] === silence) || null;
297
+ const levels = Object.keys(ESCALATION_SILENCE_MINUTES);
298
+ return levels.find((level) => ESCALATION_SILENCE_MINUTES[level] === silence)
299
+ || levels.find((level) => LEGACY_ESCALATION_SILENCE_MINUTES[level] === silence)
300
+ || null;
285
301
  }
286
302
 
287
303
  async function armEscalationNet({ patientCode, urgencyLevel, symptom, suspectedCondition = null, checkIn = null, trace = null, isLive = null }) {
304
+ if (!Object.hasOwn(ESCALATION_SILENCE_MINUTES, urgencyLevel)) return { armed: false, reason: 'urgency_not_covered' };
288
305
  const silence = ESCALATION_SILENCE_MINUTES[urgencyLevel];
289
- if (!silence) return { armed: false, reason: 'urgency_not_covered' };
306
+ // stat gets no check-in of its own; it only clears the check-ins already armed.
307
+ if (!silence) {
308
+ const superseded = await supersedeForStat({ patientCode, trace, isLive }).catch((error) => {
309
+ logger.warn('[contingency] check-ins not retired for a stat escalation', { patientCode, error: error?.message });
310
+ return [];
311
+ });
312
+ return { armed: false, reason: 'level_without_check_in', superseded };
313
+ }
290
314
 
291
315
  await sweepOrphanCeilingNets({ patientCode, trace, isLive });
292
316
  const target = await escalationNetTarget(patientCode, { stepsAside: isCeilingNet, touched: casesTouchedThisTurn(trace) });
@@ -325,6 +349,7 @@ async function armEscalationNet({ patientCode, urgencyLevel, symptom, suspectedC
325
349
  firesAfterSilenceMinutes: silence,
326
350
  windowReasoning: contingency.patientReminder.windowReasoning,
327
351
  extra: { armedBy: 'escalation', escalationUrgency: urgencyLevel },
352
+ checkInWindow: checkInWindowFor(urgencyLevel),
328
353
  });
329
354
 
330
355
  const out = await commitMachineNet({ patientCode, contingency, caseId: null, trace, isLive, planId, stepsAside: isCeilingNet });
@@ -343,7 +368,7 @@ async function armContingency({ contingency, patientCode, trace = null, isLive =
343
368
  isLive,
344
369
  actionType,
345
370
  reminderId: `${carePlan.planId}-patient`,
346
- reminderDateUtc: dueAt(carePlan.createdAt, patientReminder.firesAfterSilenceMinutes),
371
+ reminderDateUtc: dueAt(carePlan.createdAt, patientReminder.firesAfterSilenceMinutes, checkInWindowFor(escalationUrgencyOf(contingency))),
347
372
  reminderType: 'contingency',
348
373
  description: patientReminder.message,
349
374
  firesAfterSilenceMinutes: patientReminder.firesAfterSilenceMinutes,
@@ -468,4 +493,4 @@ async function applyContingencyEvent({ patientCode, planId, stage, event, at = n
468
493
  return { applied: true, status: next, teamStageArmed: handoff.armed, ...(handoff.armed ? {} : { teamStageReason: handoff.reason }) };
469
494
  }
470
495
 
471
- module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
496
+ module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW, ASAP_CHECK_IN_WINDOW };
@@ -7,7 +7,7 @@ const { evidenceQuoteAnchoring } = require('../helpers/evidenceAnchorHelper');
7
7
  const { dispatcherService } = require('../services/dispatcherService');
8
8
  const { armEscalationNet } = require('../services/contingencyDispatchService');
9
9
  const { recordEmergency, writeUnresolvedRequest } = require('../services/clinicalAirtableService');
10
- const { escalationAssessmentLive, escalationUpdateModeLive, feverPatientTimerLive } = require('../flags/escalationFlags');
10
+ const { escalationAssessmentLive, escalationPatientTimerLive, escalationUpdateModeLive, feverPatientTimerLive } = require('../flags/escalationFlags');
11
11
  const { alertWithoutEmergencyRow, attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
12
12
  const { URGENCY_RANK } = require('../../models/escalationReviewModel');
13
13
  const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
@@ -21,7 +21,7 @@ const FEVER_RULE = 'Fever that is `stat`: ≥38.0 °C within 8 weeks of cytotoxi
21
21
 
22
22
  const definition = {
23
23
  'name': 'reportMedicalEscalation',
24
- 'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; the payload is INTERNAL — the patient never sees it.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate without a further clarifying question: `asap` by default, `stat` if there is an acute deficit (sudden weakness of an arm, a leg or one side — even if they can still move it —, can\'t walk/stand, sphincter loss, bilateral leg weakness → possible cord compression) or any instability; an acute deficit is must-go.\n\n**When NOT to call:**\n- An open case in `turn_focus.team_cases` already covers this symptom at this level or higher. Read it before calling (load `getRouterContextBundle` first if you have not this turn). Call again, as an update, only for a new symptom, a higher grade, a new red flag, a detail that makes something more serious plausible, or a symptom that persists or worsens while the team has not answered; a characterization detail that changes none of these needs no call. Otherwise tell the patient where the case stands.\n- Unconfirmed/unspecific symptom — ask ONE characterization question via `DeliverPatientMessage` first.\n- Active mental-health crisis — use `reportCrisis`.\n- Patient shared lab/imaging/values/files — use `reportResultsReceived`.\n- Administrative / operative matter (appointments, insurance, authorizations, letters, transport, scheduling, out-of-scope request) or a non-clinical referral (psico-oncología, paliativos, non-oncology medical) — use `reportUnresolvedRequestv2`.\n- Twice in the same turn for the same episode — already committed; a later datum belongs to the same open escalation.\n\n**After the commit:** the escalation does not end the conversation.\n- **Patient message** (`DeliverPatientMessage`, calm, ≤60 words): acknowledge what they told you → \'Ya avisé al equipo médico\' → ONE concrete next step (a `stat` that is not must-go has none) → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside a must-go `stat` and the fever rule, no warning signs by default: naming a sign the patient did not mention makes them watch for it and feel it. If one is truly needed, give at most ONE per episode, about the symptom they already reported getting worse or not easing (\'si el dolor no cede con lo que tomas, escríbeme y lo vemos\') — never another body part or symptom, never a list (not even of related symptoms), never the last line. Outside a must-go `stat` never write \'de inmediato\', \'con urgencia\', \'máxima urgencia\', \'no esperes\', \'por si acaso\' or \'es poco probable, pero\' — not in \'escríbeme de inmediato\' nor in \'ya avisé con urgencia\': the priority travels to the team, not to the patient. Explain the purpose only in general words (\'para revisar qué está pasando y ver si necesitas algo más\'): never name an organ, a complication, a mechanism or what is being ruled out (\'descartar que sea del corazón\', \'una presión en la columna\') — to an oncology patient that reads as a diagnosis. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` asks no characterization question (the fever rule keeps its question about the treatment and the last dose; who can take them is part of the urgencias instruction), and it is the ONLY level that may send the patient now — only for fever (the fever rule below) or when it cannot wait for the team (must-go): bleeding that does not stop; fainting or loss of consciousness; INTENSE shortness of breath at rest (mild breathlessness at rest is not must-go); chest pain with CLEAR shortness of breath, cold sweat, or spreading to the arm or jaw; sudden confusion or a seizure; SUDDEN inability to walk or stand, or sudden weakness (a known, long-standing limitation is not sudden); possible cord compression — weakness in both legs or loss of bladder or bowel control, even if it came on over hours or days; anaphylaxis, only once it is well characterized — the patient confirms swelling of the tongue or throat, trouble swallowing, breathing or speaking (hoarse voice, wheezing), or hives all over WITH dizziness or fainting (more likely after an infusion, a new drug or an antibiotic); swollen lips, hives or a "strange" throat on their own are not enough; shock — skin that is cold and sweaty, mottled, or very pale or greyish TOGETHER WITH strong dizziness on standing, marked weakness or drowsiness, a racing heart, or almost no urine (none in 12 hours or more). Not must-go: hives or itching alone, mouth sores or swelling from mucositis, a puffy face from steroids, throat tightness brought on by cold after oxaliplatin, or cold hands or pallor alone. When a sign is only partly described (swollen lips, hives or a strange throat with nothing else; pale and weak), it is not confirmed yet: ask ONE question about the missing part before choosing the level (\'¿Ahorita tienes hinchazón de lengua o garganta, dificultad para tragar o respirar, voz ronca, o mareo?\' / \'¿Te mareas o casi te desmayas al ponerte de pie, y cuándo orinaste por última vez?\'). Confusion or drowsiness that is slowly increasing, or major bleeding that has already stopped, is not must-go. Any confirmed must-go sign is `stat`, never `asap`. Then calm and unambiguous: ve a urgencias ahora, acompañado; 911 (or an ambulance) if they are alone with no one to take them, cannot move safely, or are unstable — being alone counts as unsafe transport, and they never drive themselves. For anaphylaxis, 911 first, whether or not they are alone; if they have an adrenaline autoinjector, use it now; if they feel dizzy, lie down with the legs raised and do not stand up suddenly. Any other `stat` (not must-go, not fever): only the acknowledgement (\'Ya avisé al equipo médico\') and the availability line — no urgencias, no 911, no question; if the patient asks whether to go to urgencias or says it is getting worse, check it again against the must-go list and answer honestly. ' + FEVER_RULE + '`asap` and `urgent`: no urgencias and no 911 in the message, not even as a condition — the team decides where they are seen (two exceptions: the fever rule, and chest pain with only mild or doubtful shortness of breath, kept at `asap`, where one calm conditional line stays: \'si te cuesta más respirar o el dolor aumenta, ve a urgencias acompañado\'). If they ask whether to go to urgencias or what to watch, answer honestly with 1–2 points about their symptom — the only case where more than one sign is fine. Chest pain alone is not `stat` (anxiety, gastritis, muscle); chest pain WITH clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw IS `stat` (on checkpoint-inhibitor immunotherapy, chest pain is at least `asap`) — even if the patient sounds calm, and even if the two come in different messages of the same episode; otherwise ask ONE question first. `routine`: acknowledgement and when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, ask no characterization question: after a must-go instruction only confirm they are on their way and accompanied.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and make the fallback explicit to the patient whenever nothing is armed. `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
24
+ 'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; the payload is INTERNAL — the patient never sees it.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate without a further clarifying question: `asap` by default, `stat` if there is an acute deficit (sudden weakness of an arm, a leg or one side — even if they can still move it —, can\'t walk/stand, sphincter loss, bilateral leg weakness → possible cord compression) or any instability; an acute deficit is must-go.\n\n**When NOT to call:**\n- An open case in `turn_focus.team_cases` already covers this symptom at this level or higher. Read it before calling (load `getRouterContextBundle` first if you have not this turn). Call again, as an update, only for a new symptom, a higher grade, a new red flag, a detail that makes something more serious plausible, or a symptom that persists or worsens while the team has not answered; a characterization detail that changes none of these needs no call. Otherwise tell the patient where the case stands.\n- Unconfirmed/unspecific symptom — ask ONE characterization question via `DeliverPatientMessage` first.\n- Active mental-health crisis — use `reportCrisis`.\n- Patient shared lab/imaging/values/files — use `reportResultsReceived`.\n- Administrative / operative matter (appointments, insurance, authorizations, letters, transport, scheduling, out-of-scope request) or a non-clinical referral (psico-oncología, paliativos, non-oncology medical) — use `reportUnresolvedRequestv2`.\n- Twice in the same turn for the same episode — already committed; a later datum belongs to the same open escalation.\n\n**After the commit:** the escalation does not end the conversation.\n- **Patient message** (`DeliverPatientMessage`, calm, ≤60 words): acknowledge what they told you → \'Ya avisé al equipo médico\' → ONE concrete next step (a `stat` that is not must-go has none) → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside a must-go `stat` and the fever rule, no warning signs by default: naming a sign the patient did not mention makes them watch for it and feel it. If one is truly needed, give at most ONE per episode, about the symptom they already reported getting worse or not easing (\'si el dolor no cede con lo que tomas, escríbeme y lo vemos\') — never another body part or symptom, never a list (not even of related symptoms), never the last line. Outside a must-go `stat` never write \'de inmediato\', \'con urgencia\', \'máxima urgencia\', \'no esperes\', \'por si acaso\' or \'es poco probable, pero\' — not in \'escríbeme de inmediato\' nor in \'ya avisé con urgencia\': the priority travels to the team, not to the patient. Explain the purpose only in general words (\'para revisar qué está pasando y ver si necesitas algo más\'): never name an organ, a complication, a mechanism or what is being ruled out (\'descartar que sea del corazón\', \'una presión en la columna\') — to an oncology patient that reads as a diagnosis. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` asks no characterization question (the fever rule keeps its question about the treatment and the last dose; who can take them is part of the urgencias instruction), and it is the ONLY level that may send the patient now — only for fever (the fever rule below) or when it cannot wait for the team (must-go): bleeding that does not stop; fainting or loss of consciousness; INTENSE shortness of breath at rest (mild breathlessness at rest is not must-go); chest pain with CLEAR shortness of breath, cold sweat, or spreading to the arm or jaw; sudden confusion or a seizure; SUDDEN inability to walk or stand, or sudden weakness (a known, long-standing limitation is not sudden); possible cord compression — weakness in both legs or loss of bladder or bowel control, even if it came on over hours or days; anaphylaxis, only once it is well characterized — the patient confirms swelling of the tongue or throat, trouble swallowing, breathing or speaking (hoarse voice, wheezing), or hives all over WITH dizziness or fainting (more likely after an infusion, a new drug or an antibiotic); swollen lips, hives or a "strange" throat on their own are not enough; shock — skin that is cold and sweaty, mottled, or very pale or greyish TOGETHER WITH strong dizziness on standing, marked weakness or drowsiness, a racing heart, or almost no urine (none in 12 hours or more). Not must-go: hives or itching alone, mouth sores or swelling from mucositis, a puffy face from steroids, throat tightness brought on by cold after oxaliplatin, or cold hands or pallor alone. When a sign is only partly described (swollen lips, hives or a strange throat with nothing else; pale and weak), it is not confirmed yet: ask ONE question about the missing part before choosing the level (\'¿Ahorita tienes hinchazón de lengua o garganta, dificultad para tragar o respirar, voz ronca, o mareo?\' / \'¿Te mareas o casi te desmayas al ponerte de pie, y cuándo orinaste por última vez?\'). Confusion or drowsiness that is slowly increasing, or major bleeding that has already stopped, is not must-go. Any confirmed must-go sign is `stat`, never `asap`. Then calm and unambiguous: ve a urgencias ahora, acompañado; 911 (or an ambulance) if they are alone with no one to take them, cannot move safely, or are unstable — being alone counts as unsafe transport, and they never drive themselves. For anaphylaxis, 911 first, whether or not they are alone; if they have an adrenaline autoinjector, use it now; if they feel dizzy, lie down with the legs raised and do not stand up suddenly. Any other `stat` (not must-go, not fever): only the acknowledgement (\'Ya avisé al equipo médico\') and the availability line — no urgencias, no 911, no question; if the patient asks whether to go to urgencias or says it is getting worse, check it again against the must-go list and answer honestly. ' + FEVER_RULE + '`asap` and `urgent`: no urgencias and no 911 in the message, not even as a condition — the team decides where they are seen (two exceptions: the fever rule, and chest pain with only mild or doubtful shortness of breath, kept at `asap`, where one calm conditional line stays: \'si te cuesta más respirar o el dolor aumenta, ve a urgencias acompañado\'). If they ask whether to go to urgencias or what to watch, answer honestly with 1–2 points about their symptom — the only case where more than one sign is fine. Chest pain alone is not `stat` (anxiety, gastritis, muscle); chest pain WITH clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw IS `stat` (on checkpoint-inhibitor immunotherapy, chest pain is at least `asap`) — even if the patient sounds calm, and even if the two come in different messages of the same episode; otherwise ask ONE question first. `routine`: acknowledgement and when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, ask no characterization question: after a must-go instruction only confirm they are on their way and accompanied.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and, unless it says otherwise, make the fallback explicit to the patient whenever nothing is armed. `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
25
25
  'strict': true,
26
26
  'parameters': {
27
27
  'type': 'object',
@@ -268,6 +268,9 @@ function followUpNote(armed, reason) {
268
268
  if (armed === null) {
269
269
  return 'This urgency tier gets NO automatic check-in. Nobody will write again on its own — make the fallback explicit in your message to the patient.';
270
270
  }
271
+ if (reason === 'level_without_check_in' && escalationPatientTimerLive()) {
272
+ return 'This level gets no automatic check-in by design: if nobody takes the case, the patient timer sends the numbers to call. Do not add a timed fallback; keep to the instruction for this level.';
273
+ }
271
274
  if (reason === 'active_net_exists') {
272
275
  return 'No check-in was armed for THIS escalation because one is already open for this patient — it may be tracking a different concern, so do not assume the patient will be asked about this one.';
273
276
  }
@@ -44,21 +44,25 @@ const groupConfigured = () => Boolean(runtimeConfig.get('WHAPI_TOKEN') && runtim
44
44
 
45
45
  const teamChannelConfigured = () => groupConfigured() || teamPhones().length > 0;
46
46
 
47
- async function sendToGroup(body) {
47
+ async function postToGroup(body, quoted) {
48
+ const res = await axios({
49
+ url: WHAPI_MESSAGES_URL,
50
+ method: 'POST',
51
+ data: { to: runtimeConfig.get('ESCALATION_TEAM_GROUP_ID'), body, ...(quoted ? { quoted } : {}) },
52
+ timeout: REQUEST_TIMEOUT_MS,
53
+ headers: { authorization: `Bearer ${runtimeConfig.get('WHAPI_TOKEN')}` },
54
+ validateStatus: () => true,
55
+ });
56
+ if (res.status >= 200 && res.status < 300) return { delivered: true, error: null, messageId: res.data?.message?.id || null };
57
+ return { delivered: false, error: `whapi responded ${res.status}` };
58
+ }
59
+
60
+ async function sendToGroup(body, quoted = null) {
48
61
  if (!groupConfigured()) return { delivered: false, error: 'WHAPI_TOKEN or ESCALATION_TEAM_GROUP_ID is not configured' };
49
- const token = runtimeConfig.get('WHAPI_TOKEN');
50
- const group = runtimeConfig.get('ESCALATION_TEAM_GROUP_ID');
51
62
  try {
52
- const res = await axios({
53
- url: WHAPI_MESSAGES_URL,
54
- method: 'POST',
55
- data: { to: group, body },
56
- timeout: REQUEST_TIMEOUT_MS,
57
- headers: { authorization: `Bearer ${token}` },
58
- validateStatus: () => true,
59
- });
60
- if (res.status >= 200 && res.status < 300) return { delivered: true, error: null };
61
- return { delivered: false, error: `whapi responded ${res.status}` };
63
+ const sent = await postToGroup(body, quoted);
64
+ // A quoted message Whapi no longer knows must not cost the alert: it goes out unthreaded.
65
+ return sent.delivered || !quoted ? sent : await postToGroup(body, null);
62
66
  } catch (error) {
63
67
  return { delivered: false, error: redacted(error) };
64
68
  }
@@ -66,9 +70,9 @@ async function sendToGroup(body) {
66
70
 
67
71
  // Alerts the team group and every on-call phone. One failed recipient never stops the others,
68
72
  // and nothing throws: the caller records what reached whom.
69
- async function sendTeamAlert({ message, operator, notice = false }) {
73
+ async function sendTeamAlert({ message, operator, notice = false, quoted = null }) {
70
74
  const templateKey = notice ? NOTICE_TEMPLATE_KEY : ALERT_TEMPLATE_KEY;
71
- const group = await sendToGroup(message.body);
75
+ const group = await sendToGroup(message.body, quoted);
72
76
  const phones = [];
73
77
  for (const code of teamPhones()) {
74
78
  try {
@@ -2,7 +2,7 @@ const { inlineOf } = require('../utils/coercionUtils');
2
2
  const { logger } = require('../utils/logger');
3
3
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
4
4
  const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
5
- const { conversationLink } = require('../clinical/services/clinicalAirtableService');
5
+ const { conversationLink, readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
6
6
  const { escalationGravePendingShadow, escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
7
7
 
8
8
  const { getPatientInformation, logPatientChange } = require('./patientService');
@@ -48,8 +48,15 @@ function untakenClockOf(review, policy) {
48
48
  URGENCY_RANK[appliedLevelOf(alarm)] > (URGENCY_RANK[top] || 0) ? appliedLevelOf(alarm) : top
49
49
  ), null);
50
50
  if (!level) return null;
51
- const since = new Date(alarms.find((alarm) => appliedLevelOf(alarm) === level).raisedAt);
52
- return { level, since, symptom: oneLine(alarms.findLast((alarm) => appliedLevelOf(alarm) === level).symptom), stages: untakenStagesOf(level, since, policy) };
51
+ const atLevel = alarms.filter((alarm) => appliedLevelOf(alarm) === level);
52
+ const since = new Date(atLevel[0].raisedAt);
53
+ return {
54
+ level,
55
+ since,
56
+ symptom: oneLine(atLevel.at(-1).symptom),
57
+ emergencyRecordId: atLevel.find((alarm) => alarm.emergencyRecordId)?.emergencyRecordId ?? null,
58
+ stages: untakenStagesOf(level, since, policy),
59
+ };
53
60
  }
54
61
 
55
62
  const sameStage = (clock, stage) => ({ level: clock.level, stage: stage.stage, since: clock.since });
@@ -141,8 +148,10 @@ async function alertIfUntaken(review, clock, stage, now) {
141
148
  return false;
142
149
  }
143
150
  const message = await untakenMessage(review, clock, stage);
151
+ // Replies to the group message Airtable posted for this alarm, so the case reads as one thread.
152
+ const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
144
153
  if (!await claimStage(review, clock, stage, now)) return false;
145
- const result = await sendTeamAlert({ message, operator: OPERATOR });
154
+ const result = await sendTeamAlert({ message, operator: OPERATOR, quoted });
146
155
  const phonesDelivered = result.phones.filter((phone) => phone.delivered).length;
147
156
  await getEscalationReview().updateOne(
148
157
  { _id: review._id, untakenAlerts: { $elemMatch: sameStage(clock, stage) } },
@@ -155,7 +164,7 @@ async function alertIfUntaken(review, clock, stage, now) {
155
164
  BOOKKEEPING,
156
165
  );
157
166
  await audit(review, {
158
- action: 'untaken_team_alerted', urgencyLevel: clock.level, stage: stage.stage,
167
+ action: 'untaken_team_alerted', urgencyLevel: clock.level, stage: stage.stage, threaded: Boolean(quoted),
159
168
  delivered: result.delivered, groupDelivered: result.group.delivered, phonesDelivered, phones: result.phones.length,
160
169
  });
161
170
  return true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.0-dev.16228",
3
+ "version": "6.0.0-dev.16255",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",