@peopl-health/nexus 5.71.31 → 5.71.33

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.
@@ -22,6 +22,10 @@ function profileSyncOn() {
22
22
  return flagOn('PATIENT_PROFILE_SYNC');
23
23
  }
24
24
 
25
+ function regimenCloserLive() {
26
+ return flagOn('REGIMEN_CLOSER_WRITE_LIVE');
27
+ }
28
+
25
29
  function contextMirrorLive() {
26
30
  return flagOn('CLINICAL_CONTEXT_MIRROR_LIVE') && contextReadLive();
27
31
  }
@@ -33,4 +37,5 @@ module.exports = {
33
37
  contextVerifierLive,
34
38
  profileFromMongo,
35
39
  profileSyncOn,
40
+ regimenCloserLive,
36
41
  };
@@ -1,12 +1,20 @@
1
+ const { regimenCloserLive } = require('../flags/clinicalContextFlags');
1
2
  const { syncContextFacts } = require('./contextSyncService');
2
3
  const { syncLegacyContext } = require('./legacyContextSyncService');
4
+ const { closeStoppedRegimens } = require('./regimenCloserService');
3
5
 
4
6
  // Tier 1 reads what tier 2 wrote, so running them concurrently races a real fact against a floor on one key.
5
7
  async function syncClinicalContext(options = {}) {
6
8
  const facts = await syncContextFacts(options);
7
- if (!facts.ok) return { ok: false, facts, legacy: null };
9
+ if (!facts.ok) return { ok: false, facts, legacy: null, closer: null };
8
10
  const legacy = await syncLegacyContext(options);
9
- return { ok: legacy.ok, facts, legacy };
11
+ // closes what the unit stopped giving after the facts tier wrote, so a fact restated this pass is seen; the
12
+ // per-patient list stays out of the result, which callers log
13
+ const closer = regimenCloserLive()
14
+ ? await closeStoppedRegimens({ dryRun: options.dryRun ?? false, patientScope: options.patientScope ?? null })
15
+ : null;
16
+ const { patients: _patients, ...closerCounts } = closer ?? {};
17
+ return { ok: legacy.ok && (closer?.ok ?? true), facts, legacy, closer: closer ? closerCounts : null };
10
18
  }
11
19
 
12
20
  module.exports = { syncClinicalContext };
@@ -4,7 +4,7 @@ const { readRecordedChemo } = require('../helpers/clinicalProfileHelper');
4
4
  const { getRecordByFilter } = require('../../services/airtableService');
5
5
  const { Quimio_Ops_ID } = require('../../config/airtableConfig');
6
6
  const { MATCH_ALL } = require('../../helpers/airtableFormulaHelper');
7
- const { readContextFacts, listContextFactPatients } = require('../../fhir');
7
+ const { readContextFacts, listContextFactPatients, storeContextFacts } = require('../../fhir');
8
8
  const { mapConcurrent } = require('../../utils/concurrencyUtils');
9
9
  const { daysBetween, mexicoDay } = require('../../utils/dateUtils');
10
10
  const { maskSensitiveValue } = require('../../utils/sanitizerUtils');
@@ -18,6 +18,9 @@ const REGIMEN_MIN_DAYS = 21;
18
18
  // a checkpoint inhibitor is often given every 6 weeks, or held for an immune toxicity
19
19
  const CHECKPOINT_REGIMEN_MIN_DAYS = 84;
20
20
  const INJECTABLE_VARIABLE = 'injectable_onco_summary';
21
+ // the unit's own record: a doctor's role, as trusted as the most trusted extractor source
22
+ const CLOSURE_SOURCE = 'unit';
23
+ const CLOSURE_TRUST = 0.95;
21
24
  const CURRENT_STATUSES = new Set([null, 'taking', 'unknown']);
22
25
  const PROPOSED_STATUS = 'stopped';
23
26
  // the unit's catalog files support care and premedication apart; only its own antineoplastics are closed
@@ -62,12 +65,15 @@ function skipReason(row, { chemo, identity, regimen, regimenDays, replacedInClas
62
65
  return null;
63
66
  }
64
67
 
68
+ // a closure dated on or before the slot's own statement could lose arbitration to it; the regimen start always
69
+ // falls after it, and the drug is absent from that regimen
65
70
  function endOf(row, chemo, identity) {
66
71
  const previous = new Set((chemo.esquemaPrevio?.farmacos ?? []).flatMap((name) => drugsNamed(name, identity).drugs).flatMap(keysOf));
67
72
  const named = drugsNamed(row.concept ?? row.value, identity).drugs.flatMap(keysOf);
68
- return previous.size && named.every((key) => previous.has(key))
73
+ const end = previous.size && named.every((key) => previous.has(key))
69
74
  ? { endDate: chemo.esquemaPrevio.hasta, endFrom: 'esquemaPrevio' }
70
75
  : { endDate: chemo.inicioEsquema.fecha, endFrom: 'inicioEsquema' };
76
+ return end.endDate <= dayOf(row) ? { endDate: chemo.inicioEsquema.fecha, endFrom: 'inicioEsquema' } : end;
71
77
  }
72
78
 
73
79
  // an injectable antineoplastic the unit stopped giving: absent from its current regimen and stated before that regimen began
@@ -103,6 +109,7 @@ function proposeClosures({ chemo, facts, identity, today = mexicoDay(new Date())
103
109
  }
104
110
  closures.push({
105
111
  conceptKey: row.conceptKey,
112
+ concept: row.concept,
106
113
  drug: row.value,
107
114
  status: row.status ?? null,
108
115
  since: dayOf(row),
@@ -119,26 +126,69 @@ function proposeClosures({ chemo, facts, identity, today = mexicoDay(new Date())
119
126
  return { closures, skipped };
120
127
  }
121
128
 
122
- async function dryRunRegimenClosures({ today = mexicoDay(new Date()) } = {}) {
129
+ const closureOf = (patientId, closure, recordTime) => ({
130
+ patientId,
131
+ variableId: INJECTABLE_VARIABLE,
132
+ concept: closure.concept,
133
+ value: closure.drug,
134
+ status: closure.proposedStatus,
135
+ source: CLOSURE_SOURCE,
136
+ trust: CLOSURE_TRUST,
137
+ validTime: `${closure.endDate}T00:00:00.000Z`,
138
+ recordTime,
139
+ });
140
+
141
+ // an async scope answers with a promise, which is truthy, so every patient would pass
142
+ function inScope(patientIds, patientScope) {
143
+ if (!patientScope) return patientIds;
144
+ const answers = patientIds.map((patientId) => patientScope(patientId));
145
+ return answers.every((answer) => typeof answer === 'boolean') ? patientIds.filter((_, i) => answers[i]) : null;
146
+ }
147
+
148
+ // writes only with a patient scope, like the other context passes; a dry run lists what it would write
149
+ async function closeStoppedRegimens({ dryRun = true, patientScope = null, today = mexicoDay(new Date()) } = {}) {
150
+ const empty = { dryRun, closures: 0, written: 0, failed: 0, unreadable: 0, skipped: {}, patients: [] };
151
+ if (patientScope !== null && typeof patientScope !== 'function') return { ...empty, ok: false, reason: 'patient-scope-must-be-a-function' };
152
+ if (!patientScope && !dryRun) return { ...empty, ok: false, reason: 'patient-scope-required' };
123
153
  const identity = await loadDrugIdentity();
124
- if (!identity) return { ok: false, dryRun: true, reason: 'drug-catalog-unreadable', closures: 0, unreadable: 0, skipped: {}, patients: [] };
154
+ if (!identity) return { ...empty, ok: false, reason: 'drug-catalog-unreadable' };
155
+ const scoped = inScope(await listContextFactPatients(), patientScope);
156
+ if (!scoped) return { ...empty, ok: false, reason: 'patient-scope-must-return-boolean' };
125
157
  const patients = [];
126
158
  const skipped = {};
127
159
  let unreadable = 0;
128
- await mapConcurrent(await listContextFactPatients(), DEFAULT_PATIENT_CONCURRENCY, async (patientId) => {
160
+ let written = 0;
161
+ let failed = 0;
162
+ await mapConcurrent(scoped, DEFAULT_PATIENT_CONCURRENCY, async (patientId) => {
163
+ let result;
129
164
  try {
130
165
  const [chemo, facts] = await Promise.all([readRecordedChemo(patientId), readContextFacts({ patientId })]);
131
- const result = proposeClosures({ chemo, facts, identity, today });
132
- Object.entries(result.skipped).forEach(([reason, n]) => { skipped[reason] = (skipped[reason] ?? 0) + n; });
133
- if (result.closures.length) patients.push({ patientId, closures: result.closures });
166
+ result = proposeClosures({ chemo, facts, identity, today });
134
167
  } catch (error) {
135
168
  unreadable += 1;
136
169
  logger.error('[regimenCloser] Patient unreadable', { code: maskSensitiveValue(patientId), error: error.message });
170
+ return;
171
+ }
172
+ Object.entries(result.skipped).forEach(([reason, n]) => { skipped[reason] = (skipped[reason] ?? 0) + n; });
173
+ if (!result.closures.length) return;
174
+ patients.push({ patientId, closures: result.closures });
175
+ if (dryRun) return;
176
+ const recordTime = new Date().toISOString();
177
+ for (const closure of result.closures) {
178
+ try {
179
+ await storeContextFacts({ patientId, assertions: [closureOf(patientId, closure, recordTime)] });
180
+ written += 1;
181
+ } catch (error) {
182
+ failed += 1;
183
+ logger.error('[regimenCloser] Closure rejected', { code: maskSensitiveValue(patientId), error: error.message });
184
+ }
137
185
  }
138
186
  });
139
187
  const closures = patients.reduce((n, patient) => n + patient.closures.length, 0);
140
- logger.info('[regimenCloser] Dry run complete', { patients: patients.length, closures, unreadable, skipped });
141
- return { ok: !unreadable, dryRun: true, closures, unreadable, skipped, patients };
188
+ logger.info('[regimenCloser] Pass complete', { dryRun, patients: patients.length, closures, written, failed, unreadable, skipped });
189
+ return { ok: !unreadable && !failed, dryRun, closures, written, failed, unreadable, skipped, patients };
142
190
  }
143
191
 
144
- module.exports = { proposeClosures, dryRunRegimenClosures };
192
+ const dryRunRegimenClosures = ({ today } = {}) => closeStoppedRegimens({ dryRun: true, today });
193
+
194
+ module.exports = { proposeClosures, closeStoppedRegimens, dryRunRegimenClosures };
@@ -10,10 +10,11 @@ const SEVERITY_RANK = { emergency: 3, safety_relevant: 2, moderate: 1 };
10
10
 
11
11
  const NOT_REPORTED_NOTE = 'El paciente no reportó ningún síntoma actual en este turno. Todo lo que aparezca en el perfil de riesgo son eventos PREVISTOS del tratamiento, no síntomas reportados: nunca afirmes que el paciente los reportó ni le atribuyas un grado.';
12
12
 
13
- const emptyBrief = (escalations) => ({
13
+ const emptyBrief = (escalations, teamCases) => ({
14
14
  current_concerns: [],
15
15
  symptom_history: [],
16
16
  recent_escalations: escalations,
17
+ team_cases: teamCases,
17
18
  relevant_risks: [],
18
19
  checks_now: [],
19
20
  selection: 'no_current_concerns',
@@ -98,6 +99,24 @@ function escalationsFor(escalations, now) {
98
99
  }));
99
100
  }
100
101
 
102
+ // Every case the team still holds, and those it closed within the escalation window.
103
+ function teamCasesFor(escalationCases, now) {
104
+ if (!Array.isArray(escalationCases)) return [];
105
+ const since = escalationLookbackSince(now);
106
+ return escalationCases
107
+ .filter((escalationCase) => escalationCase.isOpen || Date.parse(escalationCase.closedAt ?? escalationCase.lastModified) >= since)
108
+ .slice(0, MAX_ESCALATIONS)
109
+ .map((escalationCase) => ({
110
+ status: escalationCase.label,
111
+ is_open: escalationCase.isOpen,
112
+ level: escalationCase.priority,
113
+ opened_at: isoDay(escalationCase.openedAt),
114
+ days_since: daysSince(escalationCase.openedAt, now),
115
+ doctor_decision: escalationCase.decision,
116
+ case_ids: escalationCase.conditionIds,
117
+ }));
118
+ }
119
+
101
120
  const graded = (assessment) => Number.isInteger(assessment?.grade?.bestEstimate);
102
121
  const at = (assessment) => Date.parse(assessment?.performedAt) || 0;
103
122
 
@@ -131,10 +150,11 @@ function historyFor(concerns, symptomCases, now) {
131
150
  });
132
151
  }
133
152
 
134
- function buildTurnRiskBrief(profile, clinicalMentions = [], { symptomCases = [], escalations = [], now = Date.now() } = {}) {
153
+ function buildTurnRiskBrief(profile, clinicalMentions = [], { symptomCases = [], escalations = [], escalationCases = [], now = Date.now() } = {}) {
135
154
  const recentEscalations = escalationsFor(escalations, now);
155
+ const teamCases = teamCasesFor(escalationCases, now);
136
156
  const concerns = currentConcerns(clinicalMentions);
137
- if (!concerns.length) return emptyBrief(recentEscalations);
157
+ if (!concerns.length) return emptyBrief(recentEscalations, teamCases);
138
158
 
139
159
  const candidates = riskCandidates(profile).map((risk, index) => {
140
160
  const riskTokens = tokens([risk.concern, risk.why, ...risk.warning_signs].join(' '));
@@ -181,6 +201,7 @@ function buildTurnRiskBrief(profile, clinicalMentions = [], { symptomCases = [],
181
201
  current_concerns: concerns.map((concern) => concern.display),
182
202
  symptom_history: historyFor(concerns, symptomCases, now),
183
203
  recent_escalations: recentEscalations,
204
+ team_cases: teamCases,
184
205
  relevant_risks: selected,
185
206
  checks_now: dedupe(selected.flatMap((risk) => risk.checks_now)).slice(0, MAX_CHECKS),
186
207
  selection: !candidates.length
@@ -9,7 +9,7 @@ const EMPTY_OUTBOUND_FALLBACK = 'Recibí tu mensaje. Si quieres contarme más o
9
9
  const definition = {
10
10
  name: 'DeliverPatientMessage',
11
11
  replayArgs: ['message_text', 'purpose'],
12
- description: '**Does:** Delivers the final, patient-facing message in Spanish — the only tool that produces text the patient sees. Call exactly ONCE as the last action of every CHAT turn.\n\n**Required inputs:** `message_text` (the message itself, in Spanish); `purpose` (the conversational purpose); `reasoning` (one short sentence, never shown to the patient, explaining why this is the right message for this turn).\n\n**When to call:** at the end of every chat turn — once. Every substantive inbound must first complete an intake/classification decision. When that decision extracts clinical mentions, code enforces: processed risk through `getRouterContextBundle` (or its dedicated recovery) → `submitRoutingDecision` → this tool. A committed non-clinical terminal workflow may deliver without clinical risk/routing. A rejected call returns the missing step in `data.recovery`; perform it and regenerate the message.\n\n**When NOT to call:**\n- More than once per turn — only ONE patient-facing message per turn.\n- Before the required classification or clinical chain is complete. A rejected call does not set outbound text.\n\n**Returns:** a RECORD, not a send — `{purpose, recorded, delivered:false, still_active, means}`. The reply is stored as the outbound of this turn and leaves only when the turn finishes as the active run; a newer patient message drops it and `still_active` is `false`. Never treat the patient as informed because this call succeeded.\n\n**Side effects:** records the final patient-facing message on the turn trace; delivery to the patient is handled downstream.',
12
+ description: '**Does:** Delivers the final, patient-facing message in Spanish — the only tool that produces text the patient sees. Call exactly ONCE as the last action of every CHAT turn.\n\n**Required inputs:** `message_text` (the message itself, in Spanish); `purpose` (the conversational purpose); `reasoning` (one short sentence, never shown to the patient, explaining why this is the right message for this turn).\n\n**When to call:** at the end of every chat turn — once. Every substantive inbound must first complete an intake/classification decision. When that decision extracts clinical mentions, code enforces: processed risk through `getRouterContextBundle` (or its dedicated recovery) → `submitRoutingDecision` → this tool. A committed non-clinical terminal workflow may deliver without clinical risk/routing. A rejected call returns the missing step in `data.recovery`; perform it and regenerate the message.\n\n**When NOT to call:**\n- More than once per turn — only ONE patient-facing message per turn.\n- Before the required classification or clinical chain is complete. A rejected call does not set outbound text.\n\n**When the patient asks what the care team answered:** say where the case stands from `turn_focus.team_cases` (load `getRouterContextBundle` first if you have not this turn). Never add a time, and never say the team already reviewed or saw something unless the status is one where the team answered (`Esperando paciente`, `Indicaciones dadas`, `En vigilancia`).\n\n**Returns:** a RECORD, not a send — `{purpose, recorded, delivered:false, still_active, means}`. The reply is stored as the outbound of this turn and leaves only when the turn finishes as the active run; a newer patient message drops it and `still_active` is `false`. Never treat the patient as informed because this call succeeded.\n\n**Side effects:** records the final patient-facing message on the turn trace; delivery to the patient is handled downstream.',
13
13
  strict: false,
14
14
  parameters: {
15
15
  type: 'object',
@@ -1,11 +1,11 @@
1
1
  const { assembleRiskProfile } = require('../services/riskAssessmentService');
2
2
  const { buildTurnRiskBrief, escalationLookbackSince } = require('../services/turnRiskBriefService');
3
- const { readDispatchedEscalations, readSymptomCases } = require('../../fhir');
3
+ const { readDispatchedEscalations, readEscalationCases, readSymptomCases } = require('../../fhir');
4
4
  const { logger } = require('../../utils/logger');
5
5
 
6
6
  const definition = {
7
7
  name: 'getPatientRiskAssessment',
8
- description: '**Does:** Returns the patient\'s latest full risk assessment and a deterministic `turn_focus` for the symptoms extracted in this turn. Read-only; no model call.\n\n**Required inputs:** none.\n\n**When to call:** immediately before `submitRoutingDecision` only when `getRouterContextBundle.sections_returned` does not contain `risk`, including a bundle result with `_diagnostics.risk_error`. The routine load is the bundle\'s mandatory `risk` section, which resolves the same assessment through the same code path.\n\n**When NOT to call:** when `getRouterContextBundle` already returned `risk` this turn — it is the same assessment, and a second read cannot change it. Nor again in the same turn after a `not_generated` result — generation runs between turns and the result cannot change mid-turn.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT — never whether the team replied, what they advised, or whether the problem resolved; ask the patient for that. A complaint unchanged since an escalation a day ago rarely needs a second dispatch; one still uncontrolled days after its escalation needs one at a HIGHER urgency, and `urgency_justification` should say which of the two this is. Empty means nothing was escalated in the window.\n\n**Use `turn_focus.symptom_history` before grading or escalating.** It carries what no other section does: how this patient compares to their own past. `worst_grade` and `worst_reported_at` are the worst they have ever been recorded, `at_personal_worst` says whether they are back at it, and `days_since_last_report` says how stale `last_grade` is. (The current grade and trajectory are already in `landscape.active_cases` — do not expect them repeated here.) Escalate on the comparison, not on severity alone: a patient at their personal worst is a different decision from one below it, and a grade unchanged for weeks is different from the same grade reported yesterday. When you ask about it, anchor the question in the value and the date so the patient can compare. Empty means no graded case on record. \n\n**How to use:** read `turn_focus.current_concerns`, then each `relevant_risks[].checks_now` and `escalation_threshold`. It preserves concurrent symptoms. Any `selection` containing `fallback` marks a precaution to check, not a confirmed explanation. When `selection` is `no_current_concerns` the patient reported no current symptom this turn. Use `profile` only for supporting detail.\n\n**`profile` is a forecast, not history:** `predicted_aes[].minimum_symptom_set`, `disease_risks[].warning_symptoms` and every other profile list name symptoms to watch for, none of which the patient has reported. Never tell the patient a profile symptom appears in their report, and never attach a CTCAE grade to one. Reported symptoms come only from `turn_focus.current_concerns`.\n\n**Returns:** `status` — `final` when an assessment exists and carries findings, `no_signal` when one exists but the synthesis found nothing usable, or `not_generated`; `turn_focus`, always present; and the full `profile` (`predicted_aes[]`, `disease_risks[]`, `comorbidity_amplifiers[]`, lifecycle and missing-information fields). `profile` is null when not yet generated.',
8
+ description: '**Does:** Returns the patient\'s latest full risk assessment and a deterministic `turn_focus` for the symptoms extracted in this turn. Read-only; no model call.\n\n**Required inputs:** none.\n\n**When to call:** immediately before `submitRoutingDecision` only when `getRouterContextBundle.sections_returned` does not contain `risk`, including a bundle result with `_diagnostics.risk_error`. The routine load is the bundle\'s mandatory `risk` section, which resolves the same assessment through the same code path.\n\n**When NOT to call:** when `getRouterContextBundle` already returned `risk` this turn — it is the same assessment, and a second read cannot change it. Nor again in the same turn after a `not_generated` result — generation runs between turns and the result cannot change mid-turn.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT; where the team is with it is in `team_cases`. A complaint unchanged since an escalation a day ago rarely needs a second dispatch; one still uncontrolled days after its escalation needs one at a HIGHER urgency, and `urgency_justification` should say which of the two this is. Empty means nothing was escalated in the window.\n\n**`turn_focus.team_cases` — where the care team is with each case.** Every case the team still holds, and those it closed in the last 14 days, newest first: `status`, `is_open`, `level`, `opened_at`, `days_since`, `doctor_decision` and `case_ids` (the symptom cases it covers).\n- `Por revisar`, `En evaluación`, `Con el médico`, `Indicación por enviar`, `Requiere valoración`: the team has it and has not answered yet. Tell the patient it is with the team, without promising a time. A new escalation is for a new symptom, a higher grade, a new red flag, or a symptom that persists or worsens while it waits (send it as an update).\n- `Esperando paciente`, `Indicaciones dadas`, `En vigilancia`: the team already answered (an indication on its way to the patient, given, or under watch). This comes first: ask how the indication is going before escalating again.\n- `Cerrado`, `No requiere`: the team closed it. A new complaint is a new decision.\n`doctor_decision` is internal (`approved`, `edited_approved`, `monitor`, `needs_intervention` = the doctor asked for an in-person evaluation, `returned`, `direct_chat`): use it to understand the case, never quote it. `team_cases` never says whether the problem resolved; ask the patient. An escalation in `recent_escalations` with no case here has an unknown team status, not an absent one.\n\n**Use `turn_focus.symptom_history` before grading or escalating.** It carries what no other section does: how this patient compares to their own past. `worst_grade` and `worst_reported_at` are the worst they have ever been recorded, `at_personal_worst` says whether they are back at it, and `days_since_last_report` says how stale `last_grade` is. (The current grade and trajectory are already in `landscape.active_cases` — do not expect them repeated here.) Escalate on the comparison, not on severity alone: a patient at their personal worst is a different decision from one below it, and a grade unchanged for weeks is different from the same grade reported yesterday. When you ask about it, anchor the question in the value and the date so the patient can compare. Empty means no graded case on record. \n\n**How to use:** read `turn_focus.current_concerns`, then each `relevant_risks[].checks_now` and `escalation_threshold`. It preserves concurrent symptoms. Any `selection` containing `fallback` marks a precaution to check, not a confirmed explanation. When `selection` is `no_current_concerns` the patient reported no current symptom this turn. Use `profile` only for supporting detail.\n\n**`profile` is a forecast, not history:** `predicted_aes[].minimum_symptom_set`, `disease_risks[].warning_symptoms` and every other profile list name symptoms to watch for, none of which the patient has reported. Never tell the patient a profile symptom appears in their report, and never attach a CTCAE grade to one. Reported symptoms come only from `turn_focus.current_concerns`.\n\n**Returns:** `status` — `final` when an assessment exists and carries findings, `no_signal` when one exists but the synthesis found nothing usable, or `not_generated`; `turn_focus`, always present; and the full `profile` (`predicted_aes[]`, `disease_risks[]`, `comorbidity_amplifiers[]`, lifecycle and missing-information fields). `profile` is null when not yet generated.',
9
9
  strict: false,
10
10
  replayScope: 'turn',
11
11
  parameters: {
@@ -21,7 +21,7 @@ async function handler(_args = {}, context = {}) {
21
21
  if (!runtime?.turnId || !runtime?.patientCode) {
22
22
  return JSON.stringify({ success: false, error: 'getPatientRiskAssessment requires an active turn context (turnId, patientCode).', data: {} });
23
23
  }
24
- const [data, symptomCases, escalations] = await Promise.all([
24
+ const [data, symptomCases, escalations, escalationCases] = await Promise.all([
25
25
  assembleRiskProfile(runtime.patientCode),
26
26
  readSymptomCases({ patientId: runtime.patientCode }).catch((error) => {
27
27
  logger.warn('[getPatientRiskAssessment] symptom history unavailable', { code: runtime.patientCode, error: error?.message });
@@ -32,8 +32,12 @@ async function handler(_args = {}, context = {}) {
32
32
  logger.warn('[getPatientRiskAssessment] escalation recall unavailable', { code: runtime.patientCode, error: error?.message });
33
33
  return [];
34
34
  }),
35
+ readEscalationCases({ patientId: runtime.patientCode }).catch((error) => {
36
+ logger.warn('[getPatientRiskAssessment] team cases unavailable', { code: runtime.patientCode, error: error?.message });
37
+ return [];
38
+ }),
35
39
  ]);
36
- const turnFocus = buildTurnRiskBrief(data.profile, runtime.trace?.signals?.clinicalMentions, { symptomCases, escalations });
40
+ const turnFocus = buildTurnRiskBrief(data.profile, runtime.trace?.signals?.clinicalMentions, { symptomCases, escalations, escalationCases });
37
41
  const result = { ...data, turn_focus: turnFocus };
38
42
  runtime.trace?.setSignals?.({
39
43
  riskAssessmentChecked: true,
@@ -2,7 +2,7 @@ const { assembleLandscape } = require('../services/symptomLandscapeService');
2
2
  const { assembleHistory, SUPPORTED_SCOPES, TIMEFRAME_DAYS } = require('../services/patientHistoryService');
3
3
  const { assembleRiskProfile } = require('../services/riskAssessmentService');
4
4
  const { buildTurnRiskBrief, escalationLookbackSince } = require('../services/turnRiskBriefService');
5
- const { readDispatchedEscalations, readSymptomCases } = require('../../fhir');
5
+ const { readDispatchedEscalations, readEscalationCases, readSymptomCases } = require('../../fhir');
6
6
  const { logger } = require('../../utils/logger');
7
7
 
8
8
  const ALLOWED_SECTIONS = ['landscape', 'history', 'risk'];
@@ -10,7 +10,7 @@ const REQUIRED_SECTION = 'risk';
10
10
 
11
11
  const definition = {
12
12
  name: 'getRouterContextBundle',
13
- description: '**Does:** Batched router-context fetch — always evaluates and returns the mandatory `risk` section, plus the requested `landscape` and/or `history` sections. Read-only.\n\n**Required inputs:** none. Optional `include` selects additional sections (`landscape`, `history`; a supplied `risk` value is accepted but redundant), plus optional `landscape_min_priority`, `history_scope`, `history_filter`. Omitting `include` returns all three sections.\n\n**When to call:** after intake at the start of every routing turn, as the single load of the patient\'s clinical context. Do not call it in parallel with `Skill(clinical_routing)`: first read the skill body, then call this bundle. The patient\'s risk disposition cannot be excluded by `include`. Prefer this over calling `getActiveSymptomLandscape`, `getPatientHistory` or `getPatientRiskAssessment` for the same context.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT — never whether the team replied, what they advised, or whether the problem resolved; ask the patient for that. A complaint unchanged since an escalation a day ago rarely needs a second dispatch; one still uncontrolled days after its escalation needs one at a HIGHER urgency, and `urgency_justification` should say which of the two this is. Empty means nothing was escalated in the window.\n\n**Use `turn_focus.symptom_history` before grading or escalating.** It carries what no other section does: how this patient compares to their own past. `worst_grade` and `worst_reported_at` are the worst they have ever been recorded, `at_personal_worst` says whether they are back at it, and `days_since_last_report` says how stale `last_grade` is. (The current grade and trajectory are already in `landscape.active_cases` — do not expect them repeated here.) Escalate on the comparison, not on severity alone: a patient at their personal worst is a different decision from one below it, and a grade unchanged for weeks is different from the same grade reported yesterday. When you ask about it, anchor the question in the value and the date so the patient can compare. Empty means no graded case on record. \n\n**A case flagged `stale_no_recent_evidence` has had no new evidence for two weeks or more.** `days_since_evidence` says how long. Ask whether the symptom is still there, and close the case with `recordClinicalImpression` `close` when it is not: an open case keeps consuming the landscape and keeps the symptom reading as active on the record.\n\n**How to use risk:** read `risk.turn_focus` first — it is always present. It deterministically keeps every current symptom and maps it to relevant full-profile risks, `checks_now`, and `escalation_threshold`; use the full `risk.profile` only for supporting detail. A highest-severity fallback is labelled explicitly when no direct symptom match exists. When `turn_focus.selection` is `no_current_concerns` the patient reported no current symptom this turn.\n\n**`risk.profile` is a forecast, not history:** `predicted_aes[].minimum_symptom_set`, `disease_risks[].warning_symptoms` and every other profile list name symptoms to watch for, none of which the patient has reported. Never tell the patient a profile symptom appears in their report, and never attach a CTCAE grade to one. Reported symptoms come only from `landscape`, `history` and `turn_focus.current_concerns`.\n\n**Recovery:** verify `sections_returned` contains `risk`. If it does not, inspect `_diagnostics.risk_error` and call `getPatientRiskAssessment` before `submitRoutingDecision`.\n\n**Returns:** `patient_id`, `sections_requested[]`, `sections_returned[]` (only sections that succeeded), mandatory `risk` (always including `turn_focus`), and requested `landscape` / `history`. A section that errors is omitted and its error reported under `_diagnostics`. The attempted risk read and deterministic turn processing are recorded on the turn trace even when no profile exists.',
13
+ description: '**Does:** Batched router-context fetch — always evaluates and returns the mandatory `risk` section, plus the requested `landscape` and/or `history` sections. Read-only.\n\n**Required inputs:** none. Optional `include` selects additional sections (`landscape`, `history`; a supplied `risk` value is accepted but redundant), plus optional `landscape_min_priority`, `history_scope`, `history_filter`. Omitting `include` returns all three sections.\n\n**When to call:** after intake at the start of every routing turn, as the single load of the patient\'s clinical context. Do not call it in parallel with `Skill(clinical_routing)`: first read the skill body, then call this bundle. The patient\'s risk disposition cannot be excluded by `include`. Prefer this over calling `getActiveSymptomLandscape`, `getPatientHistory` or `getPatientRiskAssessment` for the same context.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT; where the team is with it is in `team_cases`. A complaint unchanged since an escalation a day ago rarely needs a second dispatch; one still uncontrolled days after its escalation needs one at a HIGHER urgency, and `urgency_justification` should say which of the two this is. Empty means nothing was escalated in the window.\n\n**`turn_focus.team_cases` — where the care team is with each case.** Every case the team still holds, and those it closed in the last 14 days, newest first: `status`, `is_open`, `level`, `opened_at`, `days_since`, `doctor_decision` and `case_ids` (the symptom cases it covers).\n- `Por revisar`, `En evaluación`, `Con el médico`, `Indicación por enviar`, `Requiere valoración`: the team has it and has not answered yet. Tell the patient it is with the team, without promising a time. A new escalation is for a new symptom, a higher grade, a new red flag, or a symptom that persists or worsens while it waits (send it as an update).\n- `Esperando paciente`, `Indicaciones dadas`, `En vigilancia`: the team already answered (an indication on its way to the patient, given, or under watch). This comes first: ask how the indication is going before escalating again.\n- `Cerrado`, `No requiere`: the team closed it. A new complaint is a new decision.\n`doctor_decision` is internal (`approved`, `edited_approved`, `monitor`, `needs_intervention` = the doctor asked for an in-person evaluation, `returned`, `direct_chat`): use it to understand the case, never quote it. `team_cases` never says whether the problem resolved; ask the patient. An escalation in `recent_escalations` with no case here has an unknown team status, not an absent one.\n\n**Use `turn_focus.symptom_history` before grading or escalating.** It carries what no other section does: how this patient compares to their own past. `worst_grade` and `worst_reported_at` are the worst they have ever been recorded, `at_personal_worst` says whether they are back at it, and `days_since_last_report` says how stale `last_grade` is. (The current grade and trajectory are already in `landscape.active_cases` — do not expect them repeated here.) Escalate on the comparison, not on severity alone: a patient at their personal worst is a different decision from one below it, and a grade unchanged for weeks is different from the same grade reported yesterday. When you ask about it, anchor the question in the value and the date so the patient can compare. Empty means no graded case on record. \n\n**A case flagged `stale_no_recent_evidence` has had no new evidence for two weeks or more.** `days_since_evidence` says how long. Ask whether the symptom is still there, and close the case with `recordClinicalImpression` `close` when it is not: an open case keeps consuming the landscape and keeps the symptom reading as active on the record.\n\n**How to use risk:** read `risk.turn_focus` first — it is always present. It deterministically keeps every current symptom and maps it to relevant full-profile risks, `checks_now`, and `escalation_threshold`; use the full `risk.profile` only for supporting detail. A highest-severity fallback is labelled explicitly when no direct symptom match exists. When `turn_focus.selection` is `no_current_concerns` the patient reported no current symptom this turn.\n\n**`risk.profile` is a forecast, not history:** `predicted_aes[].minimum_symptom_set`, `disease_risks[].warning_symptoms` and every other profile list name symptoms to watch for, none of which the patient has reported. Never tell the patient a profile symptom appears in their report, and never attach a CTCAE grade to one. Reported symptoms come only from `landscape`, `history` and `turn_focus.current_concerns`.\n\n**Recovery:** verify `sections_returned` contains `risk`. If it does not, inspect `_diagnostics.risk_error` and call `getPatientRiskAssessment` before `submitRoutingDecision`.\n\n**Returns:** `patient_id`, `sections_requested[]`, `sections_returned[]` (only sections that succeeded), mandatory `risk` (always including `turn_focus`), and requested `landscape` / `history`. A section that errors is omitted and its error reported under `_diagnostics`. The attempted risk read and deterministic turn processing are recorded on the turn trace even when no profile exists.',
14
14
  strict: false,
15
15
  replayScope: 'turn',
16
16
  parameters: {
@@ -65,7 +65,7 @@ async function handler(args = {}, context = {}) {
65
65
  if (args.history_scope != null) historyArgs.scope = args.history_scope;
66
66
  if (args.history_filter != null) historyArgs.filter = args.history_filter;
67
67
 
68
- const [symptomCases, escalations] = await Promise.all([
68
+ const [symptomCases, escalations, escalationCases] = await Promise.all([
69
69
  readSymptomCases({ patientId }).catch((error) => {
70
70
  logger.warn('[routerContextBundle] symptom cases unavailable', { code: patientId, error: error?.message });
71
71
  return null;
@@ -74,6 +74,10 @@ async function handler(args = {}, context = {}) {
74
74
  logger.warn('[routerContextBundle] escalation recall unavailable', { code: patientId, error: error?.message });
75
75
  return [];
76
76
  }),
77
+ readEscalationCases({ patientId }).catch((error) => {
78
+ logger.warn('[routerContextBundle] team cases unavailable', { code: patientId, error: error?.message });
79
+ return [];
80
+ }),
77
81
  ]);
78
82
 
79
83
  const readers = {
@@ -93,7 +97,7 @@ async function handler(args = {}, context = {}) {
93
97
  bundle[section] = outcome.value;
94
98
  bundle.sections_returned.push(section);
95
99
  if (section === 'risk') {
96
- const turnFocus = buildTurnRiskBrief(outcome.value.profile, runtime.trace?.signals?.clinicalMentions, { symptomCases: symptomCases || [], escalations });
100
+ const turnFocus = buildTurnRiskBrief(outcome.value.profile, runtime.trace?.signals?.clinicalMentions, { symptomCases: symptomCases || [], escalations, escalationCases });
97
101
  bundle[section] = { ...outcome.value, turn_focus: turnFocus };
98
102
  // Same signal shape as getPatientRiskAssessmentTool: utilization metrics must count both read paths.
99
103
  runtime.trace?.setSignals?.({
@@ -25,7 +25,7 @@ const FEVER_RULE = 'Fever that is `stat`: ≥38.0 °C within 8 weeks of cytotoxi
25
25
 
26
26
  const definition = {
27
27
  'name': 'reportMedicalEscalation',
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`).',
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- 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 → 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`).',
29
29
  'strict': true,
30
30
  'parameters': {
31
31
  'type': 'object',
@@ -15,7 +15,7 @@ const NO_KNOWN_ALLERGY = {
15
15
  };
16
16
 
17
17
  const SOURCE_ROLES = {
18
- specialist: DOCTOR, doctor: DOCTOR, oncologist: DOCTOR, auna: DOCTOR, note: DOCTOR, operator: DOCTOR,
18
+ specialist: DOCTOR, doctor: DOCTOR, oncologist: DOCTOR, auna: DOCTOR, note: DOCTOR, operator: DOCTOR, unit: DOCTOR,
19
19
  'legacy-clinician': DOCTOR,
20
20
  self: PATIENT, patient: PATIENT, chat: PATIENT,
21
21
  'legacy-self': PATIENT,
package/lib/index.d.ts CHANGED
@@ -451,6 +451,8 @@ declare module '@peopl-health/nexus' {
451
451
  ok: boolean;
452
452
  facts: ContextSyncResult;
453
453
  legacy: ContextSyncResult | null;
454
+ /** The regimen closer's counts, without the per-patient list; null while REGIMEN_CLOSER_WRITE_LIVE is off. */
455
+ closer: Omit<RegimenCloserResult, 'patients'> | null;
454
456
  }
455
457
 
456
458
  export function syncContextFacts(options?: ContextSyncOptions): Promise<ContextSyncResult>;
@@ -573,6 +575,7 @@ declare module '@peopl-health/nexus' {
573
575
 
574
576
  export interface RegimenClosure {
575
577
  conceptKey: string;
578
+ concept: string | null;
576
579
  drug: string;
577
580
  status: string | null;
578
581
  since: string;
@@ -582,16 +585,23 @@ declare module '@peopl-health/nexus' {
582
585
  evidence: { ultimaAplicacion: ChemoContext['ultimaAplicacion']; esquema: string[]; inicioEsquema: ChemoContext['inicioEsquema']; esquemaPrevio: ChemoContext['esquemaPrevio'] };
583
586
  }
584
587
 
585
- /** Read-only: the injectable antineoplastic slots the chemo unit's current regimen shows as stopped. Writes nothing. */
586
- export function dryRunRegimenClosures(options?: { today?: string }): Promise<{
588
+ export interface RegimenCloserResult {
587
589
  ok: boolean;
588
- dryRun: true;
590
+ dryRun: boolean;
589
591
  closures: number;
592
+ written: number;
593
+ failed: number;
590
594
  unreadable: number;
591
595
  reason?: string;
592
596
  skipped: Record<string, number>;
593
597
  patients: Array<{ patientId: string; closures: RegimenClosure[] }>;
594
- }>;
598
+ }
599
+
600
+ /** Read-only: the injectable antineoplastic slots the chemo unit's current regimen shows as stopped. Writes nothing. */
601
+ export function dryRunRegimenClosures(options?: { today?: string }): Promise<RegimenCloserResult>;
602
+
603
+ /** Writes those closures as `stopped` facts (source `unit`, validTime = end date); a dry run unless `dryRun: false` with a `patientScope`. */
604
+ export function closeStoppedRegimens(options?: { dryRun?: boolean; patientScope?: (patientId: string) => boolean; today?: string }): Promise<RegimenCloserResult>;
595
605
 
596
606
  export const routes: any;
597
607
  export function setupDefaultRoutes(app: any): void;
package/lib/index.js CHANGED
@@ -48,7 +48,7 @@ const { syncLegacyContext } = require('./clinical/services/legacyContextSyncServ
48
48
  const { syncClinicalContext } = require('./clinical/services/contextSyncRunner');
49
49
  const { runProactiveOutreachSweep } = require('./clinical/services/outreachSweepRunner');
50
50
  const { currentRegimen } = require('./clinical/services/currentRegimenService');
51
- const { dryRunRegimenClosures } = require('./clinical/services/regimenCloserService');
51
+ const { closeStoppedRegimens, dryRunRegimenClosures } = require('./clinical/services/regimenCloserService');
52
52
  const { readRecordedChemo } = require('./clinical/helpers/clinicalProfileHelper');
53
53
  const { registerTool, hasTool, getToolSchemas, clearRegistry } = require('./services/toolRegistryService');
54
54
  const { MapCache } = require('./utils/MapCache');
@@ -364,6 +364,7 @@ module.exports = {
364
364
  runProactiveOutreachSweep,
365
365
  currentRegimen,
366
366
  dryRunRegimenClosures,
367
+ closeStoppedRegimens,
367
368
  readRecordedChemo,
368
369
  syncContextFacts,
369
370
  retractContentlessFacts,
@@ -10,7 +10,7 @@ const { updatePatientTask } = require('./patientTaskService');
10
10
  const MIRROR_OPERATOR = 'bot:escalationCase';
11
11
  const MIRROR_SOURCE = 'escalation_case';
12
12
 
13
- const caseTaskLive = () => String(runtimeConfig.get('ESCALATION_CASE_TASK_LIVE', 'false')).trim().toLowerCase() === 'true';
13
+ const caseTaskLive = () => String(runtimeConfig.get('ESCALATION_CASE_TASK_LIVE', 'true')).trim().toLowerCase() !== 'false';
14
14
 
15
15
  function conditionIdsOf(review) {
16
16
  const impressed = (review.updates ?? []).flatMap((update) => (update.impressions ?? []).map((impression) => impression.caseId));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.71.31",
3
+ "version": "5.71.33",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",