@peopl-health/nexus 6.5.0-dev.19149 → 6.5.0-dev.20073

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/lib/clinical/AssistantProcessor.js +3 -1
  2. package/lib/clinical/config/planTextsConfig.js +41 -0
  3. package/lib/clinical/flags/escalationFlags.js +15 -0
  4. package/lib/clinical/helpers/doctorPlanHelper.js +32 -23
  5. package/lib/clinical/helpers/legacyContextHelper.js +6 -2
  6. package/lib/clinical/helpers/planTextHelper.js +9 -2
  7. package/lib/clinical/protocols/treatmentFormulary.js +3 -3
  8. package/lib/clinical/services/bridgeService.js +2 -2
  9. package/lib/clinical/services/checkInDueService.js +3 -2
  10. package/lib/clinical/services/clinicalAirtableService.js +3 -2
  11. package/lib/clinical/services/clinicalExtractionService.js +9 -2
  12. package/lib/clinical/services/contingencyDispatchService.js +8 -4
  13. package/lib/clinical/services/doctorPlanService.js +27 -11
  14. package/lib/clinical/tools/deliverPatientMessageTool.js +1 -1
  15. package/lib/clinical/tools/getPatientRiskAssessmentTool.js +1 -1
  16. package/lib/clinical/tools/getRouterContextBundleTool.js +1 -1
  17. package/lib/clinical/tools/reportMedicalEscalationTool.js +1 -0
  18. package/lib/clinical/tools/schedulePatientReminderTool.js +10 -1
  19. package/lib/config/awsConfig.js +1 -1
  20. package/lib/controllers/assistantController.js +5 -2
  21. package/lib/controllers/escalationReviewController.js +16 -3
  22. package/lib/controllers/messageController.js +5 -6
  23. package/lib/core/NexusMessaging.js +16 -18
  24. package/lib/fhir/constants/escalationCaseStatus.js +1 -1
  25. package/lib/helpers/caregiverHelper.js +8 -0
  26. package/lib/helpers/templateFlowControllerHelper.js +9 -48
  27. package/lib/index.d.ts +3 -3
  28. package/lib/models/escalationReviewModel.js +32 -2
  29. package/lib/services/assistantMessageService.js +11 -6
  30. package/lib/services/caseFollowUpService.js +226 -0
  31. package/lib/services/caseFollowUpSweepService.js +89 -0
  32. package/lib/services/characterizationOutcomeService.js +25 -9
  33. package/lib/services/escalationCaseStateService.js +68 -0
  34. package/lib/services/escalationReviewService.js +90 -27
  35. package/lib/services/flowDataExchangeService.js +6 -35
  36. package/lib/services/reviewAlertSweepService.js +19 -1
  37. package/lib/services/reviewBoardService.js +24 -6
  38. package/lib/services/reviewDeadlineService.js +1 -1
  39. package/lib/services/untakenAlertService.js +9 -7
  40. package/lib/services/watchExpiryService.js +162 -0
  41. package/lib/utils/textMatchUtils.js +52 -18
  42. package/package.json +1 -1
@@ -163,6 +163,7 @@ class AssistantProcessor {
163
163
  traceId: ctx?.trace?._id ? String(ctx.trace._id) : null,
164
164
  shouldContinue: runOptions.shouldContinue,
165
165
  sendMessage: this.sendMessage,
166
+ ...(runOptions.contactCode && { contactCode: runOptions.contactCode, contactRole: runOptions.contactRole }),
166
167
  });
167
168
  return bridgeDecision;
168
169
  };
@@ -294,6 +295,7 @@ class AssistantProcessor {
294
295
  outreachCarrier: runOptions.outreachCarrier || null,
295
296
  outreachStartedAt: runOptions.outreachStartedAt || null,
296
297
  triggeredBy: runOptions.triggeredBy || null,
298
+ ...(runOptions.contactCode && { contactCode: runOptions.contactCode, contactRole: runOptions.contactRole }),
297
299
  run,
298
300
  predictionTimeMs,
299
301
  retries: runResult?.retries || 0,
@@ -395,7 +397,7 @@ class AssistantProcessor {
395
397
  const outreachCarrier = result.outreachCarrier
396
398
  ? { ...result.outreachCarrier, utilityBasis: result.signals?.outreachDecision?.utilityBasis || result.outreachCarrier.utilityBasis || null }
397
399
  : null;
398
- sent = await this.sendMessage({ code, body: result.output, processed: true, origin: 'assistant', tools_executed: result.tools_executed, prompt: result.prompt, preset: result.preset, response_id: result.response_id, turnId: result.turnId, traceId: result.traceId, triggeredBy: result.triggeredBy, preemptiveWindowRoute: result.preemptiveWindowRoute, outreachCarrier, outreachStartedAt: result.outreachStartedAt });
400
+ sent = await this.sendMessage({ code, body: result.output, processed: true, origin: 'assistant', tools_executed: result.tools_executed, prompt: result.prompt, preset: result.preset, response_id: result.response_id, turnId: result.turnId, traceId: result.traceId, triggeredBy: result.triggeredBy, preemptiveWindowRoute: result.preemptiveWindowRoute, outreachCarrier, outreachStartedAt: result.outreachStartedAt, ...(result.contactCode && { contactCode: result.contactCode, contactRole: result.contactRole }) });
399
401
  result.delivery = sent || null;
400
402
  } catch (error) {
401
403
  if (directive) {
@@ -0,0 +1,41 @@
1
+ const { PLAN_TEXTS } = require('../helpers/doctorPlanHelper');
2
+ const { Config_ID } = require('../../config/airtableConfig');
3
+
4
+ const { getRecordByFilter } = require('../../services/airtableService');
5
+
6
+ const { logger } = require('../../utils/logger');
7
+ const { MapCache } = require('../../utils/MapCache');
8
+
9
+ const PLAN_TEXTS_TABLE = 'plan_instructions';
10
+ const CACHE_TTL = 5 * 60 * 1000;
11
+ const CACHE_KEY = 'planTexts';
12
+ const NEEDS_HOURS = ['FOLLOW_UP_CHECK_IN', 'FOLLOW_UP_VIGILANCIA'];
13
+
14
+ const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL });
15
+
16
+ // A missing, empty or broken row keeps the code's text, so an edit in Airtable never stops a plan from going out.
17
+ async function getPlanTexts() {
18
+ const cached = cache.get(CACHE_KEY);
19
+ if (cached) return cached;
20
+
21
+ let records = null;
22
+ try {
23
+ records = await getRecordByFilter(Config_ID, PLAN_TEXTS_TABLE, 'TRUE()');
24
+ } catch (error) {
25
+ logger.error('[planTextsConfig] plan_instructions could not be read; using the default texts', { error: error.message });
26
+ }
27
+ const byKey = Object.fromEntries((records || []).map((record) => [record.config, typeof record.value === 'string' ? record.value.trim() : '']));
28
+ const texts = Object.fromEntries(Object.entries(PLAN_TEXTS).map(([key, fallback]) => {
29
+ const value = byKey[key];
30
+ if (!value) return [key, fallback];
31
+ if (NEEDS_HOURS.includes(key) && !value.includes('{horas}')) {
32
+ logger.error('[planTextsConfig] follow-up text lacks {horas}; using the default', { key });
33
+ return [key, fallback];
34
+ }
35
+ return [key, value];
36
+ }));
37
+ if (records) cache.set(CACHE_KEY, texts);
38
+ return texts;
39
+ }
40
+
41
+ module.exports = { getPlanTexts, _clearPlanTextsCache: () => cache.clear() };
@@ -32,12 +32,27 @@ function escalationUntakenAlertsLive() {
32
32
  return flagNotOff('ESCALATION_UNTAKEN_ALERTS_LIVE');
33
33
  }
34
34
 
35
+ function escalationWatchExpiryLive() {
36
+ return flagNotOff('ESCALATION_WATCH_EXPIRY_LIVE');
37
+ }
38
+
39
+ function escalationWatchTeamNoticeLive() {
40
+ return flagOn('ESCALATION_WATCH_TEAM_NOTICE_LIVE');
41
+ }
42
+
43
+ function escalationCaseFollowUpLive() {
44
+ return flagNotOff('ESCALATION_CASE_FOLLOW_UP_LIVE');
45
+ }
46
+
35
47
  module.exports = {
48
+ escalationCaseFollowUpLive,
36
49
  escalationApproverAlertLive,
37
50
  escalationAssessmentLive,
38
51
  escalationAutoHandoffLive,
39
52
  escalationPatientTimerLive,
40
53
  escalationUntakenAlertsLive,
41
54
  escalationUpdateModeLive,
55
+ escalationWatchExpiryLive,
56
+ escalationWatchTeamNoticeLive,
42
57
  feverPatientTimerLive,
43
58
  };
@@ -2,47 +2,55 @@ const { oneLineOf } = require('../../utils/coercionUtils');
2
2
  const { normalizeForAnchor } = require('../../utils/textMatchUtils');
3
3
  const { findDrug, formularyFor } = require('../protocols/treatmentFormulary');
4
4
 
5
- const DEFAULT_FOLLOW_UP_HOURS = Object.freeze({ check_in: 24, vigilancia: 48 });
5
+ const DEFAULT_FOLLOW_UP_HOURS = Object.freeze({ auto: 24, check_in: 24, vigilancia: 48 });
6
6
 
7
7
  const needsPrescriber = (plan) => plan.items.length > 0 || plan.studies.length > 0;
8
8
 
9
+ const DURATION_TEXTS = Object.freeze({ as_needed: 'solo si lo necesita', continuous: 'de forma continua, hasta nuevo aviso', unspecified: null });
9
10
  const daysText = (days) => (days === 1 ? '1 día' : `${days} días`);
10
- const itemLine = (item) => `${[item.drug, item.strength].filter(Boolean).join(' ')}: ${item.dose} ${item.frequency} por ${daysText(item.days)}.`;
11
+ const SAID_DURATION = Object.freeze({ as_needed: /raz[oó]n necesaria|si lo necesita/i, continuous: /forma continua/i });
12
+ const durationTextOf = (item) => {
13
+ if (!item.duration || item.duration === 'days') return `por ${daysText(item.days)}`;
14
+ return SAID_DURATION[item.duration]?.test(`${item.dose ?? ''} ${item.frequency ?? ''}`) ? null : DURATION_TEXTS[item.duration];
15
+ };
16
+ const itemLine = (item) => `${[item.drug, item.strength].filter(Boolean).join(' ')}: ${[item.dose, item.frequency, durationTextOf(item)].filter(Boolean).join(' ')}.`;
11
17
  const studyLine = (study) => `${study.name}${study.instructions ? `: ${study.instructions}` : ''}.`;
12
- const PRESCRIPTION_LINE = 'Justo después de tu mensaje le llega aparte la receta del médico en PDF; dile que la va a recibir.';
18
+ // The defaults for the plan_instructions rows of the Config base; {horas} is filled with the follow-up hours.
19
+ const PLAN_TEXTS = Object.freeze({
20
+ INTRO: 'Transmítele al paciente lo que indicó el médico, con tus palabras: no agregues medicamentos ni estudios que el médico no indicó, ni avisos de urgencia que no dio.',
21
+ MEDS_HEADER: 'Medicamentos (no cambies dosis, frecuencia ni días; escríbelos con números, como vienen aquí, sin repetirlos con letra):',
22
+ // Written without numbers so the reply check, which flags any amount or hour the plan lacks, stays quiet.
23
+ COMPLEMENTARY: 'Indicaciones complementarias: además de lo anterior, por cada síntoma que contó dale de 2 a 4 cuidados en casa concretos, accionables y de alto valor, diciendo qué hacer y cómo hacerlo, aunque el médico no los haya escrito. Escríbelos con palabras, sin números, cantidades ni frecuencias y sin avisos de urgencia, para que no se confundan con lo que indicó el médico. Solo medidas estándar de enfermería oncológica: sin medicamentos, suplementos, remedios caseros ni dietas restrictivas.',
24
+ FOLLOW_UP_CHECK_IN: 'Seguimiento: le escribiremos en unas {horas} horas para ver cómo va.',
25
+ FOLLOW_UP_VIGILANCIA: 'Seguimiento: queda en vigilancia las próximas {horas} horas; le escribiremos para ver cómo va.',
26
+ });
13
27
 
14
- const FOLLOW_UP_LINES = {
15
- check_in: (hours) => `Seguimiento: le escribiremos en unas ${hours} horas para ver cómo va.`,
16
- vigilancia: (hours) => `Seguimiento: queda en vigilancia las próximas ${hours} horas; le escribiremos para ver cómo va.`,
17
- };
18
- const followUpLineOf = (plan) => FOLLOW_UP_LINES[plan.followUp?.kind]?.(plan.followUp.hours) ?? null;
28
+ const FOLLOW_UP_KEYS = { auto: 'FOLLOW_UP_CHECK_IN', check_in: 'FOLLOW_UP_CHECK_IN', vigilancia: 'FOLLOW_UP_VIGILANCIA' };
29
+ const followUpLineOf = (plan, texts = PLAN_TEXTS) => texts[FOLLOW_UP_KEYS[plan.followUp?.kind]]?.replaceAll('{horas}', plan.followUp.hours) ?? null;
19
30
 
20
- function planInstructions(plan) {
21
- const lines = ['Transmítele al paciente lo que indicó el médico, con tus palabras: no cambies dosis, frecuencia ni días, y no agregues otros medicamentos ni estudios. Escribe dosis, horas y días con números, como vienen aquí, sin repetirlos con letra, y no agregues avisos de urgencia que el médico no dio.'];
31
+ function planInstructions(plan, texts = PLAN_TEXTS) {
32
+ const lines = [texts.INTRO];
22
33
  if (plan.items.length) {
23
- lines.push('Medicamentos:', ...plan.items.map((item) => `- ${itemLine(item)}`));
34
+ lines.push(texts.MEDS_HEADER, ...plan.items.map((item) => `- ${itemLine(item)}`));
24
35
  }
25
36
  if (plan.studies.length) {
26
37
  lines.push('Estudios:', ...plan.studies.map((study) => `- ${studyLine(study)}`));
27
38
  }
28
39
  if (plan.homeCare.length) lines.push('Cuidados en casa:', ...plan.homeCare.map((entry) => `- ${entry}`));
29
40
  if (plan.note) lines.push(`Nota del médico: «${plan.note}».`);
30
- const followUp = followUpLineOf(plan);
41
+ lines.push(texts.COMPLEMENTARY);
42
+ const followUp = followUpLineOf(plan, texts);
31
43
  if (followUp) lines.push(followUp);
32
- if (needsPrescriber(plan)) lines.push(PRESCRIPTION_LINE);
33
44
  return lines.join('\n');
34
45
  }
35
46
 
36
- // An edit can drop or reword the receta line; the PDF goes out anyway, so the assistant is still told.
37
- function assistantInstructionsOf(plan) {
38
- if (!needsPrescriber(plan) || normalizeForAnchor(plan.instructions).includes(normalizeForAnchor(PRESCRIPTION_LINE))) return plan.instructions;
39
- return `${plan.instructions}\n${PRESCRIPTION_LINE}`;
40
- }
41
-
42
47
  function planSummary(plan) {
43
48
  const lines = [...plan.items.map(itemLine), ...plan.studies.map((study) => `Estudio: ${studyLine(study)}`)];
44
49
  if (plan.homeCare.length) lines.push(`Cuidados en casa: ${plan.homeCare.join('; ')}.`);
45
50
  if (plan.note) lines.push(`Nota: ${plan.note}`);
51
+ if (plan.followUp?.kind === 'auto') lines.push(`Seguimiento: automático, unas ${plan.followUp.hours} h.`);
52
+ if (plan.followUp?.kind === 'check_in') lines.push(`Seguimiento: check-in en ${plan.followUp.hours} h.`);
53
+ if (plan.followUp?.kind === 'vigilancia') lines.push(`Seguimiento: vigilancia ${plan.followUp.hours} h.`);
46
54
  return lines.join('\n');
47
55
  }
48
56
 
@@ -56,8 +64,9 @@ function prescriptionText(plan) {
56
64
  function dosingOf(item, formularyKey) {
57
65
  const entry = formularyFor(formularyKey);
58
66
  const dosing = entry && findDrug(entry, item)?.dosing;
59
- if (!dosing) return { dose: oneLineOf(item.instructions) || null, frequency: null, days: null, note: null };
60
- return { dose: dosing.dose ?? null, frequency: dosing.frequency ?? null, days: dosing.days ?? null, note: dosing.note ?? null };
67
+ if (!dosing) return { dose: oneLineOf(item.instructions) || null, frequency: null, duration: 'days', days: null, note: null };
68
+ const duration = dosing.duration ?? 'days';
69
+ return { dose: dosing.dose ?? null, frequency: dosing.frequency ?? null, duration, days: duration === 'days' ? dosing.days ?? null : null, note: dosing.note ?? null };
61
70
  }
62
71
 
63
72
  // What the formulary adds after the dosing («además, valoración por oftalmología») goes to the note.
@@ -78,7 +87,7 @@ function proposedPlanOf(draft) {
78
87
 
79
88
  // The note and home care count, so what the doctor wrote anywhere in the plan is never flagged.
80
89
  const plannedTextOf = (plan) => [
81
- ...plan.items.flatMap((item) => [item.drug, item.strength, item.dose, item.frequency, item.days && `por ${item.days} dias`]),
90
+ ...plan.items.flatMap((item) => [item.drug, item.strength, item.dose, item.frequency, durationTextOf(item)]),
82
91
  ...plan.studies.flatMap((study) => [study.name, study.instructions]),
83
92
  ...plan.homeCare,
84
93
  plan.note,
@@ -87,7 +96,7 @@ const plannedTextOf = (plan) => [
87
96
 
88
97
  module.exports = {
89
98
  DEFAULT_FOLLOW_UP_HOURS,
90
- assistantInstructionsOf,
99
+ PLAN_TEXTS,
91
100
  needsPrescriber,
92
101
  planInstructions,
93
102
  planSummary,
@@ -40,6 +40,9 @@ const SENTINELS = [
40
40
  /^no (he recibido|tengo) (alguno|ningun[oa])( mas)?$/,
41
41
  ];
42
42
 
43
+ // A bare «Sí» to the allergy question says there is one, so it stays as an unnamed allergy.
44
+ const UNNAMED_ALLERGY = 'Alergia a medicamentos referida, sin especificar';
45
+
43
46
  const clean = (s) => sanitizeInlineText(s, Infinity);
44
47
  const fold = (s) => foldAccents(clean(s)).toLowerCase().replace(/[.;,]+$/, '');
45
48
  const isSentinel = (s) => SENTINELS.some((re) => re.test(fold(s)));
@@ -73,8 +76,9 @@ function candidatesFor(record) {
73
76
  // 394 patients hold both keys; written separately the second arbitrates the first into `alternates`.
74
77
  const perVariable = new Map();
75
78
  for (const [key, variableId] of Object.entries(FIELD_MAP)) {
76
- const value = clean(clinical[key]);
77
- if (!value) continue;
79
+ const written = clean(clinical[key]);
80
+ if (!written) continue;
81
+ const value = key === 'alergias_medicamentos' && fold(written) === 'si' ? UNNAMED_ALLERGY : written;
78
82
  if (isSentinel(value)) { out.sentinels[key] = (out.sentinels[key] || 0) + 1; continue; }
79
83
  const bucket = perVariable.get(variableId) || [];
80
84
  if (bucket.some((held) => fold(held) === fold(value))) continue;
@@ -98,9 +98,16 @@ const numbersOf = (text) => new Set([...text.matchAll(NUMBER)].map(([number]) =>
98
98
  // Every number in the text, after the same spelling as dosingFactsOf.
99
99
  const allNumbersOf = (text) => numbersOf(dosingTextOf(String(text ?? '').replace(LIST_MARKER, '$1$2')));
100
100
 
101
+ // «un»/«una» before a word that is not a dose, a span or a count («una compresa fría») is an article; «toma una cada 8 horas» counts.
102
+ const COUNT_FOLLOWS = `${COUNTED_FORMS}|gota|${OTHER_FORMS}|${UNITS_SOURCE}|horas?|dias?|semanas?|mes(?:es)?|minutos?|ve(?:z|ces)|dosis|toma|cada|al|a|por|o|u|y|sola|mas|extra|adicional|en|de|diaria|diario`;
103
+ const ARTICLE = new RegExp(`\\b(?:un|una)\\s+(?=[a-z])(?!(?:${COUNT_FOLLOWS})\\b)`, 'g');
104
+ // What makes a sentence about a dose, a study or the follow-up rather than home care.
105
+ const DOSING_WORDS = new RegExp(`\\b(?:${COUNTED_FORMS}|gota|${OTHER_FORMS}|${UNITS_SOURCE}|dosis|medicamentos?|medicinas?|receta|ayun\\w*|estudios?|analisis|laboratorio|cita|consulta|contact\\w*|escrib\\w*|seguimiento|vigilancia)\\b`);
106
+ const isDosingSentence = (text) => DOSING_WORDS.test(folded(text));
107
+
101
108
  // The numbers left once the hours, days and amounts dosingFactsOf reads are taken out: what no pattern explains.
102
109
  function looseNumbersOf(text) {
103
- const dosing = dosingTextOf(String(text ?? '').replace(LIST_MARKER, '$1$2'));
110
+ const dosing = dosingTextOf(folded(String(text ?? '')).replace(LIST_MARKER, '$1$2').replace(ARTICLE, ''));
104
111
  return numbersOf([...NOT_DOSING, HOURS, DAYS, AMOUNTS, URGENCY_WORDS].reduce((rest, pattern) => rest.replace(pattern, ' '), dosing));
105
112
  }
106
113
 
@@ -111,4 +118,4 @@ function urgencyWordsIn(text) {
111
118
  .map((match) => match[1]));
112
119
  }
113
120
 
114
- module.exports = { allNumbersOf, dosingFactsOf, drugNameOf, looseNumbersOf, urgencyWordsIn };
121
+ module.exports = { allNumbersOf, dosingFactsOf, drugNameOf, isDosingSentence, looseNumbersOf, urgencyWordsIn };
@@ -96,7 +96,7 @@ const TREATMENT_FORMULARY = deepFreeze([
96
96
  {
97
97
  drug: 'Butilhioscina/metamizol', brand: 'BUSCAPINA COMPUESTA', strength: '10/250 mg', position: 'ALT', tableLabel: 'Coadyuvante', class: 'antiespasmodico',
98
98
  instructions: '1 tableta cada 8 a 12 horas por razón necesaria',
99
- dosing: { dose: '1 tableta', frequency: 'cada 8 a 12 horas por razón necesaria' },
99
+ dosing: { dose: '1 tableta', frequency: 'cada 8 a 12 horas por razón necesaria', duration: 'as_needed' },
100
100
  contextNote: 'Coadyuvante para cólico, no tratamiento de la diarrea',
101
101
  },
102
102
  ],
@@ -256,12 +256,12 @@ const TREATMENT_FORMULARY = deepFreeze([
256
256
  {
257
257
  drug: 'Urea', brand: 'NUTRAPLUS', strength: '10%', position: '1L', tableLabel: '1L, especialmente HFS/hiperqueratosis', class: 'queratolitico',
258
258
  instructions: 'capa fina cada 12 horas de forma continua',
259
- dosing: { dose: 'capa fina', frequency: 'cada 12 horas de forma continua' },
259
+ dosing: { dose: 'capa fina', frequency: 'cada 12 horas de forma continua', duration: 'continuous' },
260
260
  },
261
261
  {
262
262
  drug: 'Ceramidas', brand: 'CERAVE', strength: null, position: '1L', tableLabel: '1L emoliente', class: 'emoliente',
263
263
  instructions: '2 a 3 veces al día de forma continua',
264
- dosing: { dose: '2 a 3 veces al día de forma continua' }, isPharmacological: false,
264
+ dosing: { dose: '2 a 3 veces al día de forma continua', duration: 'continuous' }, isPharmacological: false,
265
265
  },
266
266
  { drug: 'Emoliente', brand: 'EUCERIN', strength: null, position: '1L', tableLabel: '1L emoliente', class: 'emoliente', isPharmacological: false },
267
267
  { drug: 'Vaselina/petrolato', strength: null, position: '1L', tableLabel: '1L barrera', class: 'barrera_cutanea', isPharmacological: false },
@@ -32,7 +32,7 @@ function buildDedupNote(bridgeText) {
32
32
  'clínico. El mensaje final es la SEGUNDA burbuja que verá el paciente, no la primera.';
33
33
  }
34
34
 
35
- function maybeSendBridge({ bridgeText = null, hasToolCalls, deliveryOnly = false, code, turnId = null, traceId = null, shouldContinue, sendMessage }) {
35
+ function maybeSendBridge({ bridgeText = null, hasToolCalls, deliveryOnly = false, code, turnId = null, traceId = null, shouldContinue, sendMessage, contactCode = null, contactRole = null }) {
36
36
  const authored = typeof bridgeText === 'string' && bridgeText.trim() ? bridgeText : null;
37
37
 
38
38
  if (!isBridgeEnabled()) return { sent: false, reason: 'disabled', proposed: Boolean(authored) };
@@ -67,7 +67,7 @@ function maybeSendBridge({ bridgeText = null, hasToolCalls, deliveryOnly = false
67
67
  if (entry.clearWhenDelivered && bridgeTimestamps.get(code) === entry) bridgeTimestamps.delete(code);
68
68
  };
69
69
  try {
70
- Promise.resolve(sendMessage({ code, body: text, processed: true, origin: 'assistant', raw: { bridge: true }, turnId, traceId }))
70
+ Promise.resolve(sendMessage({ code, body: text, processed: true, origin: 'assistant', raw: { bridge: true }, turnId, traceId, ...(contactCode && { contactCode, contactRole }) }))
71
71
  .then(delivered)
72
72
  .catch(failed);
73
73
  } catch (err) {
@@ -2,13 +2,13 @@ const moment = require('moment-timezone');
2
2
 
3
3
  const { TRIAGE_RESULT_MARKER } = require('../helpers/triageResultMessageHelper');
4
4
  const { getMessages } = require('../../services/messageService');
5
- const { replyContactFor } = require('../../helpers/caregiverHelper');
6
5
  const { isWithin24HourWindow } = require('../../helpers/conversationWindowHelper');
7
6
  const { checkInsPausedUntil } = require('../../services/threadService');
8
7
  const { DEFAULT_TIMEZONE, isWithinHourWindow } = require('../../utils/scheduleUtils');
9
8
  const { readRecommendationPlans } = require('../../fhir');
10
9
  const { ARMED_BY } = require('../../shared/dtos/ContingencySafetyNet');
11
10
  const { logger } = require('../../utils/logger');
11
+ const { isCaseFollowUpId, planCaseCheckIn } = require('../../services/caseFollowUpService');
12
12
  const { readActiveNets, escalationUrgencyOf, CHECK_IN_WINDOW } = require('./contingencyDispatchService');
13
13
  const { readPendingReminderForPatient, readPendingFollowUpsForPatient } = require('./clinicalAirtableService');
14
14
 
@@ -75,7 +75,7 @@ async function recentExchange(code, now) {
75
75
  lastMessage(code, now, false),
76
76
  lastMessage(code, now, true),
77
77
  getMessages({ numero: code, from_me: true, ...OWN_WRITTEN, createdAt: { $gte: startOfDay, $lt: now } }, { select: 'createdAt' }),
78
- replyContactFor(code).then((contact) => isWithin24HourWindow(code, { contactCode: contact?.contactCode || null })),
78
+ isWithin24HourWindow(code),
79
79
  ]);
80
80
  return { patient, own, ownMessagesToday: (ownToday || []).length, sessionOpen };
81
81
  }
@@ -181,6 +181,7 @@ async function planCheckInDue({ code, reminderId, type, question = '', firstName
181
181
  });
182
182
  }
183
183
 
184
+ if (isCaseFollowUpId(reminderId)) return planCaseCheckIn({ code, reminderId, firstName, now });
184
185
  const plan = await readPendingReminderForPatient({ code, reminderId });
185
186
  if (!plan) return { mode: 'stale', reason: 'plan_not_pending' };
186
187
  if (await checkInsPausedUntil(code, now)) return { mode: 'stale', reason: 'patient_paused' };
@@ -50,6 +50,7 @@ const REMINDER_TYPE_TO_AIRTABLE = {
50
50
  // of pending rows so the predicate cannot drift between them.
51
51
  const PENDING_ROW_FILTER = 'IF({is_active}, "true", "false") = "true", IF({is_sent}, "true", "false") = "false"';
52
52
  const ROUTINE_OUTREACH_FILTER = 'OR({type} = "seguimiento", LEFT({schedule_id}, 9) = "recovery_")';
53
+ const NOT_CASE_FOLLOW_UP = 'LEFT({schedule_id}, 14) != "case_followup_"';
53
54
  const RECOVERY_FILTER = 'LEFT({schedule_id}, 9) = "recovery_"';
54
55
  // `reminder` and `contingency` have no `source`; the lookup through the patient link carries it.
55
56
  const ROW_PROGRAM_FIELD = 'source (from patient_id)';
@@ -525,14 +526,14 @@ async function readPendingReminderForPatient({ code, reminderId }) {
525
526
  } : null;
526
527
  }
527
528
 
528
- async function cancelPendingFollowUps({ code, trace = null, reason = 'patient_replied', recoveryOnly = false }) {
529
+ async function cancelPendingFollowUps({ code, trace = null, reason = 'patient_replied', recoveryOnly = false, includeCaseFollowUp = false }) {
529
530
  return standDownRow({
530
531
  code,
531
532
  trace,
532
533
  table: 'reminder',
533
534
  planId: null,
534
535
  standDownReason: reason,
535
- filter: `AND(${patientRowsOf(code)}, ${recoveryOnly ? RECOVERY_FILTER : ROUTINE_OUTREACH_FILTER}, ${PENDING_ROW_FILTER})`,
536
+ filter: `AND(${patientRowsOf(code)}, ${recoveryOnly ? RECOVERY_FILTER : ROUTINE_OUTREACH_FILTER}, ${includeCaseFollowUp ? 'TRUE()' : NOT_CASE_FOLLOW_UP}, ${PENDING_ROW_FILTER})`,
536
537
  });
537
538
  }
538
539
 
@@ -3,7 +3,7 @@ const { getExtractor } = require('../config/subAgentsConfig');
3
3
  const { detectSafetyFlags } = require('../helpers/safetyFlagsHelper');
4
4
  const { buildExtractorInput, toClinicalMention } = require('../helpers/clinicalMentionHelper');
5
5
  const { readStructuredText } = require('../helpers/structuredTextHelper');
6
- const { isQuoteAnchored } = require('../../utils/textMatchUtils');
6
+ const { isQuoteAnchored, negationNearQuote } = require('../../utils/textMatchUtils');
7
7
  const { foldAccents } = require('../../utils/formatUtils');
8
8
  const { getClinicalContext } = require('../../helpers/patientInformationHelper');
9
9
  const { withTiming } = require('../../utils/tracingDecorator');
@@ -110,6 +110,7 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
110
110
  let unanchored = 0;
111
111
  let unusable = 0;
112
112
  let forcedPending = 0;
113
+ let polarityConflicts = 0;
113
114
  rawMentions.forEach((raw, index) => {
114
115
  if (!raw || typeof raw !== 'object') {
115
116
  unusable += 1;
@@ -126,10 +127,12 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
126
127
  return;
127
128
  }
128
129
  const quotes = mention.provenance.verbatimQuotes;
129
- if (!quotes.some((quote) => isQuoteAnchored(quote, text))) {
130
+ const negated = Boolean(mention.fact.assertion?.negated);
131
+ if (!quotes.some((quote) => isQuoteAnchored(quote, text, { negated }))) {
130
132
  unanchored += 1;
131
133
  return;
132
134
  }
135
+ if (!negated && quotes.every((quote) => negationNearQuote(quote, text))) polarityConflicts += 1;
133
136
  if (!mention.provenance.needsConfirmation && !endsNamedLine(raw, mention.fact)
134
137
  && namesNothingSpecific(mention.fact.canonicalTerm, vagueWords)) {
135
138
  forcedPending += 1;
@@ -148,10 +151,14 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
148
151
  if (forcedPending) {
149
152
  logger.warn('[clinicalExtraction] mentions held back: the term names no specific clinical entity', { turnId, forcedPending });
150
153
  }
154
+ if (polarityConflicts) {
155
+ logger.warn('[clinicalExtraction] mentions read as present despite a nearby negation', { turnId, polarityConflicts });
156
+ }
151
157
  trace?.setSignals?.({
152
158
  clinicalMentionsUnanchored: unanchored,
153
159
  clinicalMentionsPending: pendingMentions.length,
154
160
  clinicalMentionsForcedPending: forcedPending,
161
+ clinicalMentionsPolarityConflict: polarityConflicts,
155
162
  });
156
163
 
157
164
  const patientMentions = [...clinicalMentions, ...pendingMentions]
@@ -18,9 +18,9 @@ const MS_PER_HOUR = 60 * MS_PER_MINUTE;
18
18
  const EXPIRY_WINDOW_MULTIPLIER = 6;
19
19
  const EXPIRY_FLOOR_MS = 48 * MS_PER_HOUR;
20
20
  const EXPIRY_CEILING_MS = 14 * 24 * MS_PER_HOUR;
21
- const ESCALATION_SILENCE_MINUTES = { stat: null, asap: 60, urgent: 240 };
22
- // Nets armed before the change keep their level until they expire (stat 120, asap 180).
23
- const LEGACY_ESCALATION_SILENCE_MINUTES = { stat: 120, asap: 180 };
21
+ const ESCALATION_SILENCE_MINUTES = { stat: null, asap: 60, urgent: 120 };
22
+ // Urgent nets armed with the old 4 h window keep their level until they expire (48 h).
23
+ const LEGACY_ESCALATION_SILENCE_MINUTES = { urgent: 240 };
24
24
  const OPEN_CEILING_SILENCE_MINUTES = 720;
25
25
  const OPEN_CEILING_ORIGIN = 'open_ceiling';
26
26
  const OPEN_CEILING_CHECK_IN = 'Hola, quería saber cómo sigues. ¿Cómo va lo que me contaste?';
@@ -291,6 +291,10 @@ const supersedeForStat = ({ patientCode, trace, isLive }) => retireNets({
291
291
  patientCode, trace, isLive, select: (active) => active.filter((net) => isCeilingNet(net) || net?.carePlan?.armedBy === ARMED_BY.ESCALATION), context: 'for a stat escalation',
292
292
  });
293
293
 
294
+ const retireSilenceNets = ({ patientCode, trace = null }) => retireNets({
295
+ patientCode, trace, isLive: null, select: (active) => active.filter((net) => net?.carePlan?.armedBy === ARMED_BY.ESCALATION), context: 'after the doctor decided',
296
+ });
297
+
294
298
  function escalationUrgencyOf(net) {
295
299
  if (net?.carePlan?.armedBy !== ARMED_BY.ESCALATION) return null;
296
300
  const silence = net?.patientReminder?.firesAfterSilenceMinutes;
@@ -493,4 +497,4 @@ async function applyContingencyEvent({ patientCode, planId, stage, event, at = n
493
497
  return { applied: true, status: next, teamStageArmed: handoff.armed, ...(handoff.armed ? {} : { teamStageReason: handoff.reason }) };
494
498
  }
495
499
 
496
- module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
500
+ module.exports = { isSettledLadder, armContingency, cancelContingencies, snapshotContingencies, readActiveNets, escalationUrgencyOf, resolveContingency, autoResolveNets, computeExpiresAt, quietHoursShiftMinutes, stampContingencyPlan, teamWindowMinutes, teamDueAt, armEscalationNet, armOpenCeilingNet, applyContingencyEvent, retireSilenceNets, PATIENT_CONTACT_WINDOW, CHECK_IN_WINDOW };
@@ -1,9 +1,10 @@
1
1
  const { DEFAULT_FOLLOW_UP_HOURS, planInstructions, plannedTextOf } = require('../helpers/doctorPlanHelper');
2
- const { allNumbersOf, dosingFactsOf, looseNumbersOf, urgencyWordsIn } = require('../helpers/planTextHelper');
2
+ const { allNumbersOf, dosingFactsOf, isDosingSentence, looseNumbersOf, urgencyWordsIn } = require('../helpers/planTextHelper');
3
3
  const { httpError } = require('../../utils/httpErrorUtils');
4
4
  const { oneLineOf } = require('../../utils/coercionUtils');
5
- const { PLAN_FOLLOW_UPS } = require('../../models/escalationReviewModel');
6
- const { isDrugNamed, unplannedDrugsIn } = require('./treatmentProposalService');
5
+ const { PLAN_DURATIONS, PLAN_FOLLOW_UPS } = require('../../models/escalationReviewModel');
6
+ const { normalizeForAnchor } = require('../../utils/textMatchUtils');
7
+ const { drugsNamedIn, isDrugNamed, unplannedDrugsIn } = require('./treatmentProposalService');
7
8
 
8
9
  const FIRST_LINE = '1L';
9
10
  const MAX_ENTRIES = 10;
@@ -47,12 +48,16 @@ function itemOf(item, index) {
47
48
  const position = textOf(item?.position, `${name}.position`)?.toUpperCase() ?? null;
48
49
  const reason = textOf(item?.reason, `${name}.reason`);
49
50
  if (position && position !== FIRST_LINE && !reason) throw httpError(400, `${name}.reason is required for a drug that is not first line`);
51
+ if (item?.duration != null && !PLAN_DURATIONS.includes(item.duration)) throw httpError(400, `${name}.duration must be one of: ${PLAN_DURATIONS.join(', ')}`);
52
+ // Typed days win: a client that predates the duration field sends the proposal's duration back beside them.
53
+ const duration = item?.days != null ? 'days' : item?.duration ?? 'days';
50
54
  return {
51
55
  drug: neededText(item?.drug, `${name}.drug`),
52
56
  strength: textOf(item?.strength, `${name}.strength`),
53
57
  dose: neededText(item?.dose, `${name}.dose`),
54
58
  frequency: neededText(item?.frequency, `${name}.frequency`),
55
- days: wholeNumber(item?.days, `${name}.days`, MAX_DAYS),
59
+ duration,
60
+ days: duration === 'days' ? wholeNumber(item?.days, `${name}.days`, MAX_DAYS) : null,
56
61
  position,
57
62
  reason,
58
63
  formularyKey: textOf(item?.formularyKey, `${name}.formularyKey`),
@@ -82,27 +87,38 @@ function planOf(input) {
82
87
  note: textOf(input.note, 'plan.note', MAX_NOTE_LENGTH),
83
88
  followUp: followUpOf(input.followUp),
84
89
  };
85
- if (!plan.items.length && !plan.studies.length && !plan.homeCare.length && !plan.note) {
86
- throw httpError(400, 'plan needs a drug, a study, a home care measure or a note');
90
+ // A follow-up alone is a plan: the assistant adds its home care and the case stays open until the check-in.
91
+ if (!plan.items.length && !plan.studies.length && !plan.homeCare.length && !plan.note && plan.followUp.kind === 'none') {
92
+ throw httpError(400, 'plan needs a drug, a study, a home care measure, a note or a follow-up');
87
93
  }
88
94
  return plan;
89
95
  }
90
96
 
91
- function approvedInstructions(plan, edited) {
97
+ function approvedInstructions(plan, edited, texts) {
92
98
  if (edited != null && typeof edited !== 'string') throw httpError(400, 'instructions must be text');
93
- if (!edited?.trim()) return { instructions: planInstructions(plan), instructionsEdited: false };
99
+ if (!edited?.trim()) return { instructions: planInstructions(plan, texts), instructionsEdited: false };
94
100
  const instructions = edited.trim();
95
101
  if (instructions.length > MAX_INSTRUCTIONS_LENGTH) throw httpError(400, `instructions exceed ${MAX_INSTRUCTIONS_LENGTH} characters`);
96
- return { instructions, instructionsEdited: instructions !== planInstructions(plan) };
102
+ return { instructions, instructionsEdited: instructions !== planInstructions(plan, texts) };
97
103
  }
98
104
 
99
105
  const strays = (said, planned) => [...said].filter((value) => !planned.has(value));
100
106
  const everyOf = (hours) => (hours < 1 ? `cada ${Math.round(hours * 60)} minutos` : `cada ${hours} horas`);
101
107
 
108
+ // With no drug in the plan, only sentences about a dose, a study or the follow-up are read for numbers: home care may count gargles.
109
+ function checkedTextOf(plan, reply, planned) {
110
+ if (plan.items.length || drugsNamedIn(planned).length) return reply;
111
+ const studies = plan.studies.map((study) => normalizeForAnchor(study.name)).filter(Boolean);
112
+ return String(reply).split(/(?<=[.!?;:])\s+|\n+/)
113
+ .filter((sentence) => isDosingSentence(sentence) || drugsNamedIn(sentence).length || studies.some((name) => normalizeForAnchor(sentence).includes(name)))
114
+ .join('\n');
115
+ }
116
+
102
117
  function replyIssues(plan, reply) {
103
118
  if (!oneLineOf(reply)) return ['no se pudo leer el mensaje enviado'];
104
119
  const planned = plannedTextOf(plan);
105
- const said = dosingFactsOf(reply);
120
+ const checked = checkedTextOf(plan, reply, planned);
121
+ const said = dosingFactsOf(checked);
106
122
  const allowed = dosingFactsOf(planned);
107
123
  const issues = plan.items.filter((item) => !isDrugNamed(reply, item.drug)).map((item) => `no menciona ${item.drug}`);
108
124
  for (const hours of strays(said.hours, allowed.hours)) issues.push(`dice «${everyOf(hours)}», que no está en el plan`);
@@ -111,7 +127,7 @@ function replyIssues(plan, reply) {
111
127
  if (!allowed.amounts.has(amount)) issues.push(`dice «${written}», que no está en el plan`);
112
128
  }
113
129
  // A number no pattern reads («tómalo 5 días», «a las 10») still flags when the plan never names it.
114
- for (const number of strays(looseNumbersOf(reply), allNumbersOf(planned))) issues.push(`menciona «${number}», que no está en el plan`);
130
+ for (const number of strays(looseNumbersOf(checked), allNumbersOf(planned))) issues.push(`menciona «${number}», que no está en el plan`);
115
131
  for (const name of unplannedDrugsIn(reply, planned)) issues.push(`menciona ${name}, que el médico no indicó`);
116
132
  for (const word of strays(urgencyWordsIn(reply), urgencyWordsIn(planned))) issues.push(`usa «${word}», que el médico no indicó`);
117
133
  return issues;
@@ -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**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**When you relay what a doctor indicated:** name the doctor the team instruction names, even when it is not the `Médico tratante` of the clinical context. Saying the treating doctor reviewed the case when another doctor did tells the patient something false.\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 (`Indicación en cola`, `Indicaciones dadas`, `En vigilancia`).\n\n**When you relay what a doctor indicated:** name the doctor the team instruction names, even when it is not the `Médico tratante` of the clinical context. Saying the treating doctor reviewed the case when another doctor did tells the patient something false.\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',
@@ -5,7 +5,7 @@ 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; 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`, `plan_approved` = the doctor gave a structured plan, `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.',
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- `Indicación en cola`, `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`, `plan_approved` = the doctor gave a structured plan, `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: {
@@ -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; 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`, `plan_approved` = the doctor gave a structured plan, `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.',
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- `Indicación en cola`, `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`, `plan_approved` = the doctor gave a structured plan, `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: {
@@ -318,6 +318,7 @@ async function handler(args, context = {}) {
318
318
  const review = recordsAlarm
319
319
  ? await recordEscalationAlarm({
320
320
  code: runtime.patientCode,
321
+ mode: updateMode ? 'update' : 'new',
321
322
  alarm: {
322
323
  alarmId,
323
324
  urgencyLevel: requestedLevel,