@peopl-health/nexus 5.71.30 → 5.71.32

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.
@@ -1,4 +1,4 @@
1
- const { readContingencies, readClusters, storeCluster } = require('../../fhir');
1
+ const { closeRoutingDispositions, readContingencies, readClusters, storeCluster } = require('../../fhir');
2
2
  const { RESOLUTION_CLOSE_REASONS } = require('../../shared/dtos/ManagedSymptom');
3
3
  const { RESOLVED_REASONS } = require('../../shared/dtos/ContingencySafetyNet');
4
4
  const { ClusterImpression } = require('../../shared/dtos/ClusterImpression');
@@ -58,7 +58,7 @@ function closePatch({ closeReason, resolving, reasoning }) {
58
58
  };
59
59
  }
60
60
 
61
- async function runCloseCascade(patientId, caseId, turnId, trace = null, sourceTool = 'updateConditionStatus') {
61
+ async function runCloseCascade(patientId, caseId, turnId, trace, sourceTool, { closeReason }) {
62
62
  const autoResolvedPlans = [];
63
63
  const prunedClusters = [];
64
64
  const dissolvedClusters = [];
@@ -74,6 +74,12 @@ async function runCloseCascade(patientId, caseId, turnId, trace = null, sourceTo
74
74
  cascadeErrors.push(`contingency_auto_resolve_failed: ${error?.message || error}`);
75
75
  }
76
76
 
77
+ try {
78
+ await closeRoutingDispositions({ patientId, caseId, closeReason, resolving: isResolutionReason(closeReason) });
79
+ } catch (error) {
80
+ cascadeErrors.push(`routing_disposition_close_failed: ${error?.message || error}`);
81
+ }
82
+
77
83
  const clusters = await readClusters({ patientId, status: 'active' }).catch((error) => {
78
84
  cascadeErrors.push(`cluster_cascade_failed: ${error?.message || error}`);
79
85
  return [];
@@ -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?.({
@@ -321,7 +321,9 @@ async function handler(args = {}, context = {}) {
321
321
  const dissolvedClusters = [];
322
322
  if (event === 'close') {
323
323
  try {
324
- const cascade = await runCloseCascade(patientId, caseId, runtime.turnId, runtime.trace || null, 'recordClinicalImpression');
324
+ const cascade = await runCloseCascade(patientId, caseId, runtime.turnId, runtime.trace || null, 'recordClinicalImpression', {
325
+ closeReason: result.condition.closeReason,
326
+ });
325
327
  autoResolvedPlans.push(...cascade.autoResolvedPlans);
326
328
  prunedClusters.push(...cascade.prunedClusters);
327
329
  dissolvedClusters.push(...cascade.dissolvedClusters);
@@ -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',
@@ -3,7 +3,9 @@ const crypto = require('node:crypto');
3
3
  const { clinicalIntakeRequiresRisk, hasAlternateTerminalCommit, validateRoutingPrerequisites } = require('../helpers/clinicalWorkflowGuard');
4
4
  const { MEDICATION_NAMING_RULE } = require('../helpers/medicationNamingRule');
5
5
  const { attachRequiredSkill } = require('../helpers/skillActivationHelper');
6
- const { storeRoutingDecision, readRoutingDecisions, readSymptomCases } = require('../../fhir');
6
+ const { isResolutionReason } = require('../services/conditionCloseService');
7
+ const { closeRoutingDispositions, storeRoutingDecision, readRoutingDecisions, readSymptomCases } = require('../../fhir');
8
+ const { CLOSED_STATUSES } = require('../../shared/dtos/ManagedSymptom');
7
9
  const { RoutingDecision } = require('../../shared/dtos/RoutingDecision');
8
10
  const { foldAccents } = require('../../utils/formatUtils');
9
11
  const { logger } = require('../../utils/logger');
@@ -49,6 +51,20 @@ const _COMPOSE_SYNONYMS = {
49
51
  separate: 'separate_if_space',
50
52
  };
51
53
 
54
+ // The case is already closed (often earlier this same turn): its disposition is born closed, as the cascade
55
+ // would have left it.
56
+ async function closeDispositionForClosedCase({ patientId, turnId, caseId, cases }) {
57
+ const condition = caseId ? cases.find((c) => c.condition.conditionId === caseId)?.condition : null;
58
+ if (!CLOSED_STATUSES.includes(condition?.clinicalStatus) || !condition.closeReason) return;
59
+ try {
60
+ await closeRoutingDispositions({
61
+ patientId, caseId, closeReason: condition.closeReason, resolving: isResolutionReason(condition.closeReason),
62
+ });
63
+ } catch (error) {
64
+ logger.warn('[submitRoutingDecision] could not close the disposition of an already-closed case', { patientId, turnId, caseId, error: error?.message });
65
+ }
66
+ }
67
+
52
68
  const _ACTION_TO_DISPOSITION_KIND = {
53
69
  emergency_escalation: 'task',
54
70
  team_escalation: 'task',
@@ -398,8 +414,9 @@ async function handler(args = {}, context = {}) {
398
414
  }
399
415
 
400
416
  const namedCaseIds = [...new Set([...traceResult.findings.map((f) => f.caseId), plan.primaryCaseId].filter(Boolean))];
417
+ let cases = [];
401
418
  if (namedCaseIds.length) {
402
- const cases = await readSymptomCases({ patientId });
419
+ cases = await readSymptomCases({ patientId });
403
420
  const known = new Set(cases.map((c) => c.condition.conditionId));
404
421
  const unknown = namedCaseIds.filter((id) => !known.has(id));
405
422
  if (unknown.length) {
@@ -417,6 +434,7 @@ async function handler(args = {}, context = {}) {
417
434
 
418
435
  const decision = buildDecision({ patientId, turnId, plan, findings: traceResult.findings, now: new Date().toISOString() });
419
436
  await storeRoutingDecision({ patientId, routingDecision: decision });
437
+ await closeDispositionForClosedCase({ patientId, turnId, caseId: plan.primaryCaseId, cases });
420
438
 
421
439
  runtime.trace.setSignals({ branchTaken: 'ai_agent' });
422
440
 
@@ -165,7 +165,9 @@ async function handler(args = {}, context = {}) {
165
165
  const result = applyDormant(existing, reasoning, args, transition === 'resolve');
166
166
  if (typeof result === 'string') return result;
167
167
  await storeSymptomCase({ patientId, managedSymptom: result });
168
- const cascade = await runCloseCascade(patientId, result.condition.conditionId, runtime.turnId, runtime.trace || null);
168
+ const cascade = await runCloseCascade(patientId, result.condition.conditionId, runtime.turnId, runtime.trace || null, 'updateConditionStatus', {
169
+ closeReason: result.condition.closeReason,
170
+ });
169
171
  const data = {
170
172
  case_id: result.condition.conditionId,
171
173
  status: returnedStatus(result.condition),
package/lib/fhir/index.js CHANGED
@@ -18,7 +18,7 @@ const { storeContingency, readContingencies } = require('./services/contingencyS
18
18
  const { readDispatchedEscalations, readEscalationCases, storeEscalationCase } = require('./services/escalationService');
19
19
  const { storeIntervention, readInterventions } = require('./services/interventionService');
20
20
  const { storeCluster, readClusters } = require('./services/clusterService');
21
- const { storeRoutingDecision, readRoutingDecisions } = require('./services/routingService');
21
+ const { closeRoutingDispositions, storeRoutingDecision, readRoutingDecisions } = require('./services/routingService');
22
22
  const {
23
23
  storePalliativeAssessment,
24
24
  readPalliativeAssessments,
@@ -76,6 +76,7 @@ module.exports = {
76
76
  readInterventions,
77
77
  storeCluster,
78
78
  readClusters,
79
+ closeRoutingDispositions,
79
80
  storeRoutingDecision,
80
81
  readRoutingDecisions,
81
82
  storePalliativeAssessment,
@@ -1,5 +1,6 @@
1
+ const { codeableConcept } = require('../helpers/elementHelper');
1
2
  const { fhirId } = require('../helpers/fhirHelper');
2
- const { ROUTING_ASSESSMENT_SLUG } = require('../constants/projectionSlugs');
3
+ const { ROUTING_ASSESSMENT_SLUG, ROUTING_DISPOSITION_SLUG } = require('../constants/projectionSlugs');
3
4
  const { getFhirStore } = require('../stores/fhirStore');
4
5
  const { toFhir, fromFhir } = require('../projections/routingProjection');
5
6
  const { storeResources } = require('./fhirService');
@@ -12,6 +13,54 @@ async function storeRoutingDecision({ patientId, routingDecision }) {
12
13
  return { count: stored.length, ids: stored };
13
14
  }
14
15
 
16
+ const DISPOSITION_TYPES = ['Task', 'CommunicationRequest', 'RequestOrchestration', 'CarePlan'];
17
+ const OPEN_STATUSES = new Set(['draft', 'requested', 'received', 'accepted', 'ready', 'in-progress', 'on-hold', 'active']);
18
+ // Handing a case to the team carries these actions out; the bot's own follow-ups are withdrawn instead.
19
+ const ESCALATION_ACTIONS = new Set(['team_escalation', 'emergency_escalation', 'palliative_referral']);
20
+
21
+ const caseLinks = (resource) => [...(resource.reason || []), ...(resource.addresses || [])]
22
+ .map((link) => link.reference?.reference)
23
+ .filter(Boolean);
24
+ const primaryActionOf = (resource) => resource.code?.text || resource.action?.[0]?.title || null;
25
+
26
+ function closedStatus(resource, { closeReason, resolving }) {
27
+ if (resolving) return 'completed';
28
+ const done = closeReason === 'escalated_to_team' && ESCALATION_ACTIONS.has(primaryActionOf(resource));
29
+ if (resource.resourceType === 'Task') return done ? 'completed' : 'cancelled';
30
+ return done ? 'completed' : 'revoked';
31
+ }
32
+
33
+ function closedFields(resource, { closeReason, resolving }, now) {
34
+ const fields = { status: closedStatus(resource, { closeReason, resolving }) };
35
+ if (resource.resourceType === 'Task') {
36
+ fields.statusReason = { concept: codeableConcept(closeReason) };
37
+ fields.lastModified = now;
38
+ }
39
+ if (resource.resourceType === 'CommunicationRequest') fields.statusReason = codeableConcept(closeReason);
40
+ return fields;
41
+ }
42
+
43
+ async function closeRoutingDispositions({ patientId, caseId, closeReason, resolving }) {
44
+ if (!closeReason) throw new Error('closeRoutingDispositions requires the case closeReason');
45
+ const store = getFhirStore();
46
+ const caseRef = `Condition/${fhirId(caseId)}`;
47
+ const dispositions = await store.find({
48
+ patient: `Patient/${fhirId(patientId)}`,
49
+ resourceType: DISPOSITION_TYPES,
50
+ identifierSlug: ROUTING_DISPOSITION_SLUG,
51
+ });
52
+ const open = dispositions.filter((resource) => OPEN_STATUSES.has(resource.status) && caseLinks(resource).includes(caseRef));
53
+ const now = new Date().toISOString();
54
+ const closed = [];
55
+ for (const resource of open) {
56
+ const { stored } = await storeResources([resource], {
57
+ merge: (prior) => (OPEN_STATUSES.has(prior.status) ? { ...prior, ...closedFields(prior, { closeReason, resolving }, now) } : prior),
58
+ });
59
+ closed.push(...stored);
60
+ }
61
+ return { closed };
62
+ }
63
+
15
64
  async function readRoutingDecisions({ patientId, turnId = null }) {
16
65
  const store = getFhirStore();
17
66
  const patient = `Patient/${fhirId(patientId)}`;
@@ -31,6 +80,7 @@ async function readRoutingDecisions({ patientId, turnId = null }) {
31
80
  }
32
81
 
33
82
  module.exports = {
83
+ closeRoutingDispositions,
34
84
  storeRoutingDecision,
35
85
  readRoutingDecisions,
36
86
  };
@@ -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.30",
3
+ "version": "5.71.32",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",