@peopl-health/nexus 5.62.0 → 5.62.2

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.
@@ -2,6 +2,7 @@ const { Config_ID } = require('../../config/airtableConfig');
2
2
 
3
3
  const { getRecordByFilter } = require('../../services/airtableService');
4
4
 
5
+ const { logger } = require('../../utils/logger');
5
6
  const { MapCache } = require('../../utils/MapCache');
6
7
  const { safeParse, isPlainObject } = require('../../utils/jsonUtils');
7
8
 
@@ -67,9 +68,11 @@ async function load() {
67
68
  if (byKey.ESCALATION_NOTE_FACTS && !isPlainObject(parsedNoteFacts)) throw new Error('subAgents config ESCALATION_NOTE_FACTS is not a JSON object');
68
69
  const escalationNoteFacts = { ...ESCALATION_NOTE_FACTS_DEFAULTS, ...(parsedNoteFacts || {}) };
69
70
 
71
+ // SUPPORT_LIGHT drives an optional sweep, so a malformed row leaves it unconfigured instead of failing every sub-agent.
70
72
  const parsedSupportLight = safeParse(byKey.SUPPORT_LIGHT, null);
71
- if (byKey.SUPPORT_LIGHT && !isPlainObject(parsedSupportLight)) throw new Error('subAgents config SUPPORT_LIGHT is not a JSON object');
72
- const supportLight = { ...SUPPORT_LIGHT_DEFAULTS, ...(parsedSupportLight || {}) };
73
+ const isSupportLightValid = !byKey.SUPPORT_LIGHT || isPlainObject(parsedSupportLight);
74
+ if (!isSupportLightValid) logger.error('[subAgentsConfig] SUPPORT_LIGHT is not a JSON object; the support-light sweep stays unconfigured');
75
+ const supportLight = { ...SUPPORT_LIGHT_DEFAULTS, ...(isSupportLightValid ? parsedSupportLight || {} : {}) };
73
76
 
74
77
  const config = { EXTRACTOR: extractor, COMPOSER: composer, PATTERN_CONSULT: patternConsult, RISK_ASSESSMENT: riskAssessment, TRIAGE_GATE: triageGate, TRIAGE_PLAN: triagePlan, ESCALATION_DRAFT: escalationDraft, ESCALATION_QUESTIONS: escalationQuestions, ESCALATION_NOTE_FACTS: escalationNoteFacts, SUPPORT_LIGHT: supportLight };
75
78
  cache.set(CACHE_KEY, config);
@@ -0,0 +1,16 @@
1
+ const runtimeConfig = require('../../config/runtimeConfig');
2
+
3
+ const flagOn = (key) => String(runtimeConfig.get(key, 'false')).trim().toLowerCase() === 'true';
4
+
5
+ function escalationUpdateModeLive() {
6
+ return flagOn('ESCALATION_UPDATE_MODE_LIVE');
7
+ }
8
+
9
+ function escalationAssessmentLive() {
10
+ return flagOn('ESCALATION_ASSESSMENT_LIVE');
11
+ }
12
+
13
+ module.exports = {
14
+ escalationAssessmentLive,
15
+ escalationUpdateModeLive,
16
+ };
@@ -58,9 +58,11 @@ supportLightEventSchema.index({ patientId: 1, at: -1 });
58
58
 
59
59
  const supportLightSweepSchema = new mongoose.Schema({
60
60
  patientId: { type: String, required: true, unique: true },
61
- lastAttemptAt: { type: Date, required: true },
61
+ lastAttemptAt: { type: Date, default: null },
62
62
  lastEvaluatedAt: { type: Date, default: null },
63
63
  lastOutcome: { type: String, required: true },
64
+ claimedUntil: { type: Date, default: null },
65
+ claimToken: { type: String, default: null },
64
66
  }, { timestamps: true });
65
67
 
66
68
  function getSupportLightModel() {
@@ -224,13 +224,27 @@ async function rememberEmergency(code, recordId, urgencyFhir) {
224
224
  if (recordId && !isShadowRun()) await recentEmergencyCache.set(code, { recordId, urgencyFhir });
225
225
  }
226
226
 
227
- async function recordEmergency({ code, trace, symptom, suspectedCondition = '', recommendedAction = '', urgencyFhir = null, urgencyLevel = null, documentation = '', mergeWithRecent = true }) {
227
+ const emergencyWrites = new Map();
228
+
229
+ function serializedEmergencyWrite(code, write) {
230
+ const run = (emergencyWrites.get(code) || Promise.resolve()).then(write);
231
+ const settled = run.catch(() => null);
232
+ emergencyWrites.set(code, settled);
233
+ settled.then(() => { if (emergencyWrites.get(code) === settled) emergencyWrites.delete(code); });
234
+ return run;
235
+ }
236
+
237
+ function recordEmergency(params) {
238
+ return serializedEmergencyWrite(params.code, () => recordEmergencyNow(params));
239
+ }
240
+
241
+ async function recordEmergencyNow({ code, trace, symptom, suspectedCondition = '', recommendedAction = '', urgencyFhir = null, urgencyLevel = null, documentation = '', mergeWithRecent = true, anchor = null, keepOpenRow = false, onRecorded = null }) {
228
242
  const level = urgencyLevel || MEDICAL_URGENCY_TO_EMERGENCY_LEVEL[urgencyFhir] || 'Alta';
229
- const prior = mergeWithRecent ? (await recentEmergencyCache.get(code) || null) : null;
243
+ const prior = anchor?.recordId ? anchor : (mergeWithRecent ? (await recentEmergencyCache.get(code) || null) : null);
230
244
  const rank = EMERGENCY_URGENCY_RANK[urgencyFhir];
231
245
  const priorRank = prior ? EMERGENCY_URGENCY_RANK[prior.urgencyFhir] : undefined;
232
246
  const mergeable = Boolean(prior) && rank !== undefined && priorRank !== undefined && rank <= priorRank;
233
- const belowPrior = mergeable && rank < priorRank;
247
+ const belowPrior = mergeable && (rank < priorRank || keepOpenRow);
234
248
  const meta = {};
235
249
 
236
250
  return auditedWrite({
@@ -266,6 +280,7 @@ async function recordEmergency({ code, trace, symptom, suspectedCondition = '',
266
280
  meta.mergedInto = prior.recordId;
267
281
  if (belowPrior) meta.keptUrgencyFhir = prior.urgencyFhir;
268
282
  await rememberEmergency(code, prior.recordId, belowPrior ? prior.urgencyFhir : urgencyFhir);
283
+ onRecorded?.(prior.recordId);
269
284
  return updated;
270
285
  }
271
286
  }
@@ -274,6 +289,7 @@ async function recordEmergency({ code, trace, symptom, suspectedCondition = '',
274
289
  const created = await airtableService.addRecord(Monitoreo_ID, 'emergencies', [{ fields }], code);
275
290
  const record = Array.isArray(created) ? created[0] : created;
276
291
  await rememberEmergency(code, record?.id, mergeWithRecent ? urgencyFhir : null);
292
+ if (record?.id) onRecorded?.(record.id);
277
293
  return created;
278
294
  },
279
295
  });
@@ -1,3 +1,5 @@
1
+ const { randomUUID } = require('crypto');
2
+
1
3
  const { requireGatewayProvider } = require('../config/llmConfig');
2
4
  const { getSupportLightEvaluator } = require('../config/subAgentsConfig');
3
5
  const { getSupportLightSweepModel } = require('../models/supportLightModel');
@@ -16,16 +18,26 @@ const DEFAULT_WINDOW_DAYS = 14;
16
18
  const MAX_MESSAGES = 60;
17
19
  const MAX_PATIENT_MESSAGES = 20;
18
20
  const CANDIDATE_PAGE = 200;
21
+ const MAX_CANDIDATE_PAGES = 10;
22
+ const CLAIM_MINUTES = 15;
19
23
  const SETTLED_OUTCOMES = ['evaluated', 'no_messages'];
20
24
  const MAX_REASON_CHARS = 500;
21
25
  const MAX_EVIDENCE = 5;
22
26
  const INTERNAL_ORIGINS = ['system', 'instruction'];
27
+ const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
28
+ const DUPLICATE_KEY_ERROR = 11000;
29
+ const MINUTE_MS = 60 * 1000;
23
30
  const SERVICES = Object.keys(LIGHT_SCALE);
24
31
 
32
+ function speakerOf(message) {
33
+ if (message.from_me) return 'Equipo';
34
+ return message.contact_role === 'caregiver' ? 'Cuidador(a)' : 'Paciente';
35
+ }
36
+
25
37
  function transcriptOf(messages) {
26
38
  return messages.map((message, index) => {
27
39
  const at = new Date(message.createdAt).toISOString().slice(0, 16).replace('T', ' ');
28
- return `[${index}] ${at} ${message.from_me ? 'Equipo' : 'Paciente'}: ${String(message.body || '').trim()}`;
40
+ return `[${index}] ${at} ${speakerOf(message)}: ${String(message.body || '').trim()}`;
29
41
  }).join('\n');
30
42
  }
31
43
 
@@ -45,9 +57,10 @@ async function readRecentMessages(patientId, { now, windowDays, readMessages })
45
57
  numero: patientId,
46
58
  createdAt: { $gte: new Date(now.getTime() - windowDays * DAY_MS) },
47
59
  origin: { $nin: INTERNAL_ORIGINS },
60
+ 'statusInfo.status': { $nin: UNDELIVERED_STATUSES },
48
61
  body: { $regex: '\\S' },
49
62
  };
50
- const options = { sort: { createdAt: -1 }, select: '_id body from_me createdAt' };
63
+ const options = { sort: { createdAt: -1 }, select: '_id body from_me contact_role createdAt' };
51
64
  const [recent, fromPatient] = await Promise.all([
52
65
  readMessages(query, { ...options, limit: MAX_MESSAGES }),
53
66
  readMessages({ ...query, from_me: false }, { ...options, limit: MAX_PATIENT_MESSAGES }),
@@ -95,7 +108,7 @@ async function patientsToEvaluate({ now, cadenceHours, limit, scope, SweepModel
95
108
  const retrySince = new Date(now.getTime() - RETRY_HOURS * HOUR_MS);
96
109
  const numero = Array.isArray(scope) ? { $in: scope } : { $regex: '^whatsapp:\\+' };
97
110
  const selected = [];
98
- for (let page = 0; selected.length < limit; page += 1) {
111
+ for (let page = 0; selected.length < limit && page < MAX_CANDIDATE_PAGES; page += 1) {
99
112
  const active = await aggregateMessages([
100
113
  { $match: { from_me: false, createdAt: { $gte: since }, numero, origin: { $nin: INTERNAL_ORIGINS }, body: { $regex: '\\S' } } },
101
114
  { $group: { _id: '$numero', lastInboundAt: { $max: '$createdAt' } } },
@@ -107,7 +120,7 @@ async function patientsToEvaluate({ now, cadenceHours, limit, scope, SweepModel
107
120
  if (!ids.length) break;
108
121
  const recent = await SweepModel.find({
109
122
  patientId: { $in: ids },
110
- $or: [{ lastEvaluatedAt: { $gte: since } }, { lastAttemptAt: { $gte: retrySince } }],
123
+ $or: [{ lastEvaluatedAt: { $gte: since } }, { lastAttemptAt: { $gte: retrySince } }, { claimedUntil: { $gt: now } }],
111
124
  }).select('patientId').lean();
112
125
  const done = new Set(recent.map((row) => row.patientId));
113
126
  selected.push(...ids.filter((id) => !done.has(id)));
@@ -121,24 +134,72 @@ function validPatientIds(ids) {
121
134
  }
122
135
 
123
136
  function sweepState(outcome, now) {
124
- return { lastAttemptAt: now, lastOutcome: outcome, ...(SETTLED_OUTCOMES.includes(outcome) ? { lastEvaluatedAt: now } : {}) };
137
+ return {
138
+ lastAttemptAt: now, lastOutcome: outcome, claimedUntil: null, claimToken: null,
139
+ ...(SETTLED_OUTCOMES.includes(outcome) ? { lastEvaluatedAt: now } : {}),
140
+ };
141
+ }
142
+
143
+ function stillDue({ now, cadenceHours }) {
144
+ const since = new Date(now.getTime() - cadenceHours * HOUR_MS);
145
+ const retrySince = new Date(now.getTime() - RETRY_HOURS * HOUR_MS);
146
+ return [
147
+ { $or: [{ lastEvaluatedAt: null }, { lastEvaluatedAt: { $lt: since } }] },
148
+ { $or: [{ lastAttemptAt: null }, { lastAttemptAt: { $lt: retrySince } }] },
149
+ ];
150
+ }
151
+
152
+ async function claimPatient(SweepModel, patientId, clock, conditions = []) {
153
+ const at = clock();
154
+ const claimToken = randomUUID();
155
+ try {
156
+ const claimed = await SweepModel.findOneAndUpdate(
157
+ { patientId, $and: [{ $or: [{ claimedUntil: null }, { claimedUntil: { $lte: at } }] }, ...conditions] },
158
+ { $set: { claimedUntil: new Date(at.getTime() + CLAIM_MINUTES * MINUTE_MS), claimToken }, $setOnInsert: { lastOutcome: 'claimed' } },
159
+ { upsert: true, new: true },
160
+ );
161
+ return claimed ? claimToken : null;
162
+ } catch (error) {
163
+ if (error?.code === DUPLICATE_KEY_ERROR) return null;
164
+ throw error;
165
+ }
166
+ }
167
+
168
+ async function settleClaim(SweepModel, patientId, claimToken, update) {
169
+ try {
170
+ const settled = await SweepModel.updateOne({ patientId, claimToken }, { $set: update });
171
+ if (!settled?.matchedCount) logger.warn('[supportLightEvaluation] claim lost before its outcome was recorded', { code: patientId });
172
+ } catch (stateError) {
173
+ logger.error('[supportLightEvaluation] sweep state not recorded', { code: patientId, error: stateError.message });
174
+ }
125
175
  }
126
176
 
127
177
  async function runSupportLightSweep({
128
178
  now = new Date(), patientIds = null, scope = null, cadenceHours = DEFAULT_CADENCE_HOURS, windowDays = DEFAULT_WINDOW_DAYS, limit = 50,
129
- } = {}, { SweepModel = getSupportLightSweepModel(), evaluate = evaluatePatientSupport, ...deps } = {}) {
130
- const candidates = Array.isArray(patientIds)
179
+ } = {}, {
180
+ SweepModel = getSupportLightSweepModel(), evaluate = evaluatePatientSupport, getConfig = getSupportLightEvaluator,
181
+ clock = () => new Date(), ...deps
182
+ } = {}) {
183
+ const config = await getConfig();
184
+ if (!config?.presetId) return { evaluated: 0, partial: 0, skipped: 0, failed: 0, busy: 0, changes: [], outcome: 'not_configured' };
185
+ const isBackfill = Array.isArray(patientIds);
186
+ const candidates = isBackfill
131
187
  ? validPatientIds(patientIds).slice(0, limit)
132
188
  : await patientsToEvaluate({ now, cadenceHours, limit, scope: scope && validPatientIds(scope), SweepModel });
133
- const summary = { evaluated: 0, skipped: 0, failed: 0, changes: [] };
189
+ const evaluationDeps = { ...deps, getConfig: async () => config };
190
+ const summary = { evaluated: 0, partial: 0, skipped: 0, failed: 0, busy: 0, changes: [] };
134
191
  for (const patientId of candidates) {
192
+ const claimToken = await claimPatient(SweepModel, patientId, clock, isBackfill ? [] : stillDue({ now, cadenceHours }));
193
+ if (!claimToken) {
194
+ summary.busy += 1;
195
+ continue;
196
+ }
135
197
  let outcome = 'error';
136
198
  try {
137
- const result = await evaluate({ patientId, now, windowDays }, deps);
138
- if (result.outcome === 'not_configured') return { ...summary, outcome: 'not_configured' };
199
+ const result = await evaluate({ patientId, now, windowDays }, evaluationDeps);
139
200
  outcome = result.outcome;
140
201
  if (outcome === 'evaluated' || outcome === 'partial') {
141
- summary.evaluated += 1;
202
+ summary[outcome] += 1;
142
203
  summary.changes.push(...result.changes.map((change) => ({ patientId, ...change })));
143
204
  } else {
144
205
  summary.skipped += 1;
@@ -147,13 +208,9 @@ async function runSupportLightSweep({
147
208
  summary.failed += 1;
148
209
  logger.error('[supportLightEvaluation] patient evaluation failed', { code: patientId, error: error.message, stack: error.stack });
149
210
  }
150
- try {
151
- await SweepModel.updateOne({ patientId }, { $set: sweepState(outcome, now) }, { upsert: true });
152
- } catch (stateError) {
153
- logger.error('[supportLightEvaluation] sweep state not recorded', { code: patientId, error: stateError.message });
154
- }
211
+ await settleClaim(SweepModel, patientId, claimToken, sweepState(outcome, now));
155
212
  }
156
- return { ...summary, outcome: 'completed' };
213
+ return { ...summary, outcome: isBackfill && summary.busy ? 'incomplete' : 'completed' };
157
214
  }
158
215
 
159
216
  module.exports = { evaluatePatientSupport, runSupportLightSweep };
@@ -48,13 +48,14 @@ function registerClinicalTools() {
48
48
  unregisterTool(analyzeSymptomPatternsTool.definition.name);
49
49
  for (const tool of tools) unregisterTool(tool.definition.name);
50
50
  for (const tool of tools) {
51
+ const definition = tool.liveDefinition ? tool.liveDefinition() : tool.definition;
51
52
  registerTool({
52
- name: tool.definition.name,
53
- description: tool.definition.description,
54
- parameters: tool.definition.parameters,
55
- strict: tool.definition.strict,
56
- replayScope: tool.definition.replayScope,
57
- replayArgs: tool.definition.replayArgs,
53
+ name: definition.name,
54
+ description: definition.description,
55
+ parameters: definition.parameters,
56
+ strict: definition.strict,
57
+ replayScope: definition.replayScope,
58
+ replayArgs: definition.replayArgs,
58
59
  handler: tool.handler,
59
60
  });
60
61
  }
@@ -1,3 +1,5 @@
1
+ const { randomUUID } = require('crypto');
2
+
1
3
  const { MEDICATION_NAMING_RULE } = require('../helpers/medicationNamingRule');
2
4
  const { auditReasoningSchema } = require('../helpers/auditReasoningHelper');
3
5
  const { isShadowRun } = require('../helpers/shadowHelper');
@@ -5,7 +7,9 @@ const { evidenceQuoteAnchoring } = require('../helpers/evidenceAnchorHelper');
5
7
  const { dispatcherService } = require('../services/dispatcherService');
6
8
  const { armEscalationNet } = require('../services/contingencyDispatchService');
7
9
  const { recordEmergency, writeUnresolvedRequest } = require('../services/clinicalAirtableService');
8
- const { recordEscalationAlarm } = require('../../services/escalationReviewService');
10
+ const { escalationAssessmentLive, escalationUpdateModeLive } = require('../flags/escalationFlags');
11
+ const { attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
12
+ const { URGENCY_RANK } = require('../../models/escalationReviewModel');
9
13
  const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
10
14
  const { logger } = require('../../utils/logger');
11
15
 
@@ -134,6 +138,104 @@ const definition = {
134
138
  }
135
139
  };
136
140
 
141
+ const nullable = (schema) => ({ 'anyOf': [schema, { 'type': 'null' }] });
142
+ const nullableEnum = (values) => nullable({ 'type': 'string', 'enum': values });
143
+
144
+ const MODE_PROPERTY = {
145
+ 'type': 'string',
146
+ 'enum': ['new', 'update'],
147
+ 'description': '`new`: primer aviso de este episodio. `update`: agrega lo nuevo a la escalación que sigue abierta para este paciente, sin generar otro aviso al equipo si el nivel no sube. El nivel aplicado es el mayor entre el abierto y el que pides: uno menor no baja la escalación, queda registrado como sugerencia para el equipo. Usa `update` para sumar lo que respondió el paciente y para subir el nivel en cuanto un dato nuevo haga plausible algo más grave.',
148
+ };
149
+
150
+ const MODE_DESCRIPTION = '\n\n**mode:** `new` abre un aviso; `update` actualiza la escalación abierta y nunca baja su nivel. Lo que el paciente responde después de escalar va con `update`. El `urgency_level` del recibo es el nivel aplicado: puede ser mayor que el que pediste, nunca menor.';
151
+
152
+ const CLINICAL_ASSESSMENT_PROPERTY = nullable({
153
+ 'type': 'object',
154
+ 'description': 'Tu razonamiento clínico, estructurado para auditoría. Todos los campos aceptan `null`. No cambia el nivel: el nivel lo decides tú en `urgency_level`.',
155
+ 'properties': {
156
+ 'serious_hypotheses': nullable({
157
+ 'type': 'array',
158
+ 'items': {
159
+ 'type': 'object',
160
+ 'properties': {
161
+ 'label': { 'type': 'string' },
162
+ 'status': { 'type': 'string', 'enum': ['ruled_out', 'not_ruled_out', 'supported', 'unknown'] },
163
+ 'key_evidence': nullable({ 'type': 'string' }),
164
+ },
165
+ 'required': ['label', 'status', 'key_evidence'],
166
+ 'additionalProperties': false,
167
+ },
168
+ 'description': 'Cuadros graves que consideraste y en qué quedaron.',
169
+ }),
170
+ 'known_explanation': nullable({
171
+ 'type': 'object',
172
+ 'properties': {
173
+ 'present': nullable({ 'type': 'boolean' }),
174
+ 'plan_in_course': nullable({ 'type': 'boolean' }),
175
+ 'what': nullable({ 'type': 'string' }),
176
+ },
177
+ 'required': ['present', 'plan_in_course', 'what'],
178
+ 'additionalProperties': false,
179
+ 'description': 'Si el síntoma tiene una explicación conocida (cirugía, procedimiento, efecto esperado) y si ya hay un manejo indicado.',
180
+ }),
181
+ 'response_to_prior_management': nullableEnum(['complete', 'partial', 'none', 'worse', 'not_applicable', 'unknown']),
182
+ 'trajectory': nullableEnum(['better', 'same', 'worse', 'unknown']),
183
+ 'temporality': nullableEnum(['current', 'recent_resolved', 'past', 'unknown']),
184
+ 'missing_to_rule_out': nullable({ 'type': 'array', 'items': { 'type': 'string' }, 'description': 'Lo que falta preguntar para descartar lo grave.' }),
185
+ 'characterization_incomplete': nullable({ 'type': 'boolean', 'description': '`true` si el paciente dejó de responder antes de completar la caracterización.' }),
186
+ },
187
+ 'required': ['serious_hypotheses', 'known_explanation', 'response_to_prior_management', 'trajectory', 'temporality', 'missing_to_rule_out', 'characterization_incomplete'],
188
+ 'additionalProperties': false,
189
+ });
190
+
191
+ function liveDefinition() {
192
+ const updateMode = escalationUpdateModeLive();
193
+ const assessment = escalationAssessmentLive();
194
+ if (!updateMode && !assessment) return definition;
195
+ const live = structuredClone(definition);
196
+ const { properties, required } = live.parameters;
197
+ if (updateMode) {
198
+ live.description += MODE_DESCRIPTION;
199
+ properties.mode = MODE_PROPERTY;
200
+ required.push('mode');
201
+ }
202
+ if (assessment) {
203
+ properties.details.properties.clinical_assessment = CLINICAL_ASSESSMENT_PROPERTY;
204
+ properties.details.required.push('clinical_assessment');
205
+ }
206
+ return live;
207
+ }
208
+
209
+ const yesNo = (value) => (value === true ? 'sí' : value === false ? 'no' : null);
210
+
211
+ function knownExplanationNote(known) {
212
+ if (!isPlainObject(known)) return '';
213
+ const parts = [
214
+ yesNo(known.present) && `presente: ${yesNo(known.present)}`,
215
+ known.what,
216
+ yesNo(known.plan_in_course) && `manejo en curso: ${yesNo(known.plan_in_course)}`,
217
+ ].filter(Boolean);
218
+ return parts.length ? `Explicación conocida: ${parts.join(', ')}` : '';
219
+ }
220
+
221
+ function assessmentNote(assessment) {
222
+ if (!isPlainObject(assessment)) return '';
223
+ const hypotheses = (Array.isArray(assessment.serious_hypotheses) ? assessment.serious_hypotheses : [])
224
+ .filter((hypothesis) => hypothesis?.label)
225
+ .map((hypothesis) => `${hypothesis.label} (${hypothesis.status || 'unknown'})`)
226
+ .join('; ');
227
+ const missing = Array.isArray(assessment.missing_to_rule_out) ? assessment.missing_to_rule_out.filter(Boolean).join('; ') : '';
228
+ return [
229
+ assessment.temporality && `Temporalidad: ${assessment.temporality}`,
230
+ assessment.trajectory && `Trayectoria: ${assessment.trajectory}`,
231
+ assessment.response_to_prior_management && `Respuesta al manejo: ${assessment.response_to_prior_management}`,
232
+ hypotheses && `Hipótesis graves: ${hypotheses}`,
233
+ knownExplanationNote(assessment.known_explanation),
234
+ missing && `Falta para descartar: ${missing}`,
235
+ yesNo(assessment.characterization_incomplete) && `Caracterización incompleta: ${yesNo(assessment.characterization_incomplete)}`,
236
+ ].filter(Boolean).join(' · ');
237
+ }
238
+
137
239
  function followUpNote(armed, reason) {
138
240
  if (armed) {
139
241
  return 'An automatic check-in is armed for this escalation: if the patient goes silent, they will be contacted again about it.';
@@ -148,6 +250,7 @@ function followUpNote(armed, reason) {
148
250
  }
149
251
 
150
252
  const CATEGORIES = definition.parameters.properties.details.properties.category.anyOf.find((v) => v.enum).enum;
253
+ const LEVELS = definition.parameters.properties.urgency_level.enum;
151
254
 
152
255
  async function handler(args, context = {}) {
153
256
  try {
@@ -157,10 +260,10 @@ async function handler(args, context = {}) {
157
260
  logger.error('[reportMedicalEscalation] Medical escalation dropped — no active turn trace', { patientCode: runtime?.patientCode || null });
158
261
  return JSON.stringify({ success: false, error: 'reportMedicalEscalation requires an active turn context (trace).' });
159
262
  }
160
- const levels = definition.parameters.properties.urgency_level.enum;
161
263
  const requested = (args?.urgency_level || '').trim().toLowerCase();
162
- const isCoerced = !levels.includes(requested);
163
- const urgencyLevel = isCoerced ? 'urgent' : requested;
264
+ const isCoerced = !LEVELS.includes(requested);
265
+ const requestedLevel = isCoerced ? 'urgent' : requested;
266
+ const updateMode = escalationUpdateModeLive() && args?.mode === 'update';
164
267
  const rawDetails = args?.details;
165
268
  const parsedDetails = objectArg(rawDetails);
166
269
  const details = parsedDetails || {};
@@ -168,19 +271,46 @@ async function handler(args, context = {}) {
168
271
  const requestedCategory = typeof rawCategory === 'string' ? rawCategory.trim() : rawCategory;
169
272
  const category = CATEGORIES.includes(requestedCategory) ? requestedCategory : null;
170
273
  const categoryCoerced = rawCategory !== null && category === null;
274
+ const clinicalAssessment = escalationAssessmentLive() && isPlainObject(details.clinical_assessment) ? details.clinical_assessment : null;
171
275
  const strictlyParsed = typeof rawDetails === 'string' && isPlainObject(safeParse(rawDetails, null));
172
276
  const detailsArg = typeof rawDetails === 'string'
173
277
  ? (parsedDetails ? (strictlyParsed ? 'decoded' : 'recovered') : 'unreadable')
174
278
  : (parsedDetails ? 'object' : 'absent');
175
279
  if (detailsArg === 'recovered') {
176
- logger.warn('[reportMedicalEscalation] details arrived as malformed JSON and was recovered from its balanced prefix', { turnId: runtime.turnId, urgencyLevel });
280
+ logger.warn('[reportMedicalEscalation] details arrived as malformed JSON and was recovered from its balanced prefix', { turnId: runtime.turnId, urgencyLevel: requestedLevel });
177
281
  }
178
282
  if (detailsArg === 'unreadable') {
179
- logger.error('[reportMedicalEscalation] details arrived as a string that is not valid JSON', { turnId: runtime.turnId, urgencyLevel });
283
+ logger.error('[reportMedicalEscalation] details arrived as a string that is not valid JSON', { turnId: runtime.turnId, urgencyLevel: requestedLevel });
180
284
  const justification = String(args?.urgency_justification || '').trim();
181
285
  if (justification) details.symptom = `Sin síntoma estructurado — ${justification}`;
182
286
  }
183
287
 
288
+ const alarmId = randomUUID();
289
+ const recordsAlarm = Boolean(runtime.patientCode) && requestedLevel !== 'routine' && !isShadowRun() && runtime.isLive?.() !== false;
290
+ const review = recordsAlarm
291
+ ? await recordEscalationAlarm({
292
+ code: runtime.patientCode,
293
+ alarm: {
294
+ alarmId,
295
+ urgencyLevel: requestedLevel,
296
+ category,
297
+ symptom: details.symptom || null,
298
+ evidenceQuote: details.evidence_quote || null,
299
+ suspectedCondition: details.suspected_condition || null,
300
+ recommendedAction: details.recommended_action || null,
301
+ justification: args?.urgency_justification || null,
302
+ indicators: (Array.isArray(details.indicators) ? details.indicators : [])
303
+ .filter((indicator) => typeof indicator === 'string' && indicator.trim()),
304
+ turnId: runtime.turnId || null,
305
+ ...(clinicalAssessment ? { clinicalAssessment } : {}),
306
+ },
307
+ })
308
+ : null;
309
+ const anchor = updateMode && review ? escalationAnchorOf(review, alarmId) : null;
310
+ const keptOpenLevel = Boolean(anchor) && (URGENCY_RANK[anchor.urgencyLevel] || 0) > (URGENCY_RANK[requestedLevel] || 0);
311
+ const urgencyLevel = keptOpenLevel ? anchor.urgencyLevel : requestedLevel;
312
+ const raisesOpen = !anchor || (URGENCY_RANK[requestedLevel] || 0) > (URGENCY_RANK[anchor.urgencyLevel] || 0);
313
+
184
314
  trace.setSafetyDecision({ ...(trace.safetyDecision || {}), escalationKind: 'medical_urgent' });
185
315
  trace.setSignals({
186
316
  medicalEscalation: {
@@ -199,10 +329,12 @@ async function handler(args, context = {}) {
199
329
  coercedUrgency: isCoerced,
200
330
  requestedUrgencyLevel: requested,
201
331
  detailsArg,
332
+ ...(updateMode ? { mode: 'update', openUrgencyLevel: anchor?.urgencyLevel || null, keptOpenLevel } : {}),
333
+ ...(clinicalAssessment ? { clinicalAssessment } : {}),
202
334
  },
203
335
  });
204
336
 
205
- if (runtime.turnId && runtime.patientCode) {
337
+ if (runtime.turnId && runtime.patientCode && raisesOpen) {
206
338
  try {
207
339
  await dispatcherService.dispatch({
208
340
  trace,
@@ -231,21 +363,7 @@ async function handler(args, context = {}) {
231
363
  });
232
364
  queued = written || duplicate;
233
365
  } else {
234
- if (!isShadowRun() && runtime.isLive?.() !== false) await recordEscalationAlarm({
235
- code: runtime.patientCode,
236
- alarm: {
237
- urgencyLevel,
238
- category,
239
- symptom: details.symptom || null,
240
- evidenceQuote: details.evidence_quote || null,
241
- suspectedCondition: details.suspected_condition || null,
242
- recommendedAction: details.recommended_action || null,
243
- justification: args?.urgency_justification || null,
244
- indicators: (Array.isArray(details.indicators) ? details.indicators : [])
245
- .filter((indicator) => typeof indicator === 'string' && indicator.trim()),
246
- turnId: runtime.turnId || null,
247
- },
248
- });
366
+ let emergencyRecordId = null;
249
367
  queued = await recordEmergency({
250
368
  code: runtime.patientCode,
251
369
  trace,
@@ -254,10 +372,16 @@ async function handler(args, context = {}) {
254
372
  recommendedAction: details.recommended_action || '',
255
373
  urgencyFhir: urgencyLevel,
256
374
  documentation: [
375
+ keptOpenLevel ? `Actualización: el bot sugirió ${requestedLevel}; se mantiene ${urgencyLevel}.` : '',
257
376
  args?.urgency_justification || '',
258
377
  details.evidence_quote ? `Evidencia: «${details.evidence_quote}»` : '',
378
+ assessmentNote(clinicalAssessment),
259
379
  ].filter(Boolean).join('\n'),
380
+ anchor: anchor?.emergencyRecordId ? { recordId: anchor.emergencyRecordId, urgencyFhir: anchor.urgencyLevel } : null,
381
+ keepOpenRow: keptOpenLevel,
382
+ onRecorded: (recordId) => { emergencyRecordId = recordId; },
260
383
  });
384
+ if (review && emergencyRecordId) await attachEmergencyRow({ reviewId: review._id, alarmId, emergencyRecordId });
261
385
  try {
262
386
  const net = queued ? await armEscalationNet({
263
387
  patientCode: runtime.patientCode,
@@ -292,6 +416,8 @@ async function handler(args, context = {}) {
292
416
  ? 'The escalation is QUEUED for the care team. This is not confirmation that anyone has read or acted on it, and no reply has arrived. Do not tell the patient the team already reviewed it, and do not treat the topic as closed on the strength of this ack.'
293
417
  : 'The escalation was NOT recorded for the team. Say nothing to the patient implying they were notified, and report the failure.',
294
418
  follow_up: followUpNote(netArmed, netReason),
419
+ ...(escalationUpdateModeLive() ? { mode: updateMode ? 'update' : 'new', update_anchor: anchor ? 'open_escalation' : 'none' } : {}),
420
+ ...(keptOpenLevel ? { kept_open_level: true, requested_urgency_level: requestedLevel } : {}),
295
421
  ...(isCoerced ? { coerced_urgency: true, requested_urgency_level: requested } : {}),
296
422
  ...(categoryCoerced ? { coerced_category: true, requested_category: requestedCategory } : {}),
297
423
  ...(detailsArg === 'unreadable' ? { details_unreadable: true } : {}),
@@ -304,5 +430,6 @@ async function handler(args, context = {}) {
304
430
 
305
431
  module.exports = {
306
432
  definition,
433
+ liveDefinition,
307
434
  handler,
308
435
  };
@@ -12,6 +12,7 @@ const {
12
12
  listEscalationReviews,
13
13
  openEscalationReview,
14
14
  recordDoctorDecision,
15
+ requestBotDraft,
15
16
  sendApprovedIndications,
16
17
  setReviewCases,
17
18
  suggestDraft,
@@ -124,6 +125,16 @@ const suggestEscalationReviewDraftController = async (req, res) => {
124
125
  }
125
126
  };
126
127
 
128
+ const requestEscalationReviewDraftController = async (req, res) => {
129
+ try {
130
+ const { triggeredBy } = req.body || {};
131
+ const review = await requestBotDraft({ id: req.params.id, requestedBy: triggeredBy, requestId: req.requestId });
132
+ res.status(202).json({ success: true, review });
133
+ } catch (error) {
134
+ respondWithError(res, error, 'requesting an escalation review draft', { reviewId: req.params?.id });
135
+ }
136
+ };
137
+
127
138
  const suggestEscalationReviewQuestionsController = async (req, res) => {
128
139
  try {
129
140
  const { triggeredBy } = req.body || {};
@@ -249,6 +260,7 @@ module.exports = {
249
260
  closeEscalationReviewController,
250
261
  getEscalationReviewController,
251
262
  getReviewTimelineController,
263
+ requestEscalationReviewDraftController,
252
264
  handOffEscalationReviewController,
253
265
  listEscalationReviewsController,
254
266
  listReviewBoardController,
package/lib/index.d.ts CHANGED
@@ -1052,8 +1052,10 @@ declare module '@peopl-health/nexus' {
1052
1052
  windowDays?: number;
1053
1053
  limit?: number;
1054
1054
  }, options?: { SweepModel?: unknown; evaluate?: unknown; provider?: unknown }): Promise<{
1055
- outcome: 'completed' | 'not_configured';
1055
+ outcome: 'completed' | 'incomplete' | 'not_configured';
1056
1056
  evaluated: number;
1057
+ partial: number;
1058
+ busy: number;
1057
1059
  skipped: number;
1058
1060
  failed: number;
1059
1061
  changes: SupportLightSweepChange[];
@@ -16,6 +16,7 @@ const DECISION_SOURCES = ['platform', 'registered_by_navigator', 'chat'];
16
16
  const RETURN_REASONS = ['llamar', 'falta_dato', 'no_requiere'];
17
17
 
18
18
  const alarmSchema = new mongoose.Schema({
19
+ alarmId: { type: String, default: null },
19
20
  urgencyLevel: { type: String, enum: URGENCY_LEVELS, required: true },
20
21
  category: { type: String, default: null },
21
22
  symptom: { type: String, default: null },
@@ -25,6 +26,8 @@ const alarmSchema = new mongoose.Schema({
25
26
  justification: { type: String, default: null },
26
27
  indicators: { type: [String], default: undefined },
27
28
  turnId: { type: String, default: null },
29
+ clinicalAssessment: { type: mongoose.Schema.Types.Mixed, default: null },
30
+ emergencyRecordId: { type: String, default: null },
28
31
  raisedAt: { type: Date, required: true },
29
32
  }, { _id: false });
30
33
 
@@ -127,6 +127,7 @@ const escalationReviewRouteDefinitions = {
127
127
  'POST /:id/cases': 'setEscalationReviewCasesController',
128
128
  'POST /:id/call-logs': 'addEscalationReviewCallLogController',
129
129
  'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
130
+ 'POST /:id/draft-requests': 'requestEscalationReviewDraftController',
130
131
  'POST /:id/key-questions': 'suggestEscalationReviewQuestionsController',
131
132
  'POST /:id/note-facts': 'confirmEscalationReviewNoteFactsController',
132
133
  'POST /:id/drafts': 'addEscalationReviewDraftController',
@@ -299,6 +300,7 @@ const builtInControllers = {
299
300
  listReviewBoardController: escalationReviewController.listReviewBoardController,
300
301
  getEscalationReviewController: escalationReviewController.getEscalationReviewController,
301
302
  getReviewTimelineController: escalationReviewController.getReviewTimelineController,
303
+ requestEscalationReviewDraftController: escalationReviewController.requestEscalationReviewDraftController,
302
304
  setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
303
305
  addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
304
306
  suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,
@@ -543,6 +543,30 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
543
543
  }
544
544
  }
545
545
 
546
+ function escalationAnchorOf(review, alarmId) {
547
+ const prior = currentAlarms(review).filter((alarm) => alarm.alarmId !== alarmId);
548
+ if (!prior.length) return null;
549
+ const rankOf = (alarm) => URGENCY_RANK[alarm.urgencyLevel] || 0;
550
+ const topRank = Math.max(...prior.map(rankOf));
551
+ const top = prior.filter((alarm) => rankOf(alarm) === topRank);
552
+ const topRow = [...top].reverse().find((alarm) => alarm.emergencyRecordId);
553
+ return { urgencyLevel: top[0].urgencyLevel, emergencyRecordId: topRow?.emergencyRecordId || null };
554
+ }
555
+
556
+ async function attachEmergencyRow({ reviewId, alarmId, emergencyRecordId }) {
557
+ try {
558
+ await getEscalationReview().updateOne(
559
+ { _id: reviewId, 'alarms.alarmId': alarmId },
560
+ { $set: { 'alarms.$.emergencyRecordId': emergencyRecordId } },
561
+ { timestamps: false },
562
+ );
563
+ } catch (error) {
564
+ logger.error('[EscalationReview] The emergency row was not linked to its alarm', {
565
+ error: error.message, stack: redactedStack(error),
566
+ });
567
+ }
568
+ }
569
+
546
570
  async function openEscalationReview({
547
571
  code,
548
572
  patientCaseRecordId = null,
@@ -556,7 +580,13 @@ async function openEscalationReview({
556
580
  if (!patient) throw httpError(404, 'Patient not found');
557
581
 
558
582
  const recordIds = await requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseRecordIds });
559
- const fields = { patientCode, openedBy: operator, patientCaseRecordIds: recordIds, assistantPausedByReview: false };
583
+ const fields = {
584
+ patientCode,
585
+ openedBy: operator,
586
+ patientCaseRecordIds: recordIds,
587
+ assistantPausedByReview: false,
588
+ draftDueAt: new Date(Date.now() + DRAFT_DEBOUNCE_MS),
589
+ };
560
590
 
561
591
  const EscalationReview = getEscalationReview();
562
592
  let review;
@@ -592,6 +622,35 @@ async function openEscalationReview({
592
622
  return { review, created: true };
593
623
  }
594
624
 
625
+ async function requestBotDraft({ id, requestedBy, requestId = null } = {}) {
626
+ const reviewId = reviewIdOf(id);
627
+ const operator = requiredText(requestedBy, 'requestedBy');
628
+ const review = await loadReview(reviewId);
629
+ if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
630
+ if ((review.drafts ?? []).at(-1)?.writtenBy && review.drafts.at(-1).writtenBy !== DRAFT_OPERATOR) {
631
+ throw httpError(409, 'The latest draft was written by the team; edit it instead of asking for a new one');
632
+ }
633
+ const now = new Date();
634
+ if (review.draftDueAt && new Date(review.draftDueAt) > now) return review;
635
+ const scheduled = await getEscalationReview().findOneAndUpdate(
636
+ {
637
+ _id: reviewId,
638
+ status: { $in: DOCUMENTING_STATUSES },
639
+ drafts: { $size: (review.drafts ?? []).length },
640
+ $or: [{ draftDueAt: null }, { draftDueAt: { $lte: now } }],
641
+ },
642
+ { $set: { draftDueAt: now, draftAttempts: 0 } },
643
+ { new: true },
644
+ ).lean();
645
+ if (!scheduled) {
646
+ const latest = await loadReview(reviewId);
647
+ if (latest.draftDueAt && new Date(latest.draftDueAt) > now) return latest;
648
+ throw httpError(409, STATUS_CONFLICT);
649
+ }
650
+ await audit(scheduled, operator, requestId, { action: 'draft_requested' });
651
+ return scheduled;
652
+ }
653
+
595
654
  async function isEscalationApprover(operator) {
596
655
  try {
597
656
  return Boolean(await getEscalationApprover(operator));
@@ -685,34 +744,29 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
685
744
  if (!DOCUMENTING_STATUSES.includes(current.status)) throw httpError(409, STATUS_CONFLICT);
686
745
 
687
746
  const recordIds = await requestedCaseIds({ patientCode: current.patientCode, patientCaseRecordIds });
747
+ const casesChanged = {
748
+ $not: [{
749
+ $setEquals: [
750
+ {
751
+ $ifNull: [
752
+ '$patientCaseRecordIds',
753
+ { $cond: [{ $ifNull: ['$patientCaseRecordId', false] }, ['$patientCaseRecordId'], []] },
754
+ ],
755
+ },
756
+ recordIds,
757
+ ],
758
+ }],
759
+ };
760
+ const isBotDraft = (current.drafts ?? []).at(-1)?.writtenBy === DRAFT_OPERATOR;
688
761
 
689
762
  const review = await updateReview(reviewId, DOCUMENTING_STATUSES, [{
690
763
  $set: {
691
764
  patientCaseRecordIds: recordIds,
692
- status: {
693
- $cond: [
694
- {
695
- $and: [
696
- { $eq: ['$status', 'draft_ready'] },
697
- {
698
- $not: [{
699
- $setEquals: [
700
- {
701
- $ifNull: [
702
- '$patientCaseRecordIds',
703
- { $cond: [{ $ifNull: ['$patientCaseRecordId', false] }, ['$patientCaseRecordId'], []] },
704
- ],
705
- },
706
- recordIds,
707
- ],
708
- }],
709
- },
710
- ],
711
- },
712
- 'documenting',
713
- '$status',
714
- ],
715
- },
765
+ status: { $cond: [{ $and: [{ $eq: ['$status', 'draft_ready'] }, casesChanged] }, 'documenting', '$status'] },
766
+ ...(isBotDraft && {
767
+ draftDueAt: { $cond: [casesChanged, new Date(Date.now() + DRAFT_DEBOUNCE_MS), '$draftDueAt'] },
768
+ draftAttempts: { $cond: [casesChanged, 0, '$draftAttempts'] },
769
+ }),
716
770
  pendingCaseMirrors: {
717
771
  $filter: {
718
772
  input: { $ifNull: ['$pendingCaseMirrors', []] },
@@ -837,11 +891,15 @@ async function prepareDoctorAlert(review, kind, urgencyLevel) {
837
891
  return { approver, message };
838
892
  }
839
893
 
894
+ const currentAlarms = (review) => {
895
+ const alarms = review?.alarms ?? [];
896
+ const decidedAt = (review?.decisions ?? []).at(-1)?.createdAt;
897
+ return decidedAt ? alarms.filter((alarm) => new Date(alarm.raisedAt) > new Date(decidedAt)) : alarms;
898
+ };
899
+
840
900
  const topUrgencyOf = (review) => {
841
- const alarms = review.alarms ?? [];
842
- const decidedAt = (review.decisions ?? []).at(-1)?.createdAt;
843
- const open = decidedAt ? alarms.filter((alarm) => new Date(alarm.raisedAt) > new Date(decidedAt)) : alarms;
844
- return (open.length ? open : alarms)
901
+ const open = currentAlarms(review);
902
+ return (open.length ? open : review.alarms ?? [])
845
903
  .reduce((top, alarm) => (URGENCY_RANK[alarm.urgencyLevel] > (URGENCY_RANK[top] || 0) ? alarm.urgencyLevel : top), null);
846
904
  };
847
905
 
@@ -1720,8 +1778,10 @@ module.exports = {
1720
1778
  _resetEscalationReviewIndexes,
1721
1779
  addCallLog,
1722
1780
  addDraft,
1781
+ attachEmergencyRow,
1723
1782
  cancelEscalationReview,
1724
1783
  closeEscalationReview,
1784
+ escalationAnchorOf,
1725
1785
  generateBotDraft,
1726
1786
  getEscalationReviewById,
1727
1787
  getReviewTimeline,
@@ -1733,6 +1793,7 @@ module.exports = {
1733
1793
  recordDoctorDecision,
1734
1794
  sendScheduledDoctorAlert,
1735
1795
  recordReviewUpdate,
1796
+ requestBotDraft,
1736
1797
  sendApprovedIndications,
1737
1798
  setReviewCases,
1738
1799
  suggestDraft,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.62.0",
3
+ "version": "5.62.2",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",