@peopl-health/nexus 5.65.0 → 5.67.0-dev.11662

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.
@@ -19,6 +19,7 @@ const ESCALATION_DRAFT_DEFAULTS = { presetId: '' };
19
19
  const ESCALATION_QUESTIONS_DEFAULTS = { presetId: '' };
20
20
  const ESCALATION_NOTE_FACTS_DEFAULTS = { presetId: '' };
21
21
  const SUPPORT_LIGHT_DEFAULTS = { presetId: '' };
22
+ const ESCALATION_PATTERN_FLOOR_DEFAULTS = { presetId: '' };
22
23
 
23
24
  const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL });
24
25
 
@@ -74,7 +75,12 @@ async function load() {
74
75
  if (!isSupportLightValid) logger.error('[subAgentsConfig] SUPPORT_LIGHT is not a JSON object; the support-light sweep stays unconfigured');
75
76
  const supportLight = { ...SUPPORT_LIGHT_DEFAULTS, ...(isSupportLightValid ? parsedSupportLight || {} : {}) };
76
77
 
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 };
78
+ const parsedPatternFloor = safeParse(byKey.ESCALATION_PATTERN_FLOOR, null);
79
+ const isPatternFloorValid = !byKey.ESCALATION_PATTERN_FLOOR || isPlainObject(parsedPatternFloor);
80
+ if (!isPatternFloorValid) logger.error('[subAgentsConfig] ESCALATION_PATTERN_FLOOR is not a JSON object; the clinical pattern floor stays unconfigured');
81
+ const escalationPatternFloor = { ...ESCALATION_PATTERN_FLOOR_DEFAULTS, ...(isPatternFloorValid ? parsedPatternFloor || {} : {}) };
82
+
83
+ 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, ESCALATION_PATTERN_FLOOR: escalationPatternFloor };
78
84
  cache.set(CACHE_KEY, config);
79
85
  return config;
80
86
  }
@@ -94,4 +100,5 @@ module.exports = {
94
100
  getEscalationQuestions: () => get('ESCALATION_QUESTIONS'),
95
101
  getEscalationNoteFacts: () => get('ESCALATION_NOTE_FACTS'),
96
102
  getSupportLightEvaluator: () => get('SUPPORT_LIGHT'),
103
+ getEscalationPatternFloor: () => get('ESCALATION_PATTERN_FLOOR'),
97
104
  };
@@ -0,0 +1,19 @@
1
+ const runtimeConfig = require('../../config/runtimeConfig');
2
+
3
+ const DEFAULT_TIMEOUT_MS = 8000;
4
+ const MAX_TIMEOUT_MS = 60000;
5
+
6
+ function clinicalPatternFloorLive() {
7
+ return String(runtimeConfig.get('ESCALATION_CLINICAL_PATTERN_FLOOR_LIVE', 'true')).trim().toLowerCase() !== 'false';
8
+ }
9
+
10
+ function clinicalPatternFloorTimeoutMs() {
11
+ const value = Number(runtimeConfig.get('ESCALATION_CLINICAL_PATTERN_FLOOR_TIMEOUT_MS', DEFAULT_TIMEOUT_MS));
12
+ if (!Number.isFinite(value) || value <= 0) return DEFAULT_TIMEOUT_MS;
13
+ return Math.min(value, MAX_TIMEOUT_MS);
14
+ }
15
+
16
+ module.exports = {
17
+ clinicalPatternFloorLive,
18
+ clinicalPatternFloorTimeoutMs,
19
+ };
@@ -0,0 +1,17 @@
1
+ const runtimeConfig = require('../../config/runtimeConfig');
2
+
3
+ const DEFAULT_MAX_HOURS = 6;
4
+
5
+ function triageGateFloorLive() {
6
+ return String(runtimeConfig.get('ESCALATION_TRIAGE_GATE_FLOOR_LIVE', 'true')).trim().toLowerCase() !== 'false';
7
+ }
8
+
9
+ function triageGateFloorMaxHours() {
10
+ const value = Number(runtimeConfig.get('ESCALATION_TRIAGE_GATE_FLOOR_MAX_HOURS', DEFAULT_MAX_HOURS));
11
+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_MAX_HOURS;
12
+ }
13
+
14
+ module.exports = {
15
+ triageGateFloorLive,
16
+ triageGateFloorMaxHours,
17
+ };
@@ -15,6 +15,8 @@ const triageRecommendationEventSchema = new mongoose.Schema({
15
15
  elementCount: { type: Number, default: null },
16
16
  urgentUnder24h: { type: Boolean, default: null },
17
17
  escalationRoute: { type: String, default: null },
18
+ maxActionTimeHours: { type: Number, default: null },
19
+ triageAuthoredAt: { type: Date, default: null },
18
20
  autoRepairs: { type: [String], default: [] },
19
21
  hardRejectIssues: { type: [mongoose.Schema.Types.Mixed], default: [] },
20
22
  rejectedGate: {
@@ -0,0 +1,103 @@
1
+ const { getEscalationPatternFloor } = require('../config/subAgentsConfig');
2
+ const { requireGatewayProvider } = require('../config/llmConfig');
3
+ const { readClinicalProfile } = require('../helpers/clinicalProfileHelper');
4
+ const { buildExposureBlock } = require('../helpers/triageCaseBaseHelper');
5
+ const { readStructuredText } = require('../helpers/structuredTextHelper');
6
+ const { clinicalPatternFloorTimeoutMs } = require('../flags/clinicalPatternFloorFlags');
7
+ const { cleanText } = require('../../fhir/helpers/triagePayloadHelper');
8
+ const { isPlainObject, safeParse } = require('../../utils/jsonUtils');
9
+ const { logger } = require('../../utils/logger');
10
+ const { redactDirectIdentifiers } = require('../../utils/sanitizerUtils');
11
+ const { withTimeout } = require('../../utils/timeoutUtils');
12
+
13
+ const FLOOR_LEVELS = ['asap', 'stat'];
14
+ const PATTERN_NAME = /^[a-z0-9_]{1,64}$/;
15
+ const UNLABELLED_PATTERN = 'sin_etiqueta';
16
+ const MAX_TEXT_LENGTH = 500;
17
+
18
+ const degraded = (reason) => ({ floor: null, degraded: reason });
19
+
20
+ function normalizePattern(raw) {
21
+ const name = typeof raw === 'string' ? raw.trim().toLowerCase() : '';
22
+ return PATTERN_NAME.test(name) ? name : UNLABELLED_PATTERN;
23
+ }
24
+
25
+ const clippedText = (value) => cleanText(value)?.slice(0, MAX_TEXT_LENGTH) || null;
26
+
27
+ function buildPatternInput({ profile, details, justification, today }) {
28
+ const indicators = Array.isArray(details.indicators) ? details.indicators.filter((item) => typeof item === 'string' && item.trim()) : [];
29
+ const exposure = buildExposureBlock(profile);
30
+ return [
31
+ `Fecha de hoy: ${today}`,
32
+ '',
33
+ '## Escalación que el agente está registrando',
34
+ `Síntoma: ${cleanText(details.symptom) || 'no especificado'}`,
35
+ `Palabras del paciente: ${cleanText(details.evidence_quote) ? `«${details.evidence_quote.trim()}»` : 'no citadas'}`,
36
+ `Indicadores: ${indicators.length ? indicators.join('; ') : 'ninguno'}`,
37
+ `Sospecha del agente: ${cleanText(details.suspected_condition) || 'no especificada'}`,
38
+ `Justificación del agente: ${cleanText(justification) || 'no especificada'}`,
39
+ '',
40
+ '## Contexto clínico del paciente',
41
+ JSON.stringify(profile),
42
+ ...(exposure ? ['', '## Exposición antineoplásica y medicación documentadas', exposure] : []),
43
+ ].join('\n');
44
+ }
45
+
46
+ async function evaluatePatternFloor({ code, turnId, details, justification, provider, now }) {
47
+ const { presetId } = await getEscalationPatternFloor();
48
+ if (!presetId) {
49
+ logger.info('[clinicalPatternFloor] No preset is configured; the check is skipped', { turnId });
50
+ return degraded('no_preset');
51
+ }
52
+ const profile = await readClinicalProfile(code);
53
+ if (!profile) {
54
+ const reason = profile === undefined ? 'profile_unreadable' : 'profile_missing';
55
+ logger.warn('[clinicalPatternFloor] The clinical profile is missing or unreadable; the check is skipped', { turnId, profile: reason });
56
+ return degraded(reason);
57
+ }
58
+ const result = await (provider || requireGatewayProvider()).runStructured({
59
+ presetId,
60
+ input: [{ role: 'user', content: buildPatternInput({ profile, details, justification, today: now.toISOString().slice(0, 10) }) }],
61
+ metadata: { subAgent: 'escalation-pattern-floor', turnId },
62
+ });
63
+ if (result?.status && result.status !== 'completed') {
64
+ logger.warn('[clinicalPatternFloor] The pattern check did not complete', { turnId, status: result.status });
65
+ return degraded('incomplete');
66
+ }
67
+ const parsed = safeParse(readStructuredText(result), null);
68
+ if (!isPlainObject(parsed)) {
69
+ logger.warn('[clinicalPatternFloor] The pattern check did not return a JSON object', { turnId });
70
+ return degraded('malformed_output');
71
+ }
72
+ if (parsed.min_level == null) {
73
+ if (parsed.pattern == null) return { floor: null, degraded: null };
74
+ logger.warn('[clinicalPatternFloor] The pattern check named a pattern without a level', { turnId, pattern: parsed.pattern });
75
+ return degraded('missing_level');
76
+ }
77
+ if (!FLOOR_LEVELS.includes(parsed.min_level)) {
78
+ logger.warn('[clinicalPatternFloor] The pattern check returned an unsupported level', { turnId, minLevel: parsed.min_level, pattern: parsed.pattern });
79
+ return degraded('unsupported_level');
80
+ }
81
+ return {
82
+ floor: { level: parsed.min_level, pattern: normalizePattern(parsed.pattern), evidence: clippedText(parsed.evidence), reason: clippedText(parsed.reason) },
83
+ degraded: null,
84
+ };
85
+ }
86
+
87
+ async function clinicalPatternFloor({ code, turnId = null, details = {}, justification = null, provider = null, now = new Date() }) {
88
+ try {
89
+ return await withTimeout(
90
+ evaluatePatternFloor({ code, turnId, details, justification, provider, now }),
91
+ clinicalPatternFloorTimeoutMs(),
92
+ 'clinical pattern floor',
93
+ );
94
+ } catch (error) {
95
+ const timedOut = /timed out after/.test(error?.message || '');
96
+ logger.error('[clinicalPatternFloor] The clinical pattern check failed', {
97
+ turnId, error: error.message, stack: redactDirectIdentifiers(String(error?.stack || '')),
98
+ });
99
+ return degraded(timedOut ? 'timeout' : 'error');
100
+ }
101
+ }
102
+
103
+ module.exports = { clinicalPatternFloor, buildPatternInput };
@@ -0,0 +1,49 @@
1
+ const { getTriageRecommendationEventModel } = require('../models/triageRecommendationEventModel');
2
+ const { triageGateFloorMaxHours } = require('../flags/triageGateFloorFlags');
3
+ const { logger } = require('../../utils/logger');
4
+ const { redactDirectIdentifiers } = require('../../utils/sanitizerUtils');
5
+
6
+ const HOUR_MS = 60 * 60 * 1000;
7
+ const LOOKBACK_MS = 24 * HOUR_MS;
8
+ const ROUTE_FLOOR = { emergencia: 'stat', urgencias: 'asap', equipo_tratante_hoy: 'asap' };
9
+ const DEFAULT_FLOOR = 'asap';
10
+ const PROMPT_ROUTES = ['urgencias', 'emergencia'];
11
+ const NO_FLOOR = { floor: null, degraded: null };
12
+
13
+ const settledAt = (event) => new Date(event.createdAt).getTime();
14
+ const gateTime = (event) => Math.min(new Date(event.triageAuthoredAt || event.createdAt).getTime(), settledAt(event));
15
+
16
+ async function activeTriageGateFloor(code, now = new Date()) {
17
+ try {
18
+ const gates = await getTriageRecommendationEventModel()
19
+ .find({ patientCode: code, gateVerdict: { $ne: null }, createdAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } })
20
+ .select('runId triageRecordId urgentUnder24h escalationRoute maxActionTimeHours triageAuthoredAt createdAt')
21
+ .lean();
22
+ const latest = gates.reduce((best, event) => (!best || gateTime(event) > gateTime(best)
23
+ || (gateTime(event) === gateTime(best) && settledAt(event) > settledAt(best)) ? event : best), null);
24
+ if (!latest?.urgentUnder24h) return NO_FLOOR;
25
+
26
+ const hours = Number.isFinite(latest.maxActionTimeHours) ? latest.maxActionTimeHours : null;
27
+ const promptRoute = PROMPT_ROUTES.includes(latest.escalationRoute);
28
+ if (!promptRoute && (hours === null || hours > triageGateFloorMaxHours())) return NO_FLOOR;
29
+
30
+ const windowMs = Math.max(hours ?? 24, 1) * HOUR_MS;
31
+ if (now.getTime() - gateTime(latest) > windowMs) return NO_FLOOR;
32
+
33
+ return {
34
+ floor: {
35
+ level: ROUTE_FLOOR[latest.escalationRoute] || DEFAULT_FLOOR,
36
+ runId: latest.runId,
37
+ triageRecordId: latest.triageRecordId,
38
+ escalationRoute: latest.escalationRoute,
39
+ maxActionTimeHours: hours,
40
+ },
41
+ degraded: null,
42
+ };
43
+ } catch (error) {
44
+ logger.error('[triageGateFloor] The latest triage gate could not be read', { error: error.message, stack: redactDirectIdentifiers(String(error?.stack || '')) });
45
+ return { floor: null, degraded: 'read_failed' };
46
+ }
47
+ }
48
+
49
+ module.exports = { activeTriageGateFloor };
@@ -575,6 +575,8 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
575
575
  settle.gateVerdict = gate.urgentUnder24h ? 'urgent' : 'clear';
576
576
  settle.urgentUnder24h = gate.urgentUnder24h;
577
577
  settle.escalationRoute = gate.escalationRoute;
578
+ settle.maxActionTimeHours = gate.maxActionTimeHours;
579
+ settle.triageAuthoredAt = payload.authored || null;
578
580
  settle.qualityWarnings = gateWarnings;
579
581
  settle.supportSafetyCleared = !gate.urgentUnder24h
580
582
  && gate.redFlags.every((flag) => flag.verificationStatus === 'denied');
@@ -7,7 +7,11 @@ const { evidenceQuoteAnchoring } = require('../helpers/evidenceAnchorHelper');
7
7
  const { dispatcherService } = require('../services/dispatcherService');
8
8
  const { armEscalationNet } = require('../services/contingencyDispatchService');
9
9
  const { recordEmergency, writeUnresolvedRequest } = require('../services/clinicalAirtableService');
10
+ const { activeTriageGateFloor } = require('../services/triageGateFloorService');
11
+ const { clinicalPatternFloor } = require('../services/clinicalPatternFloorService');
10
12
  const { escalationAssessmentLive, escalationUpdateModeLive } = require('../flags/escalationFlags');
13
+ const { triageGateFloorLive } = require('../flags/triageGateFloorFlags');
14
+ const { clinicalPatternFloorLive } = require('../flags/clinicalPatternFloorFlags');
11
15
  const { attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
12
16
  const { URGENCY_RANK } = require('../../models/escalationReviewModel');
13
17
  const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
@@ -308,8 +312,18 @@ async function handler(args, context = {}) {
308
312
  : null;
309
313
  const anchor = updateMode && review ? escalationAnchorOf(review, alarmId) : null;
310
314
  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);
315
+ const agentLevel = keptOpenLevel ? anchor.urgencyLevel : requestedLevel;
316
+ const gateCheck = triageGateFloorLive() && runtime.patientCode ? await activeTriageGateFloor(runtime.patientCode) : null;
317
+ const gateFloor = gateCheck?.floor || null;
318
+ const raisedByGate = Boolean(gateFloor) && (URGENCY_RANK[gateFloor.level] || 0) > (URGENCY_RANK[agentLevel] || 0);
319
+ const flooredLevel = raisedByGate ? gateFloor.level : agentLevel;
320
+ const patternCheck = clinicalPatternFloorLive() && runtime.patientCode && (URGENCY_RANK[flooredLevel] || 0) < URGENCY_RANK.stat
321
+ ? await clinicalPatternFloor({ code: runtime.patientCode, turnId: runtime.turnId, details, justification: args?.urgency_justification })
322
+ : null;
323
+ const patternFloor = patternCheck?.floor || null;
324
+ const raisedByPattern = Boolean(patternFloor) && (URGENCY_RANK[patternFloor.level] || 0) > (URGENCY_RANK[flooredLevel] || 0);
325
+ const urgencyLevel = raisedByPattern ? patternFloor.level : flooredLevel;
326
+ const raisesOpen = !anchor || (URGENCY_RANK[urgencyLevel] || 0) > (URGENCY_RANK[anchor.urgencyLevel] || 0);
313
327
 
314
328
  trace.setSafetyDecision({ ...(trace.safetyDecision || {}), escalationKind: 'medical_urgent' });
315
329
  trace.setSignals({
@@ -331,6 +345,10 @@ async function handler(args, context = {}) {
331
345
  detailsArg,
332
346
  ...(updateMode ? { mode: 'update', openUrgencyLevel: anchor?.urgencyLevel || null, keptOpenLevel } : {}),
333
347
  ...(clinicalAssessment ? { clinicalAssessment } : {}),
348
+ ...(gateFloor ? { triageGateFloor: { ...gateFloor, raised: raisedByGate } } : {}),
349
+ ...(patternFloor ? { clinicalPatternFloor: { ...patternFloor, raised: raisedByPattern } } : {}),
350
+ ...(gateCheck?.degraded ? { triageGateFloorDegraded: gateCheck.degraded } : {}),
351
+ ...(patternCheck?.degraded ? { clinicalPatternFloorDegraded: patternCheck.degraded } : {}),
334
352
  },
335
353
  });
336
354
 
@@ -372,7 +390,9 @@ async function handler(args, context = {}) {
372
390
  recommendedAction: details.recommended_action || '',
373
391
  urgencyFhir: urgencyLevel,
374
392
  documentation: [
375
- keptOpenLevel ? `Actualización: el bot sugirió ${requestedLevel}; se mantiene ${urgencyLevel}.` : '',
393
+ keptOpenLevel ? `Actualización: el bot sugirió ${requestedLevel}; se mantiene ${agentLevel}.` : '',
394
+ raisedByGate ? `Piso del triaje: el gate de seguridad pidió acción en ${gateFloor.maxActionTimeHours ?? '<24'} h (${gateFloor.escalationRoute}); se aplica ${flooredLevel} aunque el bot sugirió ${agentLevel}.` : '',
395
+ raisedByPattern ? `Piso clínico (${patternFloor.pattern}): ${patternFloor.reason || 'patrón de riesgo cumplido'}; se aplica ${urgencyLevel} en lugar de ${flooredLevel}${raisedByGate ? ' (nivel ya elevado por el triaje)' : ''}.` : '',
376
396
  args?.urgency_justification || '',
377
397
  details.evidence_quote ? `Evidencia: «${details.evidence_quote}»` : '',
378
398
  assessmentNote(clinicalAssessment),
@@ -381,24 +401,27 @@ async function handler(args, context = {}) {
381
401
  keepOpenRow: keptOpenLevel,
382
402
  onRecorded: (recordId) => { emergencyRecordId = recordId; },
383
403
  });
384
- if (review && emergencyRecordId) await attachEmergencyRow({ reviewId: review._id, alarmId, emergencyRecordId });
385
- try {
386
- const net = queued ? await armEscalationNet({
387
- patientCode: runtime.patientCode,
388
- urgencyLevel,
389
- symptom: details.symptom || '',
390
- suspectedCondition: details.suspected_condition || null,
391
- checkIn: args?.patient_check_in || null,
392
- trace,
393
- isLive: runtime.isLive?.bind(runtime),
394
- }) : { armed: false, reason: 'emergency_row_not_recorded' };
395
- netArmed = Boolean(net?.armed);
396
- netReason = netArmed ? null : (net?.reason || 'unknown');
397
- logger.info('[reportMedicalEscalation] contingency net', { turnId: runtime.turnId, urgencyLevel, ...net });
398
- } catch (netErr) {
399
- netArmed = false;
400
- netReason = 'arm_failed';
401
- logger.error('[reportMedicalEscalation] escalation net not armed', { turnId: runtime.turnId, urgencyLevel, error: netErr?.message });
404
+ if (review && emergencyRecordId) await attachEmergencyRow({ reviewId: review._id, alarmId, emergencyRecordId, appliedLevel: urgencyLevel });
405
+ const netLevel = raisedByGate || raisedByPattern ? urgencyLevel : agentLevel;
406
+ if (netLevel !== 'routine') {
407
+ try {
408
+ const net = queued ? await armEscalationNet({
409
+ patientCode: runtime.patientCode,
410
+ urgencyLevel: netLevel,
411
+ symptom: details.symptom || '',
412
+ suspectedCondition: details.suspected_condition || null,
413
+ checkIn: args?.patient_check_in || null,
414
+ trace,
415
+ isLive: runtime.isLive?.bind(runtime),
416
+ }) : { armed: false, reason: 'emergency_row_not_recorded' };
417
+ netArmed = Boolean(net?.armed);
418
+ netReason = netArmed ? null : (net?.reason || 'unknown');
419
+ logger.info('[reportMedicalEscalation] contingency net', { turnId: runtime.turnId, urgencyLevel, ...net });
420
+ } catch (netErr) {
421
+ netArmed = false;
422
+ netReason = 'arm_failed';
423
+ logger.error('[reportMedicalEscalation] escalation net not armed', { turnId: runtime.turnId, urgencyLevel, error: netErr?.message });
424
+ }
402
425
  }
403
426
  }
404
427
  } else if (urgencyLevel !== 'routine') {
@@ -418,6 +441,16 @@ async function handler(args, context = {}) {
418
441
  follow_up: followUpNote(netArmed, netReason),
419
442
  ...(escalationUpdateModeLive() ? { mode: updateMode ? 'update' : 'new', update_anchor: anchor ? 'open_escalation' : 'none' } : {}),
420
443
  ...(keptOpenLevel ? { kept_open_level: true, requested_urgency_level: requestedLevel } : {}),
444
+ ...(raisedByGate ? {
445
+ raised_by_triage_gate: true,
446
+ requested_urgency_level: requestedLevel,
447
+ triage_gate: { escalation_route: gateFloor.escalationRoute, max_action_time_hours: gateFloor.maxActionTimeHours },
448
+ } : {}),
449
+ ...(raisedByPattern ? {
450
+ raised_by_clinical_pattern: true,
451
+ requested_urgency_level: requestedLevel,
452
+ clinical_pattern: { pattern: patternFloor.pattern, reason: patternFloor.reason },
453
+ } : {}),
421
454
  ...(isCoerced ? { coerced_urgency: true, requested_urgency_level: requested } : {}),
422
455
  ...(categoryCoerced ? { coerced_category: true, requested_category: requestedCategory } : {}),
423
456
  ...(detailsArg === 'unreadable' ? { details_unreadable: true } : {}),
@@ -125,6 +125,7 @@ function buildPayloadFromTriageRow(row = {}, { patientCode, triageRecordId, addi
125
125
  }
126
126
 
127
127
  module.exports = {
128
+ cleanText,
128
129
  normalizeAnswerToken,
129
130
  buildTriageResponse,
130
131
  buildPayloadFromTriageRow,
@@ -29,6 +29,7 @@ const alarmSchema = new mongoose.Schema({
29
29
  turnId: { type: String, default: null },
30
30
  clinicalAssessment: { type: mongoose.Schema.Types.Mixed, default: null },
31
31
  emergencyRecordId: { type: String, default: null },
32
+ appliedLevel: { type: String, default: null },
32
33
  raisedAt: { type: Date, required: true },
33
34
  }, { _id: false });
34
35
 
@@ -549,18 +549,19 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
549
549
  function escalationAnchorOf(review, alarmId) {
550
550
  const prior = currentAlarms(review).filter((alarm) => alarm.alarmId !== alarmId);
551
551
  if (!prior.length) return null;
552
- const rankOf = (alarm) => URGENCY_RANK[alarm.urgencyLevel] || 0;
552
+ const levelOf = (alarm) => alarm.appliedLevel || alarm.urgencyLevel;
553
+ const rankOf = (alarm) => URGENCY_RANK[levelOf(alarm)] || 0;
553
554
  const topRank = Math.max(...prior.map(rankOf));
554
555
  const top = prior.filter((alarm) => rankOf(alarm) === topRank);
555
556
  const topRow = [...top].reverse().find((alarm) => alarm.emergencyRecordId);
556
- return { urgencyLevel: top[0].urgencyLevel, emergencyRecordId: topRow?.emergencyRecordId || null };
557
+ return { urgencyLevel: levelOf(top[0]), emergencyRecordId: topRow?.emergencyRecordId || null };
557
558
  }
558
559
 
559
- async function attachEmergencyRow({ reviewId, alarmId, emergencyRecordId }) {
560
+ async function attachEmergencyRow({ reviewId, alarmId, emergencyRecordId, appliedLevel = null }) {
560
561
  try {
561
562
  await getEscalationReview().updateOne(
562
563
  { _id: reviewId, 'alarms.alarmId': alarmId },
563
- { $set: { 'alarms.$.emergencyRecordId': emergencyRecordId } },
564
+ { $set: { 'alarms.$.emergencyRecordId': emergencyRecordId, 'alarms.$.appliedLevel': appliedLevel } },
564
565
  { timestamps: false },
565
566
  );
566
567
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.65.0",
3
+ "version": "5.67.0-dev.11662",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",