@peopl-health/nexus 5.65.0-dev.11557 → 5.65.0-dev.11560

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,80 @@
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 PATTERNS = ['posquirurgico_abdominal', 'toxicidad_gi_quimioterapia', 'toxicidad_gi_inmunoterapia', 'fiebre_quimioterapia'];
14
+ const FLOOR_LEVELS = ['asap', 'stat'];
15
+
16
+ function buildPatternInput({ profile, details, justification, today }) {
17
+ const indicators = Array.isArray(details.indicators) ? details.indicators.filter((item) => typeof item === 'string' && item.trim()) : [];
18
+ const exposure = buildExposureBlock(profile);
19
+ return [
20
+ `Fecha de hoy: ${today}`,
21
+ '',
22
+ '## Escalación que el agente está registrando',
23
+ `Síntoma: ${cleanText(details.symptom) || 'no especificado'}`,
24
+ `Palabras del paciente: ${cleanText(details.evidence_quote) ? `«${details.evidence_quote.trim()}»` : 'no citadas'}`,
25
+ `Indicadores: ${indicators.length ? indicators.join('; ') : 'ninguno'}`,
26
+ `Sospecha del agente: ${cleanText(details.suspected_condition) || 'no especificada'}`,
27
+ `Justificación del agente: ${cleanText(justification) || 'no especificada'}`,
28
+ '',
29
+ '## Contexto clínico del paciente',
30
+ JSON.stringify(profile),
31
+ ...(exposure ? ['', '## Exposición antineoplásica y medicación documentadas', exposure] : []),
32
+ ].join('\n');
33
+ }
34
+
35
+ async function evaluatePatternFloor({ code, turnId, details, justification, provider, now }) {
36
+ const { presetId } = await getEscalationPatternFloor();
37
+ if (!presetId) {
38
+ logger.info('[clinicalPatternFloor] No preset is configured; the check is skipped', { turnId });
39
+ return null;
40
+ }
41
+ const profile = await readClinicalProfile(code);
42
+ if (!profile) {
43
+ logger.warn('[clinicalPatternFloor] The clinical profile is missing or unreadable; the check is skipped', { turnId, profile: profile === undefined ? 'unreadable' : 'missing_or_unparseable' });
44
+ return null;
45
+ }
46
+ const result = await (provider || requireGatewayProvider()).runStructured({
47
+ presetId,
48
+ input: [{ role: 'user', content: buildPatternInput({ profile, details, justification, today: now.toISOString().slice(0, 10) }) }],
49
+ metadata: { subAgent: 'escalation-pattern-floor', turnId },
50
+ });
51
+ if (result?.status && result.status !== 'completed') throw new Error(`pattern floor incomplete: status=${result.status}`);
52
+ const parsed = safeParse(readStructuredText(result), null);
53
+ if (!isPlainObject(parsed)) {
54
+ logger.warn('[clinicalPatternFloor] The pattern check did not return a JSON object', { turnId });
55
+ return null;
56
+ }
57
+ if (parsed.min_level == null && parsed.pattern == null) return null;
58
+ if (!FLOOR_LEVELS.includes(parsed.min_level) || !PATTERNS.includes(parsed.pattern)) {
59
+ logger.warn('[clinicalPatternFloor] The pattern check returned an unsupported level or pattern', { turnId, minLevel: parsed.min_level, pattern: parsed.pattern });
60
+ return null;
61
+ }
62
+ return { level: parsed.min_level, pattern: parsed.pattern, evidence: cleanText(parsed.evidence), reason: cleanText(parsed.reason) };
63
+ }
64
+
65
+ async function clinicalPatternFloor({ code, turnId = null, details = {}, justification = null, provider = null, now = new Date() }) {
66
+ try {
67
+ return await withTimeout(
68
+ evaluatePatternFloor({ code, turnId, details, justification, provider, now }),
69
+ clinicalPatternFloorTimeoutMs(),
70
+ 'clinical pattern floor',
71
+ );
72
+ } catch (error) {
73
+ logger.error('[clinicalPatternFloor] The clinical pattern check failed', {
74
+ turnId, error: error.message, stack: redactDirectIdentifiers(String(error?.stack || '')),
75
+ });
76
+ return null;
77
+ }
78
+ }
79
+
80
+ module.exports = { clinicalPatternFloor, buildPatternInput, PATTERNS };
@@ -103,43 +103,32 @@ async function evaluatePatientSupport({
103
103
  return { outcome: isPartial ? 'partial' : 'evaluated', changes };
104
104
  }
105
105
 
106
- async function patientsToEvaluate({
107
- now, cadenceHours, activeWithinHours, limit, scope, SweepModel,
108
- }) {
106
+ async function patientsToEvaluate({ now, cadenceHours, limit, scope, SweepModel }) {
109
107
  const since = new Date(now.getTime() - cadenceHours * HOUR_MS);
110
- const activeSince = new Date(now.getTime() - activeWithinHours * HOUR_MS);
111
108
  const retrySince = new Date(now.getTime() - RETRY_HOURS * HOUR_MS);
112
109
  const numero = Array.isArray(scope) ? { $in: scope } : { $regex: '^whatsapp:\\+' };
113
110
  const selected = [];
114
111
  for (let page = 0; selected.length < limit && page < MAX_CANDIDATE_PAGES; page += 1) {
115
112
  const active = await aggregateMessages([
116
- { $match: { from_me: false, createdAt: { $gte: activeSince }, numero, origin: { $nin: INTERNAL_ORIGINS }, body: { $regex: '\\S' } } },
113
+ { $match: { from_me: false, createdAt: { $gte: since }, numero, origin: { $nin: INTERNAL_ORIGINS }, body: { $regex: '\\S' } } },
117
114
  { $group: { _id: '$numero', lastInboundAt: { $max: '$createdAt' } } },
118
115
  { $sort: { lastInboundAt: -1, _id: 1 } },
119
116
  { $skip: page * CANDIDATE_PAGE },
120
117
  { $limit: CANDIDATE_PAGE },
121
118
  ]);
122
- if (!active?.length) break;
123
- const states = await SweepModel.find({ patientId: { $in: active.map((row) => row._id) } })
124
- .select('patientId lastEvaluatedAt lastAttemptAt claimedUntil').lean();
125
- const stateOf = new Map(states.map((state) => [state.patientId, state]));
126
- selected.push(...active
127
- .filter((row) => !isSettled(stateOf.get(row._id), { lastInboundAt: row.lastInboundAt, since, retrySince, now }))
128
- .map((row) => ({ patientId: row._id, lastInboundAt: row.lastInboundAt })));
129
- if (active.length < CANDIDATE_PAGE) break;
119
+ const ids = (active || []).map((row) => row._id);
120
+ if (!ids.length) break;
121
+ const recent = await SweepModel.find({
122
+ patientId: { $in: ids },
123
+ $or: [{ lastEvaluatedAt: { $gte: since } }, { lastAttemptAt: { $gte: retrySince } }, { claimedUntil: { $gt: now } }],
124
+ }).select('patientId').lean();
125
+ const done = new Set(recent.map((row) => row.patientId));
126
+ selected.push(...ids.filter((id) => !done.has(id)));
127
+ if (ids.length < CANDIDATE_PAGE) break;
130
128
  }
131
129
  return selected.slice(0, limit);
132
130
  }
133
131
 
134
- // Settled: evaluated within the cadence, or nothing new since the last evaluation, or tried recently, or claimed.
135
- function isSettled(state, { lastInboundAt, since, retrySince, now }) {
136
- if (!state) return false;
137
- const evaluatedAt = state.lastEvaluatedAt ? new Date(state.lastEvaluatedAt) : null;
138
- return Boolean((evaluatedAt && (evaluatedAt >= since || evaluatedAt >= new Date(lastInboundAt)))
139
- || (state.lastAttemptAt && new Date(state.lastAttemptAt) >= retrySince)
140
- || (state.claimedUntil && new Date(state.claimedUntil) > now));
141
- }
142
-
143
132
  function validPatientIds(ids) {
144
133
  return [...new Set(ids.filter((id) => /^whatsapp:\+\d{6,20}$/.test(String(id))))];
145
134
  }
@@ -151,12 +140,11 @@ function sweepState(outcome, now) {
151
140
  };
152
141
  }
153
142
 
154
- function stillDue({ now, cadenceHours, lastInboundAt }) {
143
+ function stillDue({ now, cadenceHours }) {
155
144
  const since = new Date(now.getTime() - cadenceHours * HOUR_MS);
156
145
  const retrySince = new Date(now.getTime() - RETRY_HOURS * HOUR_MS);
157
- const notEvaluatedSince = new Date(Math.min(since.getTime(), new Date(lastInboundAt).getTime()));
158
146
  return [
159
- { $or: [{ lastEvaluatedAt: null }, { lastEvaluatedAt: { $lt: notEvaluatedSince } }] },
147
+ { $or: [{ lastEvaluatedAt: null }, { lastEvaluatedAt: { $lt: since } }] },
160
148
  { $or: [{ lastAttemptAt: null }, { lastAttemptAt: { $lt: retrySince } }] },
161
149
  ];
162
150
  }
@@ -187,8 +175,7 @@ async function settleClaim(SweepModel, patientId, claimToken, update) {
187
175
  }
188
176
 
189
177
  async function runSupportLightSweep({
190
- now = new Date(), patientIds = null, scope = null, cadenceHours = DEFAULT_CADENCE_HOURS, activeWithinHours = cadenceHours,
191
- windowDays = DEFAULT_WINDOW_DAYS, limit = 50,
178
+ now = new Date(), patientIds = null, scope = null, cadenceHours = DEFAULT_CADENCE_HOURS, windowDays = DEFAULT_WINDOW_DAYS, limit = 50,
192
179
  } = {}, {
193
180
  SweepModel = getSupportLightSweepModel(), evaluate = evaluatePatientSupport, getConfig = getSupportLightEvaluator,
194
181
  clock = () => new Date(), ...deps
@@ -197,14 +184,12 @@ async function runSupportLightSweep({
197
184
  if (!config?.presetId) return { evaluated: 0, partial: 0, skipped: 0, failed: 0, busy: 0, changes: [], outcome: 'not_configured' };
198
185
  const isBackfill = Array.isArray(patientIds);
199
186
  const candidates = isBackfill
200
- ? validPatientIds(patientIds).slice(0, limit).map((patientId) => ({ patientId, lastInboundAt: null }))
201
- : await patientsToEvaluate({
202
- now, cadenceHours, activeWithinHours: Math.max(activeWithinHours, cadenceHours), limit, scope: scope && validPatientIds(scope), SweepModel,
203
- });
187
+ ? validPatientIds(patientIds).slice(0, limit)
188
+ : await patientsToEvaluate({ now, cadenceHours, limit, scope: scope && validPatientIds(scope), SweepModel });
204
189
  const evaluationDeps = { ...deps, getConfig: async () => config };
205
190
  const summary = { evaluated: 0, partial: 0, skipped: 0, failed: 0, busy: 0, changes: [] };
206
- for (const { patientId, lastInboundAt } of candidates) {
207
- const claimToken = await claimPatient(SweepModel, patientId, clock, isBackfill ? [] : stillDue({ now, cadenceHours, lastInboundAt }));
191
+ for (const patientId of candidates) {
192
+ const claimToken = await claimPatient(SweepModel, patientId, clock, isBackfill ? [] : stillDue({ now, cadenceHours }));
208
193
  if (!claimToken) {
209
194
  summary.busy += 1;
210
195
  continue;
@@ -0,0 +1,44 @@
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 FLOOR_LEVEL = 'asap';
9
+ const PROMPT_ROUTES = ['urgencias', 'emergencia'];
10
+
11
+ const settledAt = (event) => new Date(event.createdAt).getTime();
12
+ const gateTime = (event) => Math.min(new Date(event.triageAuthoredAt || event.createdAt).getTime(), settledAt(event));
13
+
14
+ async function activeTriageGateFloor(code, now = new Date()) {
15
+ try {
16
+ const gates = await getTriageRecommendationEventModel()
17
+ .find({ patientCode: code, gateVerdict: { $ne: null }, createdAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } })
18
+ .select('runId triageRecordId urgentUnder24h escalationRoute maxActionTimeHours triageAuthoredAt createdAt')
19
+ .lean();
20
+ const latest = gates.reduce((best, event) => (!best || gateTime(event) > gateTime(best)
21
+ || (gateTime(event) === gateTime(best) && settledAt(event) > settledAt(best)) ? event : best), null);
22
+ if (!latest?.urgentUnder24h) return null;
23
+
24
+ const hours = Number.isFinite(latest.maxActionTimeHours) ? latest.maxActionTimeHours : null;
25
+ const promptRoute = PROMPT_ROUTES.includes(latest.escalationRoute);
26
+ if (!promptRoute && (hours === null || hours > triageGateFloorMaxHours())) return null;
27
+
28
+ const windowMs = (hours ?? 24) * HOUR_MS;
29
+ if (now.getTime() - gateTime(latest) > windowMs) return null;
30
+
31
+ return {
32
+ level: FLOOR_LEVEL,
33
+ runId: latest.runId,
34
+ triageRecordId: latest.triageRecordId,
35
+ escalationRoute: latest.escalationRoute,
36
+ maxActionTimeHours: hours,
37
+ };
38
+ } catch (error) {
39
+ logger.error('[triageGateFloor] The latest triage gate could not be read', { error: error.message, stack: redactDirectIdentifiers(String(error?.stack || '')) });
40
+ return null;
41
+ }
42
+ }
43
+
44
+ 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,16 @@ 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 gateFloor = triageGateFloorLive() && runtime.patientCode ? await activeTriageGateFloor(runtime.patientCode) : null;
317
+ const raisedByGate = Boolean(gateFloor) && (URGENCY_RANK[gateFloor.level] || 0) > (URGENCY_RANK[agentLevel] || 0);
318
+ const flooredLevel = raisedByGate ? gateFloor.level : agentLevel;
319
+ const patternFloor = clinicalPatternFloorLive() && runtime.patientCode && (URGENCY_RANK[flooredLevel] || 0) < URGENCY_RANK.stat
320
+ ? await clinicalPatternFloor({ code: runtime.patientCode, turnId: runtime.turnId, details, justification: args?.urgency_justification })
321
+ : null;
322
+ const raisedByPattern = Boolean(patternFloor) && (URGENCY_RANK[patternFloor.level] || 0) > (URGENCY_RANK[flooredLevel] || 0);
323
+ const urgencyLevel = raisedByPattern ? patternFloor.level : flooredLevel;
324
+ const raisesOpen = !anchor || (URGENCY_RANK[urgencyLevel] || 0) > (URGENCY_RANK[anchor.urgencyLevel] || 0);
313
325
 
314
326
  trace.setSafetyDecision({ ...(trace.safetyDecision || {}), escalationKind: 'medical_urgent' });
315
327
  trace.setSignals({
@@ -331,6 +343,8 @@ async function handler(args, context = {}) {
331
343
  detailsArg,
332
344
  ...(updateMode ? { mode: 'update', openUrgencyLevel: anchor?.urgencyLevel || null, keptOpenLevel } : {}),
333
345
  ...(clinicalAssessment ? { clinicalAssessment } : {}),
346
+ ...(gateFloor ? { triageGateFloor: { ...gateFloor, raised: raisedByGate } } : {}),
347
+ ...(patternFloor ? { clinicalPatternFloor: { ...patternFloor, raised: raisedByPattern } } : {}),
334
348
  },
335
349
  });
336
350
 
@@ -372,7 +386,9 @@ async function handler(args, context = {}) {
372
386
  recommendedAction: details.recommended_action || '',
373
387
  urgencyFhir: urgencyLevel,
374
388
  documentation: [
375
- keptOpenLevel ? `Actualización: el bot sugirió ${requestedLevel}; se mantiene ${urgencyLevel}.` : '',
389
+ keptOpenLevel ? `Actualización: el bot sugirió ${requestedLevel}; se mantiene ${agentLevel}.` : '',
390
+ 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}.` : '',
391
+ 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
392
  args?.urgency_justification || '',
377
393
  details.evidence_quote ? `Evidencia: «${details.evidence_quote}»` : '',
378
394
  assessmentNote(clinicalAssessment),
@@ -381,24 +397,26 @@ async function handler(args, context = {}) {
381
397
  keepOpenRow: keptOpenLevel,
382
398
  onRecorded: (recordId) => { emergencyRecordId = recordId; },
383
399
  });
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 });
400
+ if (review && emergencyRecordId) await attachEmergencyRow({ reviewId: review._id, alarmId, emergencyRecordId, appliedLevel: urgencyLevel });
401
+ if (agentLevel !== 'routine') {
402
+ try {
403
+ const net = queued ? await armEscalationNet({
404
+ patientCode: runtime.patientCode,
405
+ urgencyLevel: agentLevel,
406
+ symptom: details.symptom || '',
407
+ suspectedCondition: details.suspected_condition || null,
408
+ checkIn: args?.patient_check_in || null,
409
+ trace,
410
+ isLive: runtime.isLive?.bind(runtime),
411
+ }) : { armed: false, reason: 'emergency_row_not_recorded' };
412
+ netArmed = Boolean(net?.armed);
413
+ netReason = netArmed ? null : (net?.reason || 'unknown');
414
+ logger.info('[reportMedicalEscalation] contingency net', { turnId: runtime.turnId, urgencyLevel, ...net });
415
+ } catch (netErr) {
416
+ netArmed = false;
417
+ netReason = 'arm_failed';
418
+ logger.error('[reportMedicalEscalation] escalation net not armed', { turnId: runtime.turnId, urgencyLevel, error: netErr?.message });
419
+ }
402
420
  }
403
421
  }
404
422
  } else if (urgencyLevel !== 'routine') {
@@ -418,6 +436,16 @@ async function handler(args, context = {}) {
418
436
  follow_up: followUpNote(netArmed, netReason),
419
437
  ...(escalationUpdateModeLive() ? { mode: updateMode ? 'update' : 'new', update_anchor: anchor ? 'open_escalation' : 'none' } : {}),
420
438
  ...(keptOpenLevel ? { kept_open_level: true, requested_urgency_level: requestedLevel } : {}),
439
+ ...(raisedByGate ? {
440
+ raised_by_triage_gate: true,
441
+ requested_urgency_level: requestedLevel,
442
+ triage_gate: { escalation_route: gateFloor.escalationRoute, max_action_time_hours: gateFloor.maxActionTimeHours },
443
+ } : {}),
444
+ ...(raisedByPattern ? {
445
+ raised_by_clinical_pattern: true,
446
+ requested_urgency_level: requestedLevel,
447
+ clinical_pattern: { pattern: patternFloor.pattern, reason: patternFloor.reason },
448
+ } : {}),
421
449
  ...(isCoerced ? { coerced_urgency: true, requested_urgency_level: requested } : {}),
422
450
  ...(categoryCoerced ? { coerced_category: true, requested_category: requestedCategory } : {}),
423
451
  ...(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,
package/lib/index.d.ts CHANGED
@@ -1061,7 +1061,6 @@ declare module '@peopl-health/nexus' {
1061
1061
  patientIds?: string[] | null;
1062
1062
  scope?: string[] | null;
1063
1063
  cadenceHours?: number;
1064
- activeWithinHours?: number;
1065
1064
  windowDays?: number;
1066
1065
  limit?: number;
1067
1066
  }, options?: { SweepModel?: unknown; evaluate?: unknown; provider?: unknown }): Promise<{
@@ -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-dev.11557",
3
+ "version": "5.65.0-dev.11560",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",