@peopl-health/nexus 6.5.15 → 6.5.17

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.
@@ -24,7 +24,7 @@ const FEVER_RULE = 'Fever within 6 weeks (42 days) of cytotoxic chemotherapy (or
24
24
 
25
25
  const definition = {
26
26
  'name': 'reportMedicalEscalation',
27
- 'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; the payload is INTERNAL — the patient never sees it.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate now, with no question that invites a downgrade: `asap` by default, `stat` if there is an acute deficit (new, sudden weakness of an arm, a leg or one side, numbness of the face or a whole side, a drooping face or new trouble speaking — even if they can still move it —; new loss of bladder or bowel control; new or worsening leg weakness with back or neck pain, known spine disease or bone metastases (or, with bone status unknown, a cancer that often spreads to the spine), or groin numbness, or sudden weakness of both legs → possible cord compression) or any instability; an acute deficit is must-go and asks nothing, except the one onset question when it is not yet known whether it came on suddenly. In `asap`, ask the short neuro checklist in the same message as ONE question on one line, not a numbered list (\'¿Sabes dónde estás y qué día es, puedes hablar bien, ves bien, sientes debilidad de un lado, has vomitado o convulsionado?\'), keeping the message ≤60 words — the one exception to asking about a single sign and to no lists.\n\n**When NOT to call:**\n- An open case in `turn_focus.team_cases` already covers this symptom at this level or higher. Read it before calling (load `getRouterContextBundle` first if you have not this turn). Call again, as an update, only for a new symptom, a higher grade, a new red flag, a detail that makes something more serious plausible, or a symptom that persists or worsens while the team has not answered; a characterization detail that changes none of these needs no call. Otherwise tell the patient where the case stands.\n- Unconfirmed/unspecific symptom — ask ONE characterization question via `DeliverPatientMessage` first.\n- Active mental-health crisis — use `reportCrisis`.\n- Patient shared lab/imaging/values/files — use `reportResultsReceived`.\n- Administrative / operative matter (appointments, insurance, authorizations, letters, transport, scheduling, out-of-scope request) or a non-clinical referral (psico-oncología, paliativos, non-oncology medical) — use `reportUnresolvedRequestv2`.\n- Twice in the same turn for the same episode — already committed; a later datum belongs to the same open escalation.\n\n**After the commit:** the escalation does not end the conversation.\n- **Patient message** (`DeliverPatientMessage`, calm, ≤60 words): acknowledge what they told you → \'Ya avisé al equipo médico\' → ONE concrete next step (a `stat` that is not must-go has none) → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside a must-go `stat`, no warning signs by default: naming a sign the patient did not mention makes them watch for it and feel it. If one is truly needed, give at most ONE per episode, about the symptom they already reported getting worse or not easing (\'si el dolor no cede con lo que tomas, escríbeme y lo vemos\') — never another body part or symptom, never a list (not even of related symptoms), never the last line. Outside a must-go `stat` never write \'de inmediato\', \'con urgencia\', \'máxima urgencia\', \'no esperes\', \'por si acaso\' or \'es poco probable, pero\' — not in \'escríbeme de inmediato\' nor in \'ya avisé con urgencia\': the priority travels to the team, not to the patient. Explain the purpose only in general words (\'para revisar qué está pasando y ver si necesitas algo más\'): never name an organ, a complication, a mechanism or what is being ruled out (\'descartar que sea del corazón\', \'una presión en la columna\') — to an oncology patient that reads as a diagnosis. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` asks no characterization question (the fever rule keeps its question about the treatment and the last dose; who can take them is part of the urgencias instruction), and it is the ONLY level that may send the patient now — only for fever (the fever rule below) or when it cannot wait for the team (must-go): bleeding that does not stop, or vomiting blood or black, tarry stool together with dizziness or near-fainting on standing (even without the skin signs of shock); fainting or loss of consciousness; INTENSE shortness of breath at rest (mild breathlessness at rest is not must-go, except with the checkpoint-inhibitor signs below); chest pain with CLEAR shortness of breath, cold sweat, or spreading to the arm or jaw; sudden confusion or a seizure; NEW, SUDDEN weakness of one arm, one leg or one side, numbness of the face or of a whole side (face, arm and leg), a drooping face or new trouble speaking, even if they can still move it (a known, long-standing limitation is not sudden; general weakness or tiredness, or not getting up from fatigue, is not must-go: `asap`, or `urgent` if it is gradual and they are eating, drinking and passing urine; if they cannot stand because they feel faint, check it against fainting and shock); possible cord compression — NEW or WORSENING weakness in the legs TOGETHER WITH back or neck pain, known spine disease or bone metastases (or, with bone status unknown, a cancer that often spreads to the spine: breast, prostate, lung, kidney, myeloma), or numbness in the groin or buttocks, even if it came on over hours or days; or SUDDEN weakness of both legs (it came on within hours), even without back pain; or new loss of bladder or bowel control on its own (not feeling or not holding urine or stool, or not being able to pass urine; urgency from diarrhea is not this) — tingling or numbness in hands and feet from neuropathy, or long-standing leg weakness without back pain, is not must-go, and new back pain with no neurologic sign is `asap`; on active or recent checkpoint-inhibitor immunotherapy, drooping eyelids, double vision, new trouble swallowing or leg weakness getting worse over days is at least `asap`, and must-go with shortness of breath at rest or when they cannot swallow; anaphylaxis, only once it is well characterized — the patient confirms swelling of the tongue or throat, trouble swallowing, breathing or speaking (hoarse voice, wheezing), or hives all over WITH dizziness or fainting (more likely after an infusion, a new drug or an antibiotic); swollen lips, hives or a "strange" throat on their own are not enough; shock — skin that is cold and sweaty, or mottled, or grey or bluish lips, TOGETHER WITH at least one of: near-fainting on standing, new confusion or drowsiness, a racing heart at rest, or almost no urine (none in 12 hours or more); pallor, tiredness or weakness without those skin signs is not must-go (`asap`). Not must-go: hives or itching alone, mouth sores or swelling from mucositis, a puffy face from steroids, throat tightness brought on by cold after oxaliplatin, or cold hands, pallor or tiredness alone. When a sign is only partly described (swollen lips, hives or a strange throat with nothing else; cold or mottled skin with nothing else; weakness without knowing whether it is one side; leg weakness or numbness without knowing when it started — «sudden» means within minutes or hours, as the patient says, never assumed; numbness or tingling alone, without weakness, is not must-go unless it is of the face, of a whole side, or of the groin with leg weakness; numbness of one arm or one leg alone gets the onset question first), it is not confirmed yet: ask ONE question about the missing part before choosing the level; when leg weakness or numbness has no stated onset, that question MUST ask when it started (walking or back pain may go in the same question, never instead of it) (\'¿Ahorita tienes hinchazón de lengua o garganta, dificultad para tragar o respirar, voz ronca, o mareo?\' / \'¿Te mareas o casi te desmayas al ponerte de pie, y cuándo orinaste por última vez?\' / \'¿La debilidad es de todo el cuerpo, como cansancio, o de un brazo, una pierna o un lado?\' / \'¿Desde cuándo lo sientes, fue de golpe o poco a poco, y puedes caminar?\'). Confusion or drowsiness that is slowly increasing, or major bleeding that has already stopped, is not must-go. Any confirmed must-go sign is `stat`, never `asap`. Then calm and unambiguous: ve a urgencias ahora, acompañado, and they never drive themselves; if they are alone: \'pide que alguien venga por ti o toma un taxi; si no puedes moverte o te sientes peor, llama al 911\'. 911 (or an ambulance) FIRST, alone or not and even if they can move, for: anaphylaxis; fainting they have not fully recovered from; a seizure or sudden confusion; a possible stroke (sudden weakness of one side, an arm or a leg, sudden numbness of the face or a whole side, a drooping face, sudden trouble speaking); chest pain with clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw; INTENSE shortness of breath at rest; shock; heavy bleeding (vomiting blood, a lot of black or bloody stool, or bleeding that soaks through cloths or towels; a nosebleed or other bleed that keeps going despite pressure without soaking through is must-go, not 911-first); and cord compression when they cannot walk. For anaphylaxis, if they have an adrenaline autoinjector, use it now; if they feel dizzy, lie down with the legs raised and do not stand up suddenly. Any other `stat` (not must-go, not fever): only the acknowledgement (\'Ya avisé al equipo médico\'), the availability line and, as in `asap` and `urgent`, at most the one conditional urgencias line below — no direct urgencias, no 911, no question; if the patient asks whether to go to urgencias or says it is getting worse, check it again against the must-go list and answer honestly. ' + FEVER_RULE + '`asap` and `urgent`: never 911 and never an instruction to go now, unless an internal instruction from the system (the patient timer) asks you to — the team decides where they are seen. The one warning sign allowed above may point to urgencias, as a single calm conditional line about ONE symptom they already reported getting clearly worse (\'si el dolor aumenta mucho, ve a urgencias con alguien que te acompañe\'): one condition, no list of signs and no \'si alguno de estos…\', no other symptom or body part, and never 911 in it (one exception: chest pain with only mild or doubtful shortness of breath, kept at `asap`, where that line is always: \'si te cuesta más respirar o el dolor aumenta, ve a urgencias acompañado\'). If they ask whether to go to urgencias or what to watch, answer honestly with 1–2 points about their symptom — the only case where more than one sign is fine. Chest pain alone is not `stat` (anxiety, gastritis, muscle); chest pain WITH clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw IS `stat` (on checkpoint-inhibitor immunotherapy, chest pain is at least `asap`) — even if the patient sounds calm, and even if the two come in different messages of the same episode; otherwise ask ONE question first. `routine`: acknowledgement and when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, ask no characterization question: after a must-go instruction only confirm they are on their way: accompanied, someone or a taxi coming, or the ambulance called.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and, unless it says otherwise, make the fallback explicit to the patient whenever nothing is armed (an invitation to write again if it changes or worries them — never a time, and no urgencias beyond the one conditional line `asap` and `urgent` allow). `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
27
+ 'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; `details` and the justification are INTERNAL — the patient never sees them. Only `patient_check_in` and `patient_symptom_label` reach the patient.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate now, with no question that invites a downgrade: `asap` by default, `stat` if there is an acute deficit (new, sudden weakness of an arm, a leg or one side, numbness of the face or a whole side, a drooping face or new trouble speaking — even if they can still move it —; new loss of bladder or bowel control; new or worsening leg weakness with back or neck pain, known spine disease or bone metastases (or, with bone status unknown, a cancer that often spreads to the spine), or groin numbness, or sudden weakness of both legs → possible cord compression) or any instability; an acute deficit is must-go and asks nothing, except the one onset question when it is not yet known whether it came on suddenly. In `asap`, ask the short neuro checklist in the same message as ONE question on one line, not a numbered list (\'¿Sabes dónde estás y qué día es, puedes hablar bien, ves bien, sientes debilidad de un lado, has vomitado o convulsionado?\'), keeping the message ≤60 words — the one exception to asking about a single sign and to no lists.\n\n**When NOT to call:**\n- An open case in `turn_focus.team_cases` already covers this symptom at this level or higher. Read it before calling (load `getRouterContextBundle` first if you have not this turn). Call again, as an update, only for a new symptom, a higher grade, a new red flag, a detail that makes something more serious plausible, or a symptom that persists or worsens while the team has not answered; a characterization detail that changes none of these needs no call. Otherwise tell the patient where the case stands.\n- Unconfirmed/unspecific symptom — ask ONE characterization question via `DeliverPatientMessage` first.\n- Active mental-health crisis — use `reportCrisis`.\n- Patient shared lab/imaging/values/files — use `reportResultsReceived`.\n- Administrative / operative matter (appointments, insurance, authorizations, letters, transport, scheduling, out-of-scope request) or a non-clinical referral (psico-oncología, paliativos, non-oncology medical) — use `reportUnresolvedRequestv2`.\n- Twice in the same turn for the same episode — already committed; a later datum belongs to the same open escalation.\n\n**After the commit:** the escalation does not end the conversation.\n- **Patient message** (`DeliverPatientMessage`, calm, ≤60 words): acknowledge what they told you → \'Ya avisé al equipo médico\' → ONE concrete next step (a `stat` that is not must-go has none) → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside a must-go `stat`, no warning signs by default: naming a sign the patient did not mention makes them watch for it and feel it. If one is truly needed, give at most ONE per episode, about the symptom they already reported getting worse or not easing (\'si el dolor no cede con lo que tomas, escríbeme y lo vemos\') — never another body part or symptom, never a list (not even of related symptoms), never the last line. Outside a must-go `stat` never write \'de inmediato\', \'con urgencia\', \'máxima urgencia\', \'no esperes\', \'por si acaso\' or \'es poco probable, pero\' — not in \'escríbeme de inmediato\' nor in \'ya avisé con urgencia\': the priority travels to the team, not to the patient. Explain the purpose only in general words (\'para revisar qué está pasando y ver si necesitas algo más\'): never name an organ, a complication, a mechanism or what is being ruled out (\'descartar que sea del corazón\', \'una presión en la columna\') — to an oncology patient that reads as a diagnosis. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` asks no characterization question (the fever rule keeps its question about the treatment and the last dose; who can take them is part of the urgencias instruction), and it is the ONLY level that may send the patient now — only for fever (the fever rule below) or when it cannot wait for the team (must-go): bleeding that does not stop, or vomiting blood or black, tarry stool together with dizziness or near-fainting on standing (even without the skin signs of shock); fainting or loss of consciousness; INTENSE shortness of breath at rest (mild breathlessness at rest is not must-go, except with the checkpoint-inhibitor signs below); chest pain with CLEAR shortness of breath, cold sweat, or spreading to the arm or jaw; sudden confusion or a seizure; NEW, SUDDEN weakness of one arm, one leg or one side, numbness of the face or of a whole side (face, arm and leg), a drooping face or new trouble speaking, even if they can still move it (a known, long-standing limitation is not sudden; general weakness or tiredness, or not getting up from fatigue, is not must-go: `asap`, or `urgent` if it is gradual and they are eating, drinking and passing urine; if they cannot stand because they feel faint, check it against fainting and shock); possible cord compression — NEW or WORSENING weakness in the legs TOGETHER WITH back or neck pain, known spine disease or bone metastases (or, with bone status unknown, a cancer that often spreads to the spine: breast, prostate, lung, kidney, myeloma), or numbness in the groin or buttocks, even if it came on over hours or days; or SUDDEN weakness of both legs (it came on within hours), even without back pain; or new loss of bladder or bowel control on its own (not feeling or not holding urine or stool, or not being able to pass urine; urgency from diarrhea is not this) — tingling or numbness in hands and feet from neuropathy, or long-standing leg weakness without back pain, is not must-go, and new back pain with no neurologic sign is `asap`; on active or recent checkpoint-inhibitor immunotherapy, drooping eyelids, double vision, new trouble swallowing or leg weakness getting worse over days is at least `asap`, and must-go with shortness of breath at rest or when they cannot swallow; anaphylaxis, only once it is well characterized — the patient confirms swelling of the tongue or throat, trouble swallowing, breathing or speaking (hoarse voice, wheezing), or hives all over WITH dizziness or fainting (more likely after an infusion, a new drug or an antibiotic); swollen lips, hives or a "strange" throat on their own are not enough; shock — skin that is cold and sweaty, or mottled, or grey or bluish lips, TOGETHER WITH at least one of: near-fainting on standing, new confusion or drowsiness, a racing heart at rest, or almost no urine (none in 12 hours or more); pallor, tiredness or weakness without those skin signs is not must-go (`asap`). Not must-go: hives or itching alone, mouth sores or swelling from mucositis, a puffy face from steroids, throat tightness brought on by cold after oxaliplatin, or cold hands, pallor or tiredness alone. When a sign is only partly described (swollen lips, hives or a strange throat with nothing else; cold or mottled skin with nothing else; weakness without knowing whether it is one side; leg weakness or numbness without knowing when it started — «sudden» means within minutes or hours, as the patient says, never assumed; numbness or tingling alone, without weakness, is not must-go unless it is of the face, of a whole side, or of the groin with leg weakness; numbness of one arm or one leg alone gets the onset question first), it is not confirmed yet: ask ONE question about the missing part before choosing the level; when leg weakness or numbness has no stated onset, that question MUST ask when it started (walking or back pain may go in the same question, never instead of it) (\'¿Ahorita tienes hinchazón de lengua o garganta, dificultad para tragar o respirar, voz ronca, o mareo?\' / \'¿Te mareas o casi te desmayas al ponerte de pie, y cuándo orinaste por última vez?\' / \'¿La debilidad es de todo el cuerpo, como cansancio, o de un brazo, una pierna o un lado?\' / \'¿Desde cuándo lo sientes, fue de golpe o poco a poco, y puedes caminar?\'). Confusion or drowsiness that is slowly increasing, or major bleeding that has already stopped, is not must-go. Any confirmed must-go sign is `stat`, never `asap`. Then calm and unambiguous: ve a urgencias ahora, acompañado, and they never drive themselves; if they are alone: \'pide que alguien venga por ti o toma un taxi; si no puedes moverte o te sientes peor, llama al 911\'. 911 (or an ambulance) FIRST, alone or not and even if they can move, for: anaphylaxis; fainting they have not fully recovered from; a seizure or sudden confusion; a possible stroke (sudden weakness of one side, an arm or a leg, sudden numbness of the face or a whole side, a drooping face, sudden trouble speaking); chest pain with clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw; INTENSE shortness of breath at rest; shock; heavy bleeding (vomiting blood, a lot of black or bloody stool, or bleeding that soaks through cloths or towels; a nosebleed or other bleed that keeps going despite pressure without soaking through is must-go, not 911-first); and cord compression when they cannot walk. For anaphylaxis, if they have an adrenaline autoinjector, use it now; if they feel dizzy, lie down with the legs raised and do not stand up suddenly. Any other `stat` (not must-go, not fever): only the acknowledgement (\'Ya avisé al equipo médico\'), the availability line and, as in `asap` and `urgent`, at most the one conditional urgencias line below — no direct urgencias, no 911, no question; if the patient asks whether to go to urgencias or says it is getting worse, check it again against the must-go list and answer honestly. ' + FEVER_RULE + '`asap` and `urgent`: never 911 and never an instruction to go now, unless an internal instruction from the system (the patient timer) asks you to — the team decides where they are seen. The one warning sign allowed above may point to urgencias, as a single calm conditional line about ONE symptom they already reported getting clearly worse (\'si el dolor aumenta mucho, ve a urgencias con alguien que te acompañe\'): one condition, no list of signs and no \'si alguno de estos…\', no other symptom or body part, and never 911 in it (one exception: chest pain with only mild or doubtful shortness of breath, kept at `asap`, where that line is always: \'si te cuesta más respirar o el dolor aumenta, ve a urgencias acompañado\'). If they ask whether to go to urgencias or what to watch, answer honestly with 1–2 points about their symptom — the only case where more than one sign is fine. Chest pain alone is not `stat` (anxiety, gastritis, muscle); chest pain WITH clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw IS `stat` (on checkpoint-inhibitor immunotherapy, chest pain is at least `asap`) — even if the patient sounds calm, and even if the two come in different messages of the same episode; otherwise ask ONE question first. `routine`: acknowledgement and when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, ask no characterization question: after a must-go instruction only confirm they are on their way: accompanied, someone or a taxi coming, or the ambulance called.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and, unless it says otherwise, make the fallback explicit to the patient whenever nothing is armed (an invitation to write again if it changes or worries them — never a time, and no urgencias beyond the one conditional line `asap` and `urgent` allow). `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
28
28
  'strict': true,
29
29
  'parameters': {
30
30
  'type': 'object',
@@ -50,6 +50,17 @@ const definition = {
50
50
  }
51
51
  ]
52
52
  },
53
+ 'patient_symptom_label': {
54
+ 'anyOf': [
55
+ {
56
+ 'type': 'string',
57
+ 'description': 'Nullable. What the patient is going through, in the patient\'s own words, 2 to 6 words with the article (\'la visión borrosa y los mareos\', \'el dolor de la rodilla\'). The patient reads it verbatim days later in the case follow-up, so it is patient-facing, unlike `details`: NO grades, scales, numbers, lab values, drugs, diagnoses, CTCAE or medical terms, dates or names. On an update about the same episode, repeat the label you gave it. Pass `null` only when you cannot name it that way — the neutral question is used then.'
58
+ },
59
+ {
60
+ 'type': 'null'
61
+ }
62
+ ]
63
+ },
53
64
  'urgency_justification': {
54
65
  'type': 'string',
55
66
  'description': 'Por qué ESTE nivel — y explícitamente por qué no el inmediato superior ni el inferior (qué dato objetivo define el tier). Es el registro auditable de la decisión. Una o dos frases. INTERNO; el paciente nunca lo ve. '
@@ -72,7 +83,7 @@ const definition = {
72
83
  'persistent_symptom_72h',
73
84
  'stale_clinical_context'
74
85
  ],
75
- 'description': 'Rama clínica que motiva la escalación. Elige la que describe el motivo, no la más frecuente.\n- `febrile_neutropenia`: fiebre o sospecha de infección en ventana de quimioterapia.\n- `neuro_constellation`: DOS O MÁS de — cambio visual, mareo/vértigo/pérdida de equilibrio, incapacidad de caminar o mantenerse en pie, debilidad o adormecimiento focal, confusión aguda, cefalea súbita intensa — en este turno o en los últimos 2-3. Cuenta los que el paciente reporta, no los que descartas. Esta rama fuerza `asap` como mínimo.\n- `spinal_cord_compression`: debilidad de piernas nueva o en aumento con dolor de espalda o cuello, enfermedad de columna o metástasis óseas (o, si no se sabe, un cáncer que suele ir a la columna), o adormecimiento en ingle o glúteos; debilidad de las dos piernas de golpe; o pérdida nueva del control de orina o excremento.\n- `treatment_concern`: duda o efecto atribuible al tratamiento en curso.\n- `persistent_symptom_72h`: síntoma que lleva MÁS DE 72 HORAS sin resolverse. No es el cajón por defecto: un síntoma de hoy o de ayer no entra aquí.\n- `stale_clinical_context`: el expediente no refleja la situación real del paciente.'
86
+ 'description': 'Rama clínica que motiva la escalación. Elige la que describe el motivo, no la más frecuente.\n- `febrile_neutropenia`: un dato de temperatura en ventana de quimioterapia: 38.0 °C o más, se siente con fiebre o calentura sin termómetro, escalofríos o temblores, malestar tras paracetamol, antiinflamatorio o corticoide en las últimas 6 h, o menos de 36.0 °C confirmado al volver a medir con malestar. No lo es un síntoma de la semana de defensas bajas sin ese dato (sangrado, diarrea, dolor de garganta, sudoración, hinchazón): eso es `treatment_concern`. Una lectura de 36.0 a 37.4 °C no es fiebre, y un antipirético de hace más de 6 h no sostiene la etiqueta: una temperatura medida después, normal y sin escalofríos, descarta la fiebre. En una actualización, si la fiebre quedó descartada, cambia a `treatment_concern` aunque la alarma anterior fuera `febrile_neutropenia`.\n- `neuro_constellation`: DOS O MÁS de — cambio visual, mareo/vértigo/pérdida de equilibrio, incapacidad de caminar o mantenerse en pie, debilidad o adormecimiento focal, confusión aguda, cefalea súbita intensa — en este turno o en los últimos 2-3. Cuenta los que el paciente reporta, no los que descartas. Esta rama fuerza `asap` como mínimo.\n- `spinal_cord_compression`: debilidad de piernas nueva o en aumento con dolor de espalda o cuello, enfermedad de columna o metástasis óseas (o, si no se sabe, un cáncer que suele ir a la columna), o adormecimiento en ingle o glúteos; debilidad de las dos piernas de golpe; o pérdida nueva del control de orina o excremento.\n- `treatment_concern`: duda o efecto atribuible al tratamiento en curso.\n- `persistent_symptom_72h`: síntoma que lleva MÁS DE 72 HORAS sin resolverse. No es el cajón por defecto: un síntoma de hoy o de ayer no entra aquí.\n- `stale_clinical_context`: el expediente no refleja la situación real del paciente.'
76
87
  },
77
88
  {
78
89
  'type': 'null'
@@ -139,6 +150,7 @@ const definition = {
139
150
  'required': [
140
151
  'urgency_level',
141
152
  'patient_check_in',
153
+ 'patient_symptom_label',
142
154
  'urgency_justification',
143
155
  'details',
144
156
  'reasoning'
@@ -310,6 +322,7 @@ async function handler(args, context = {}) {
310
322
  urgencyLevel: requestedLevel,
311
323
  category,
312
324
  symptom: details.symptom || null,
325
+ patientLabel: typeof args?.patient_symptom_label === 'string' ? args.patient_symptom_label : null,
313
326
  evidenceQuote: details.evidence_quote || null,
314
327
  suspectedCondition: details.suspected_condition || null,
315
328
  recommendedAction: details.recommended_action || null,
@@ -23,6 +23,7 @@ const alarmSchema = new mongoose.Schema({
23
23
  urgencyLevel: { type: String, enum: URGENCY_LEVELS, required: true },
24
24
  category: { type: String, default: null },
25
25
  symptom: { type: String, default: null },
26
+ patientLabel: { type: String, default: null },
26
27
  evidenceQuote: { type: String, default: null },
27
28
  suspectedCondition: { type: String, default: null },
28
29
  recommendedAction: { type: String, default: null },
@@ -21,6 +21,7 @@ const SEND_WINDOW = { timeZone: DEFAULT_TIMEZONE, startHour: 11, endHour: 21 };
21
21
  const FOLLOW_UP_STATUSES = ['indications_sent', 'monitoring'];
22
22
  const BOOKKEEPING = { timestamps: false };
23
23
  const PLAN_EXCERPT = 400;
24
+ const PATIENT_LABEL_MAX = 40;
24
25
  // The follow-up template the send_reminder automation uses past the 24 h window (Airtable Monitoreo).
25
26
  const FOLLOW_UP_TEMPLATE_SID = 'HX182fee522708bdb43db5ea614f538369';
26
27
  // send_reminder fires up to 6 min before the row's time.
@@ -38,34 +39,51 @@ function followUpOf(decision) {
38
39
  return { kind: 'auto', hours: AUTO_HOURS };
39
40
  }
40
41
 
41
- const symptomOf = (review) => inlineOf([...(review.alarms ?? [])].reverse().find((alarm) => inlineOf(alarm.symptom))?.symptom) || null;
42
+ const caseAlarmOf = (review) => [...(review.alarms ?? [])].reverse().find((alarm) => inlineOf(alarm.symptom)) || null;
43
+ const symptomOf = (review) => inlineOf(caseAlarmOf(review)?.symptom) || null;
44
+ const isPatientLabel = (label) => label.length > 0 && label.length <= PATIENT_LABEL_MAX && !/[\d():;+/%=<>≈→—–_]/.test(label);
45
+ const patientLabelOf = (review) => {
46
+ const label = oneLineOf(caseAlarmOf(review)?.patientLabel).replace(/^[¿¡\s]+|[.,¿?¡!\s]+$/g, '').toLowerCase();
47
+ return isPatientLabel(label) ? label : null;
48
+ };
42
49
  const dayOf = (value) => moment(value).tz(DEFAULT_TIMEZONE).format('DD/MM');
43
50
 
44
51
  function questionFor(review, attempt) {
45
- const about = symptomOf(review) ? ` con ${symptomOf(review).toLowerCase()}` : '';
46
- return attempt === 1
47
- ? `¿Cómo has seguido${about}? Cuéntame si vas mejor, igual o peor.`
48
- : `Quería saber cómo vas${about}. ¿Vas mejor, igual o peor?`;
52
+ const label = patientLabelOf(review);
53
+ if (attempt === 1) {
54
+ return label
55
+ ? `${label}. ¿Cómo te has sentido con eso estos días?`
56
+ : 'queremos saber cómo estás. ¿Cómo te has sentido desde entonces?';
57
+ }
58
+ return label
59
+ ? `${label}. Seguimos pendientes de ti. ¿Cómo sigues con eso?`
60
+ : 'seguimos pendientes de ti. ¿Cómo sigues?';
49
61
  }
50
62
 
51
63
  function decisionContext(decision) {
52
64
  const what = decision.decision === 'monitor' ? 'el médico indicó vigilarlo en casa' : 'el médico le dio indicaciones';
53
65
  const sent = decision.plan ? oneLineOf(planSummary(decision.plan)) : oneLineOf(decision.finalText);
54
66
  const excerpt = sent && sent.length > PLAN_EXCERPT ? `${sent.slice(0, PLAN_EXCERPT)}…` : sent;
55
- return `el ${dayOf(decision.createdAt)} ${what}${excerpt ? ` («${excerpt}»)` : ''}`;
67
+ return `El ${dayOf(decision.createdAt)} ${what}${excerpt ? ` («${excerpt}»)` : ''}.`;
56
68
  }
57
69
 
58
70
  function caseInstruction(review, firstName) {
59
71
  const name = firstName || 'la paciente';
60
- const symptom = symptomOf(review)?.toLowerCase() || 'lo que te contó';
61
- const context = decisionContext(review.decisions.at(-1));
72
+ const about = patientLabelOf(review) || 'lo que te contó';
73
+ const note = symptomOf(review);
74
+ const internal = note ? `\n\nNota interna del equipo, solo para ti: «${note}». No la cites ni le pases sus grados, cifras, diagnósticos ni términos clínicos.` : '';
75
+ const how = 'Un solo mensaje breve, cálido y natural, de dos o tres frases. Nombra lo que siente con sus propias palabras de la conversación, nunca con las de la nota. Como mucho una frase de apoyo (por ejemplo «seguimos pendientes de ti»), sin dar por hecho que mejoró, sin prometer nada ni sugerir gravedad. Haz una sola pregunta abierta sobre cómo ha cambiado; no le des opciones como en una encuesta (nada de «mejor, igual o peor»). Tutéala con lenguaje neutro en género.';
76
+ const read = 'Con lo que conteste, entiende tú si va mejor, igual o peor; si no queda claro, repregúntale una sola vez de forma natural, comparando con hace unos días. Si va peor o cuenta algo nuevo, retómalo como cualquier síntoma.';
62
77
  const quiet = 'No menciones alertas, revisiones, el sistema ni que este mensaje estaba programado.';
78
+ const context = `${decisionContext(review.decisions.at(-1))}${internal}`;
63
79
  if (review.caseFollowUp.attempt > 1) {
64
- return `Le preguntaste a ${name} cómo seguía con ${symptom} (${context}) y no ha contestado. Escríbele una vez más, con un mensaje distinto al anterior, breve y cálido, para saber si va mejor, igual o peor. No le reproches que no contestó. ${quiet}`;
80
+ return `Le preguntaste a ${name} cómo seguía con ${about} y no ha contestado. ${context}
81
+
82
+ Escríbele una vez más, distinto al mensaje anterior y más corto. ${how} No le reproches que no contestó. ${read} ${quiet}`;
65
83
  }
66
- return `Toca darle seguimiento a ${name} por ${symptom}: ${context}.
84
+ return `Toca darle seguimiento a ${name} por ${about}. ${context}
67
85
 
68
- Revisa la conversación desde entonces. Si ya te contó cómo va, no se lo vuelvas a preguntar: si dijo que va peor, retómalo; si no, cierra en una línea breve y cálida. Si no lo ha dicho, pregúntale una sola vez, en un mensaje breve y natural, cómo ha seguido con ${symptom}: si va mejor, igual o peor. Si contesta algo poco claro, aclara eso antes de cerrar. ${quiet}`;
86
+ Revisa la conversación desde entonces. Si ya te contó cómo va, no se lo vuelvas a preguntar: si va peor, retómalo; si no, cierra en una línea breve y cálida. Si no lo ha dicho, pregúntaselo una sola vez. ${how} ${read} ${quiet}`;
69
87
  }
70
88
 
71
89
  async function standDown(code, reminderId, reason) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.5.15",
3
+ "version": "6.5.17",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",