@peopl-health/nexus 5.65.0-dev.11559 → 5.65.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.
@@ -19,7 +19,6 @@ 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: '' };
23
22
 
24
23
  const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL });
25
24
 
@@ -75,12 +74,7 @@ async function load() {
75
74
  if (!isSupportLightValid) logger.error('[subAgentsConfig] SUPPORT_LIGHT is not a JSON object; the support-light sweep stays unconfigured');
76
75
  const supportLight = { ...SUPPORT_LIGHT_DEFAULTS, ...(isSupportLightValid ? parsedSupportLight || {} : {}) };
77
76
 
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 };
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 };
84
78
  cache.set(CACHE_KEY, config);
85
79
  return config;
86
80
  }
@@ -100,5 +94,4 @@ module.exports = {
100
94
  getEscalationQuestions: () => get('ESCALATION_QUESTIONS'),
101
95
  getEscalationNoteFacts: () => get('ESCALATION_NOTE_FACTS'),
102
96
  getSupportLightEvaluator: () => get('SUPPORT_LIGHT'),
103
- getEscalationPatternFloor: () => get('ESCALATION_PATTERN_FLOOR'),
104
97
  };
@@ -15,8 +15,6 @@ 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 },
20
18
  autoRepairs: { type: [String], default: [] },
21
19
  hardRejectIssues: { type: [mongoose.Schema.Types.Mixed], default: [] },
22
20
  rejectedGate: {
@@ -103,32 +103,43 @@ async function evaluatePatientSupport({
103
103
  return { outcome: isPartial ? 'partial' : 'evaluated', changes };
104
104
  }
105
105
 
106
- async function patientsToEvaluate({ now, cadenceHours, limit, scope, SweepModel }) {
106
+ async function patientsToEvaluate({
107
+ now, cadenceHours, activeWithinHours, limit, scope, SweepModel,
108
+ }) {
107
109
  const since = new Date(now.getTime() - cadenceHours * HOUR_MS);
110
+ const activeSince = new Date(now.getTime() - activeWithinHours * HOUR_MS);
108
111
  const retrySince = new Date(now.getTime() - RETRY_HOURS * HOUR_MS);
109
112
  const numero = Array.isArray(scope) ? { $in: scope } : { $regex: '^whatsapp:\\+' };
110
113
  const selected = [];
111
114
  for (let page = 0; selected.length < limit && page < MAX_CANDIDATE_PAGES; page += 1) {
112
115
  const active = await aggregateMessages([
113
- { $match: { from_me: false, createdAt: { $gte: since }, numero, origin: { $nin: INTERNAL_ORIGINS }, body: { $regex: '\\S' } } },
116
+ { $match: { from_me: false, createdAt: { $gte: activeSince }, numero, origin: { $nin: INTERNAL_ORIGINS }, body: { $regex: '\\S' } } },
114
117
  { $group: { _id: '$numero', lastInboundAt: { $max: '$createdAt' } } },
115
118
  { $sort: { lastInboundAt: -1, _id: 1 } },
116
119
  { $skip: page * CANDIDATE_PAGE },
117
120
  { $limit: CANDIDATE_PAGE },
118
121
  ]);
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;
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;
128
130
  }
129
131
  return selected.slice(0, limit);
130
132
  }
131
133
 
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
+
132
143
  function validPatientIds(ids) {
133
144
  return [...new Set(ids.filter((id) => /^whatsapp:\+\d{6,20}$/.test(String(id))))];
134
145
  }
@@ -140,11 +151,12 @@ function sweepState(outcome, now) {
140
151
  };
141
152
  }
142
153
 
143
- function stillDue({ now, cadenceHours }) {
154
+ function stillDue({ now, cadenceHours, lastInboundAt }) {
144
155
  const since = new Date(now.getTime() - cadenceHours * HOUR_MS);
145
156
  const retrySince = new Date(now.getTime() - RETRY_HOURS * HOUR_MS);
157
+ const notEvaluatedSince = new Date(Math.min(since.getTime(), new Date(lastInboundAt).getTime()));
146
158
  return [
147
- { $or: [{ lastEvaluatedAt: null }, { lastEvaluatedAt: { $lt: since } }] },
159
+ { $or: [{ lastEvaluatedAt: null }, { lastEvaluatedAt: { $lt: notEvaluatedSince } }] },
148
160
  { $or: [{ lastAttemptAt: null }, { lastAttemptAt: { $lt: retrySince } }] },
149
161
  ];
150
162
  }
@@ -175,7 +187,8 @@ async function settleClaim(SweepModel, patientId, claimToken, update) {
175
187
  }
176
188
 
177
189
  async function runSupportLightSweep({
178
- now = new Date(), patientIds = null, scope = null, cadenceHours = DEFAULT_CADENCE_HOURS, windowDays = DEFAULT_WINDOW_DAYS, limit = 50,
190
+ now = new Date(), patientIds = null, scope = null, cadenceHours = DEFAULT_CADENCE_HOURS, activeWithinHours = cadenceHours,
191
+ windowDays = DEFAULT_WINDOW_DAYS, limit = 50,
179
192
  } = {}, {
180
193
  SweepModel = getSupportLightSweepModel(), evaluate = evaluatePatientSupport, getConfig = getSupportLightEvaluator,
181
194
  clock = () => new Date(), ...deps
@@ -184,12 +197,14 @@ async function runSupportLightSweep({
184
197
  if (!config?.presetId) return { evaluated: 0, partial: 0, skipped: 0, failed: 0, busy: 0, changes: [], outcome: 'not_configured' };
185
198
  const isBackfill = Array.isArray(patientIds);
186
199
  const candidates = isBackfill
187
- ? validPatientIds(patientIds).slice(0, limit)
188
- : await patientsToEvaluate({ now, cadenceHours, limit, scope: scope && validPatientIds(scope), SweepModel });
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
+ });
189
204
  const evaluationDeps = { ...deps, getConfig: async () => config };
190
205
  const summary = { evaluated: 0, partial: 0, skipped: 0, failed: 0, busy: 0, changes: [] };
191
- for (const patientId of candidates) {
192
- const claimToken = await claimPatient(SweepModel, patientId, clock, isBackfill ? [] : stillDue({ now, cadenceHours }));
206
+ for (const { patientId, lastInboundAt } of candidates) {
207
+ const claimToken = await claimPatient(SweepModel, patientId, clock, isBackfill ? [] : stillDue({ now, cadenceHours, lastInboundAt }));
193
208
  if (!claimToken) {
194
209
  summary.busy += 1;
195
210
  continue;
@@ -575,8 +575,6 @@ 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;
580
578
  settle.qualityWarnings = gateWarnings;
581
579
  settle.supportSafetyCleared = !gate.urgentUnder24h
582
580
  && gate.redFlags.every((flag) => flag.verificationStatus === 'denied');
@@ -7,11 +7,7 @@ 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');
12
10
  const { escalationAssessmentLive, escalationUpdateModeLive } = require('../flags/escalationFlags');
13
- const { triageGateFloorLive } = require('../flags/triageGateFloorFlags');
14
- const { clinicalPatternFloorLive } = require('../flags/clinicalPatternFloorFlags');
15
11
  const { attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
16
12
  const { URGENCY_RANK } = require('../../models/escalationReviewModel');
17
13
  const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
@@ -312,16 +308,8 @@ async function handler(args, context = {}) {
312
308
  : null;
313
309
  const anchor = updateMode && review ? escalationAnchorOf(review, alarmId) : null;
314
310
  const keptOpenLevel = Boolean(anchor) && (URGENCY_RANK[anchor.urgencyLevel] || 0) > (URGENCY_RANK[requestedLevel] || 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);
311
+ const urgencyLevel = keptOpenLevel ? anchor.urgencyLevel : requestedLevel;
312
+ const raisesOpen = !anchor || (URGENCY_RANK[requestedLevel] || 0) > (URGENCY_RANK[anchor.urgencyLevel] || 0);
325
313
 
326
314
  trace.setSafetyDecision({ ...(trace.safetyDecision || {}), escalationKind: 'medical_urgent' });
327
315
  trace.setSignals({
@@ -343,8 +331,6 @@ async function handler(args, context = {}) {
343
331
  detailsArg,
344
332
  ...(updateMode ? { mode: 'update', openUrgencyLevel: anchor?.urgencyLevel || null, keptOpenLevel } : {}),
345
333
  ...(clinicalAssessment ? { clinicalAssessment } : {}),
346
- ...(gateFloor ? { triageGateFloor: { ...gateFloor, raised: raisedByGate } } : {}),
347
- ...(patternFloor ? { clinicalPatternFloor: { ...patternFloor, raised: raisedByPattern } } : {}),
348
334
  },
349
335
  });
350
336
 
@@ -386,9 +372,7 @@ async function handler(args, context = {}) {
386
372
  recommendedAction: details.recommended_action || '',
387
373
  urgencyFhir: urgencyLevel,
388
374
  documentation: [
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)' : ''}.` : '',
375
+ keptOpenLevel ? `Actualización: el bot sugirió ${requestedLevel}; se mantiene ${urgencyLevel}.` : '',
392
376
  args?.urgency_justification || '',
393
377
  details.evidence_quote ? `Evidencia: «${details.evidence_quote}»` : '',
394
378
  assessmentNote(clinicalAssessment),
@@ -397,26 +381,24 @@ async function handler(args, context = {}) {
397
381
  keepOpenRow: keptOpenLevel,
398
382
  onRecorded: (recordId) => { emergencyRecordId = recordId; },
399
383
  });
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
- }
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 });
420
402
  }
421
403
  }
422
404
  } else if (urgencyLevel !== 'routine') {
@@ -436,16 +418,6 @@ async function handler(args, context = {}) {
436
418
  follow_up: followUpNote(netArmed, netReason),
437
419
  ...(escalationUpdateModeLive() ? { mode: updateMode ? 'update' : 'new', update_anchor: anchor ? 'open_escalation' : 'none' } : {}),
438
420
  ...(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
- } : {}),
449
421
  ...(isCoerced ? { coerced_urgency: true, requested_urgency_level: requested } : {}),
450
422
  ...(categoryCoerced ? { coerced_category: true, requested_category: requestedCategory } : {}),
451
423
  ...(detailsArg === 'unreadable' ? { details_unreadable: true } : {}),
package/lib/index.d.ts CHANGED
@@ -1061,6 +1061,7 @@ declare module '@peopl-health/nexus' {
1061
1061
  patientIds?: string[] | null;
1062
1062
  scope?: string[] | null;
1063
1063
  cadenceHours?: number;
1064
+ activeWithinHours?: number;
1064
1065
  windowDays?: number;
1065
1066
  limit?: number;
1066
1067
  }, options?: { SweepModel?: unknown; evaluate?: unknown; provider?: unknown }): Promise<{
@@ -29,7 +29,6 @@ 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 },
33
32
  raisedAt: { type: Date, required: true },
34
33
  }, { _id: false });
35
34
 
@@ -549,19 +549,18 @@ 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 levelOf = (alarm) => alarm.appliedLevel || alarm.urgencyLevel;
553
- const rankOf = (alarm) => URGENCY_RANK[levelOf(alarm)] || 0;
552
+ const rankOf = (alarm) => URGENCY_RANK[alarm.urgencyLevel] || 0;
554
553
  const topRank = Math.max(...prior.map(rankOf));
555
554
  const top = prior.filter((alarm) => rankOf(alarm) === topRank);
556
555
  const topRow = [...top].reverse().find((alarm) => alarm.emergencyRecordId);
557
- return { urgencyLevel: levelOf(top[0]), emergencyRecordId: topRow?.emergencyRecordId || null };
556
+ return { urgencyLevel: top[0].urgencyLevel, emergencyRecordId: topRow?.emergencyRecordId || null };
558
557
  }
559
558
 
560
- async function attachEmergencyRow({ reviewId, alarmId, emergencyRecordId, appliedLevel = null }) {
559
+ async function attachEmergencyRow({ reviewId, alarmId, emergencyRecordId }) {
561
560
  try {
562
561
  await getEscalationReview().updateOne(
563
562
  { _id: reviewId, 'alarms.alarmId': alarmId },
564
- { $set: { 'alarms.$.emergencyRecordId': emergencyRecordId, 'alarms.$.appliedLevel': appliedLevel } },
563
+ { $set: { 'alarms.$.emergencyRecordId': emergencyRecordId } },
565
564
  { timestamps: false },
566
565
  );
567
566
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.65.0-dev.11559",
3
+ "version": "5.65.0",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,9 +0,0 @@
1
- const runtimeConfig = require('../../config/runtimeConfig');
2
-
3
- function clinicalPatternFloorLive() {
4
- return String(runtimeConfig.get('ESCALATION_CLINICAL_PATTERN_FLOOR_LIVE', 'true')).trim().toLowerCase() !== 'false';
5
- }
6
-
7
- module.exports = {
8
- clinicalPatternFloorLive,
9
- };
@@ -1,17 +0,0 @@
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
- };
@@ -1,68 +0,0 @@
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 { isPlainObject, safeParse } = require('../../utils/jsonUtils');
7
- const { logger } = require('../../utils/logger');
8
-
9
- const PATTERNS = ['posquirurgico_abdominal', 'toxicidad_gi_quimioterapia', 'toxicidad_gi_inmunoterapia', 'fiebre_quimioterapia'];
10
- const FLOOR_LEVELS = ['asap', 'stat'];
11
-
12
- const text = (value) => (typeof value === 'string' && value.trim() ? value.trim() : null);
13
-
14
- function buildPatternInput({ profile, details, justification, today }) {
15
- const indicators = Array.isArray(details.indicators) ? details.indicators.filter((item) => typeof item === 'string' && item.trim()) : [];
16
- const exposure = buildExposureBlock(profile);
17
- return [
18
- `Fecha de hoy: ${today}`,
19
- '',
20
- '## Escalación que el agente está registrando',
21
- `Síntoma: ${text(details.symptom) || 'no especificado'}`,
22
- `Palabras del paciente: ${text(details.evidence_quote) ? `«${details.evidence_quote.trim()}»` : 'no citadas'}`,
23
- `Indicadores: ${indicators.length ? indicators.join('; ') : 'ninguno'}`,
24
- `Sospecha del agente: ${text(details.suspected_condition) || 'no especificada'}`,
25
- `Justificación del agente: ${text(justification) || 'no especificada'}`,
26
- '',
27
- '## Contexto clínico del paciente',
28
- JSON.stringify(profile),
29
- ...(exposure ? ['', '## Exposición antineoplásica y medicación documentadas', exposure] : []),
30
- ].join('\n');
31
- }
32
-
33
- async function clinicalPatternFloor({ code, turnId = null, details = {}, justification = null, provider = null, now = new Date() }) {
34
- try {
35
- const { presetId } = await getEscalationPatternFloor();
36
- if (!presetId) {
37
- logger.info('[clinicalPatternFloor] No preset is configured; the check is skipped', { turnId });
38
- return null;
39
- }
40
- const profile = await readClinicalProfile(code);
41
- if (!profile) {
42
- logger.warn('[clinicalPatternFloor] The clinical profile is missing or unreadable; the check is skipped', { turnId, profile: profile === undefined ? 'unreadable' : 'missing_or_unparseable' });
43
- return null;
44
- }
45
- const result = await (provider || requireGatewayProvider()).runStructured({
46
- presetId,
47
- input: [{ role: 'user', content: buildPatternInput({ profile, details, justification, today: now.toISOString().slice(0, 10) }) }],
48
- metadata: { subAgent: 'escalation-pattern-floor', turnId },
49
- });
50
- if (result?.status && result.status !== 'completed') throw new Error(`pattern floor incomplete: status=${result.status}`);
51
- const parsed = safeParse(readStructuredText(result), null);
52
- if (!isPlainObject(parsed)) {
53
- logger.warn('[clinicalPatternFloor] The pattern check did not return a JSON object', { turnId });
54
- return null;
55
- }
56
- if (parsed.min_level == null && parsed.pattern == null) return null;
57
- if (!FLOOR_LEVELS.includes(parsed.min_level) || !PATTERNS.includes(parsed.pattern)) {
58
- logger.warn('[clinicalPatternFloor] The pattern check returned an unsupported level or pattern', { turnId, minLevel: parsed.min_level, pattern: parsed.pattern });
59
- return null;
60
- }
61
- return { level: parsed.min_level, pattern: parsed.pattern, evidence: text(parsed.evidence), reason: text(parsed.reason) };
62
- } catch (error) {
63
- logger.error('[clinicalPatternFloor] The clinical pattern check failed', { turnId, error: error.message });
64
- return null;
65
- }
66
- }
67
-
68
- module.exports = { clinicalPatternFloor, buildPatternInput, PATTERNS };
@@ -1,43 +0,0 @@
1
- const { getTriageRecommendationEventModel } = require('../models/triageRecommendationEventModel');
2
- const { triageGateFloorMaxHours } = require('../flags/triageGateFloorFlags');
3
- const { logger } = require('../../utils/logger');
4
-
5
- const HOUR_MS = 60 * 60 * 1000;
6
- const LOOKBACK_MS = 24 * HOUR_MS;
7
- const FLOOR_LEVEL = 'asap';
8
- const PROMPT_ROUTES = ['urgencias', 'emergencia'];
9
-
10
- const settledAt = (event) => new Date(event.createdAt).getTime();
11
- const gateTime = (event) => Math.min(new Date(event.triageAuthoredAt || event.createdAt).getTime(), settledAt(event));
12
-
13
- async function activeTriageGateFloor(code, now = new Date()) {
14
- try {
15
- const gates = await getTriageRecommendationEventModel()
16
- .find({ patientCode: code, gateVerdict: { $ne: null }, createdAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } })
17
- .select('runId triageRecordId urgentUnder24h escalationRoute maxActionTimeHours triageAuthoredAt createdAt')
18
- .lean();
19
- const latest = gates.reduce((best, event) => (!best || gateTime(event) > gateTime(best)
20
- || (gateTime(event) === gateTime(best) && settledAt(event) > settledAt(best)) ? event : best), null);
21
- if (!latest?.urgentUnder24h) return null;
22
-
23
- const hours = Number.isFinite(latest.maxActionTimeHours) ? latest.maxActionTimeHours : null;
24
- const promptRoute = PROMPT_ROUTES.includes(latest.escalationRoute);
25
- if (!promptRoute && (hours === null || hours > triageGateFloorMaxHours())) return null;
26
-
27
- const windowMs = (hours ?? 24) * HOUR_MS;
28
- if (now.getTime() - gateTime(latest) > windowMs) return null;
29
-
30
- return {
31
- level: FLOOR_LEVEL,
32
- runId: latest.runId,
33
- triageRecordId: latest.triageRecordId,
34
- escalationRoute: latest.escalationRoute,
35
- maxActionTimeHours: hours,
36
- };
37
- } catch (error) {
38
- logger.error('[triageGateFloor] The latest triage gate could not be read', { error: error.message });
39
- return null;
40
- }
41
- }
42
-
43
- module.exports = { activeTriageGateFloor };