@peopl-health/nexus 5.65.0 → 5.66.0
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.
- package/lib/clinical/config/subAgentsConfig.js +8 -1
- package/lib/clinical/flags/clinicalPatternFloorFlags.js +19 -0
- package/lib/clinical/flags/triageGateFloorFlags.js +17 -0
- package/lib/clinical/models/triageRecommendationEventModel.js +2 -0
- package/lib/clinical/services/clinicalPatternFloorService.js +80 -0
- package/lib/clinical/services/triageGateFloorService.js +44 -0
- package/lib/clinical/services/triageRecommendationService.js +2 -0
- package/lib/clinical/tools/reportMedicalEscalationTool.js +49 -21
- package/lib/fhir/helpers/triagePayloadHelper.js +1 -0
- package/lib/models/escalationReviewModel.js +1 -0
- package/lib/services/escalationReviewService.js +5 -4
- package/package.json +1 -1
|
@@ -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
|
|
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 };
|
|
@@ -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
|
|
312
|
-
const
|
|
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 ${
|
|
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
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
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 } : {}),
|
|
@@ -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
|
|
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]
|
|
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) {
|