@peopl-health/nexus 5.72.0-dev.12926 → 5.72.0-dev.13736
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/flags/escalationFlags.js +10 -0
- package/lib/clinical/helpers/chemoContextHelper.js +25 -9
- package/lib/clinical/helpers/clinicalContextHelper.js +4 -1
- package/lib/clinical/helpers/clinicalProfileHelper.js +18 -4
- package/lib/clinical/helpers/drugIdentityHelper.js +60 -0
- package/lib/clinical/helpers/gradeEstimateHelper.js +3 -3
- package/lib/clinical/helpers/triageCaseBaseHelper.js +16 -3
- package/lib/clinical/providers/BaseLLMProvider.js +27 -8
- package/lib/clinical/services/clinicalExtractionService.js +12 -5
- package/lib/clinical/services/clinicalPatternFloorService.js +3 -2
- package/lib/clinical/services/currentRegimenService.js +60 -0
- package/lib/clinical/services/dispatcherService.js +11 -6
- package/lib/clinical/services/escalationDraftService.js +10 -4
- package/lib/clinical/services/gradeAnchorService.js +40 -18
- package/lib/clinical/services/gradeClaimService.js +15 -15
- package/lib/clinical/services/recommendationRankService.js +1 -1
- package/lib/clinical/services/regimenCloserService.js +125 -0
- package/lib/clinical/services/supportInvitability.js +6 -1
- package/lib/clinical/services/triageGateFloorService.js +1 -1
- package/lib/clinical/tools/extractClinicalInfoTool.js +27 -1
- package/lib/clinical/tools/openConditionTool.js +4 -2
- package/lib/clinical/tools/recordClinicalImpressionTool.js +11 -3
- package/lib/clinical/tools/reportMedicalEscalationTool.js +30 -8
- package/lib/clinical/tools/setContingencyPlanTool.js +3 -3
- package/lib/config/airtableConfig.js +2 -0
- package/lib/controllers/escalationReviewController.js +19 -16
- package/lib/core/NexusMessaging.js +60 -9
- package/lib/fhir/constants/escalationCaseStatus.js +31 -0
- package/lib/fhir/constants/projectionSlugs.js +6 -0
- package/lib/fhir/index.js +2 -1
- package/lib/fhir/projections/contextFactProjection.js +1 -0
- package/lib/fhir/resources/CommunicationRequest.js +1 -1
- package/lib/fhir/resources/Task.js +42 -1
- package/lib/fhir/services/escalationService.js +13 -0
- package/lib/index.d.ts +72 -2
- package/lib/index.js +6 -0
- package/lib/models/escalationReviewModel.js +34 -2
- package/lib/services/escalationCaseTaskService.js +35 -0
- package/lib/services/escalationReviewService.js +284 -48
- package/lib/services/reviewAlertSweepService.js +7 -2
- package/lib/services/reviewBoardService.js +2 -0
- package/lib/services/threadService.js +2 -1
- package/lib/shared/dtos/DispatchedEscalation.js +1 -0
- package/lib/utils/dateUtils.js +4 -0
- package/lib/utils/retryUtils.js +1 -0
- package/package.json +1 -1
|
@@ -10,7 +10,17 @@ function escalationAssessmentLive() {
|
|
|
10
10
|
return flagOn('ESCALATION_ASSESSMENT_LIVE');
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
function feverPatientTimerLive() {
|
|
14
|
+
return flagOn('FEVER_PATIENT_TIMER_LIVE');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function escalationPatientTimerLive() {
|
|
18
|
+
return flagOn('ESCALATION_PATIENT_TIMER_LIVE');
|
|
19
|
+
}
|
|
20
|
+
|
|
13
21
|
module.exports = {
|
|
14
22
|
escalationAssessmentLive,
|
|
23
|
+
escalationPatientTimerLive,
|
|
15
24
|
escalationUpdateModeLive,
|
|
25
|
+
feverPatientTimerLive,
|
|
16
26
|
};
|
|
@@ -1,17 +1,16 @@
|
|
|
1
|
-
const { mexicoDay } = require('../../utils/dateUtils');
|
|
1
|
+
const { daysBetween, mexicoDay } = require('../../utils/dateUtils');
|
|
2
2
|
const { foldAccents } = require('../../utils/formatUtils');
|
|
3
3
|
const { safeParse, isPlainObject } = require('../../utils/jsonUtils');
|
|
4
4
|
const { logger } = require('../../utils/logger');
|
|
5
5
|
|
|
6
6
|
const ACTIVE_DAYS = 35;
|
|
7
|
-
const HEADER = 'Quimioterapia (registro de la unidad de quimioterapia; úsalo para contextualizar y priorizar síntomas, nunca para bajar la urgencia; no comuniques dosis ni ajustes de tratamiento; si el paciente dice
|
|
7
|
+
const HEADER = 'Quimioterapia (registro de la unidad de quimioterapia; úsalo para contextualizar y priorizar síntomas, nunca para bajar la urgencia; no comuniques dosis ni ajustes de tratamiento; si el paciente dice algo distinto, créele: si es otra fecha de cita, que el paciente la confirme con el área de tratamiento, sin avisar al equipo; si es un dato clínico, o una sesión suspendida o cambiada por un motivo clínico, avisa al equipo)';
|
|
8
8
|
const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
9
9
|
const NO_ALLERGY = /^(ninguna?s?|no|negadas?|desconocidas?|(niega|no refiere|sin|no tiene|no presenta) alergias?( conocidas| a medicamentos)?)$/;
|
|
10
10
|
const NEGATION = /\b(sin|niega|no|ninguna?)\b/;
|
|
11
11
|
|
|
12
12
|
const isDay = (value) => typeof value === 'string' && ISO_DAY.test(value) && !Number.isNaN(Date.parse(`${value}T00:00:00Z`));
|
|
13
13
|
const dmy = (iso) => `${iso.slice(8, 10)}/${iso.slice(5, 7)}/${iso.slice(0, 4)}`;
|
|
14
|
-
const daysBetween = (from, to) => Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 86400000);
|
|
15
14
|
const addDays = (iso, days) => new Date(Date.parse(`${iso}T00:00:00Z`) + days * 86400000).toISOString().slice(0, 10);
|
|
16
15
|
const fold = (value) => foldAccents(String(value || '')).toLowerCase().trim();
|
|
17
16
|
const text = (value) => (typeof value === 'string' ? value.trim() : '');
|
|
@@ -25,6 +24,7 @@ function normalize(raw) {
|
|
|
25
24
|
const dated = (value, keys) => (isPlainObject(value) && isDay(value.fecha) && keys.every((k) => k in value) ? value : null);
|
|
26
25
|
return {
|
|
27
26
|
ultimaAplicacion: last,
|
|
27
|
+
ultimaCitotoxica: dayOr(raw.ultimaCitotoxica),
|
|
28
28
|
esquema: list(raw.esquema).filter(isPlainObject).filter((e) => text(e.farmaco)),
|
|
29
29
|
vigilancia: texts(raw.vigilancia),
|
|
30
30
|
nadirDias: nadir,
|
|
@@ -41,6 +41,7 @@ function normalize(raw) {
|
|
|
41
41
|
ajusteProximoCiclo: dated(raw.ajusteProximoCiclo, ['valor']),
|
|
42
42
|
esquemaPrevio: isPlainObject(raw.esquemaPrevio) && isDay(raw.esquemaPrevio.hasta) ? { farmacos: texts(raw.esquemaPrevio.farmacos), hasta: raw.esquemaPrevio.hasta } : null,
|
|
43
43
|
visitaSoporte: dated(raw.visitaSoporte, ['farmacos']),
|
|
44
|
+
proximaVisitaSoporte: dated(raw.proximaVisitaSoporte, ['detalle']),
|
|
44
45
|
antecedentes: dated(raw.antecedentes, []),
|
|
45
46
|
};
|
|
46
47
|
}
|
|
@@ -50,13 +51,23 @@ function parseChemoContext(raw) {
|
|
|
50
51
|
return isPlainObject(parsed) && parsed.version === 1 ? normalize(parsed) : null;
|
|
51
52
|
}
|
|
52
53
|
|
|
53
|
-
function
|
|
54
|
+
function daysSinceLastCytotoxic(context, today = mexicoDay(new Date())) {
|
|
55
|
+
return context?.ultimaCitotoxica ? daysBetween(context.ultimaCitotoxica, today) : null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function chemoStatus(context, today, windowDays = ACTIVE_DAYS) {
|
|
54
59
|
const last = context.ultimaAplicacion?.fecha;
|
|
55
60
|
if (!last) return { active: false, days: null };
|
|
56
61
|
const days = daysBetween(last, today);
|
|
57
62
|
if (days < 0) return { active: true, days: null };
|
|
58
63
|
const scheduled = context.proximaSesion && context.proximaSesion.fecha >= today;
|
|
59
|
-
return { active: days <=
|
|
64
|
+
return { active: days <= windowDays || Boolean(scheduled), days };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// the unit confirms an appointment the day before: unconfirmed is the normal state of a later one
|
|
68
|
+
function confirmation(appointment) {
|
|
69
|
+
if (typeof appointment.confirmada !== 'boolean') return '';
|
|
70
|
+
return appointment.confirmada ? 'confirmada por la unidad' : 'la unidad aún no la confirma';
|
|
60
71
|
}
|
|
61
72
|
|
|
62
73
|
function regimenText(context) {
|
|
@@ -94,10 +105,15 @@ function chemoLines(context, today) {
|
|
|
94
105
|
? `Inicio de este esquema: antes del ${dmy(context.inicioEsquema.fecha)} (inicio del registro)`
|
|
95
106
|
: `Inicio de este esquema: ${dmy(context.inicioEsquema.fecha)}`);
|
|
96
107
|
}
|
|
97
|
-
if (context.proximaSesion) {
|
|
108
|
+
if (context.proximaSesion && context.proximaSesion.fecha >= today) {
|
|
98
109
|
lines.push(context.proximaSesion.tipo === 'agendada'
|
|
99
|
-
? `Próxima sesión: ${dmy(context.proximaSesion.fecha)} (agendada)`
|
|
100
|
-
: `Próxima sesión: ${dmy(context.proximaSesion.fecha)} (estimada; no la confirmes como cita)`);
|
|
110
|
+
? `Próxima sesión de quimioterapia: ${dmy(context.proximaSesion.fecha)} (${['agendada', confirmation(context.proximaSesion)].filter(Boolean).join('; ')})`
|
|
111
|
+
: `Próxima sesión de quimioterapia: ${dmy(context.proximaSesion.fecha)} (estimada; no la confirmes como cita)`);
|
|
112
|
+
}
|
|
113
|
+
const support = context.proximaVisitaSoporte;
|
|
114
|
+
if (support && support.fecha >= today) {
|
|
115
|
+
const care = texts(support.detalle);
|
|
116
|
+
lines.push(`Próxima visita a la unidad sin quimioterapia: ${dmy(support.fecha)} (${[care.join(', '), confirmation(support)].filter(Boolean).join('; ')})`);
|
|
101
117
|
}
|
|
102
118
|
if (context.noAplicadas.length) lines.push(`Sesiones no aplicadas en los últimos 90 días: ${context.noAplicadas.map(dmy).join(', ')}`);
|
|
103
119
|
if (text(context.reaccionInfusion?.texto)) lines.push(`Reacción durante la infusión registrada: ${text(context.reaccionInfusion.texto)} (${dmy(context.reaccionInfusion.fecha)})`);
|
|
@@ -162,4 +178,4 @@ function withChemoContext(clinical, context, today = mexicoDay(new Date())) {
|
|
|
162
178
|
}
|
|
163
179
|
}
|
|
164
180
|
|
|
165
|
-
module.exports = { parseChemoContext, renderChemoContext, withChemoContext };
|
|
181
|
+
module.exports = { chemoStatus, daysSinceLastCytotoxic, parseChemoContext, renderChemoContext, withChemoContext };
|
|
@@ -32,6 +32,8 @@ const VALUE_SEPARATOR = ', ';
|
|
|
32
32
|
const PART_SEPARATOR = '. ';
|
|
33
33
|
const SECTION_SEPARATOR = '\n\n';
|
|
34
34
|
const RETRACTED = new Set(['resolved', 'inactive', 'stopped', 'not-done']);
|
|
35
|
+
// still stored and covering the field, but not rendered as what the patient has now
|
|
36
|
+
const NOT_CURRENT = new Set(['completed', 'not-taking', 'preparation']);
|
|
35
37
|
|
|
36
38
|
const isRetracted = (status) => RETRACTED.has(status);
|
|
37
39
|
|
|
@@ -48,7 +50,8 @@ const preferring = (rows, uninformative) => {
|
|
|
48
50
|
};
|
|
49
51
|
|
|
50
52
|
function renderableValues(bucket) {
|
|
51
|
-
|
|
53
|
+
const current = preferring(bucket, LEGACY_CONCEPT).filter((row) => !NOT_CURRENT.has(row.status));
|
|
54
|
+
return preferring(current, NO_KNOWN_ALLERGY.concept).map((row) => decodePair(row.value));
|
|
52
55
|
}
|
|
53
56
|
|
|
54
57
|
function fieldsFromFhir(rows, patient) {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const { resolveProfileIdentity } = require('../services/patientProfileService');
|
|
2
2
|
const { safeParse } = require('../../utils/jsonUtils');
|
|
3
|
+
const { parseChemoContext } = require('./chemoContextHelper');
|
|
3
4
|
|
|
4
5
|
const CONTEXT_FIELD = 'clinical-context-json';
|
|
5
6
|
|
|
@@ -32,15 +33,28 @@ function richestProfile(records) {
|
|
|
32
33
|
return parsed[0].profile;
|
|
33
34
|
}
|
|
34
35
|
|
|
35
|
-
|
|
36
|
+
// null: no profile; undefined: unreadable
|
|
37
|
+
async function readResolvedRecord(code) {
|
|
36
38
|
try {
|
|
37
39
|
const identity = await resolveProfileIdentity(code);
|
|
38
40
|
if (identity.kind === 'missing') return null;
|
|
39
|
-
|
|
40
|
-
return richestProfile([identity.record]);
|
|
41
|
+
return identity.kind === 'resolved' ? identity.record : undefined;
|
|
41
42
|
} catch {
|
|
42
43
|
return undefined;
|
|
43
44
|
}
|
|
44
45
|
}
|
|
45
46
|
|
|
46
|
-
|
|
47
|
+
async function readClinicalProfile(code) {
|
|
48
|
+
const record = await readResolvedRecord(code);
|
|
49
|
+
return record ? richestProfile([record]) : record;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// null: no chemo record; undefined: unreadable or unparseable
|
|
53
|
+
async function readRecordedChemo(code) {
|
|
54
|
+
const record = await readResolvedRecord(code);
|
|
55
|
+
if (!record) return record;
|
|
56
|
+
if (!record.quimio_context) return null;
|
|
57
|
+
return parseChemoContext(record.quimio_context) ?? undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
module.exports = { readClinicalProfile, readRecordedChemo, richestProfile };
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
const { foldAccents } = require('../../utils/formatUtils');
|
|
2
|
+
|
|
3
|
+
const MAX_ALIAS_WORDS = 4;
|
|
4
|
+
const PART_SEPARATORS = /\s*(?:\+|±|,|;|\/|\(|\)|\by\b|\bcon\b)\s*/;
|
|
5
|
+
// a dose or a route left between separators ("100 MG / 20 ML en 500 ML glucosado", "IV/SC") names no drug
|
|
6
|
+
const DOSE_OR_ROUTE = /^(\d+|iv|sc|im|vo|po|ev|mg|ml|mcg|ui)(\s|$)/;
|
|
7
|
+
|
|
8
|
+
// one key for a brand, a Spanish and an English spelling: ciclofosfamida and cyclophosphamide meet
|
|
9
|
+
const drugKey = (name) => foldAccents(String(name ?? '')).toLowerCase()
|
|
10
|
+
.replace(/[^a-z0-9\s-]/g, ' ')
|
|
11
|
+
.replace(/ph/g, 'f').replace(/th/g, 't').replace(/y/g, 'i').replace(/rr/g, 'r')
|
|
12
|
+
.replace(/(ina|ine)\b/g, 'in')
|
|
13
|
+
.replace(/([a-z]{3})[aeo]\b/g, '$1')
|
|
14
|
+
.replace(/\s+/g, ' ')
|
|
15
|
+
.trim();
|
|
16
|
+
|
|
17
|
+
const lines = (text) => String(text ?? '').split(/[\n,;]+/).map((line) => line.trim()).filter(Boolean);
|
|
18
|
+
|
|
19
|
+
function buildDrugIdentity(catalog) {
|
|
20
|
+
const generics = new Map();
|
|
21
|
+
const aliases = new Map();
|
|
22
|
+
for (const row of catalog) {
|
|
23
|
+
const generic = String(row.generico ?? '').trim();
|
|
24
|
+
if (!generic) continue;
|
|
25
|
+
const key = drugKey(generic);
|
|
26
|
+
if (!generics.has(key)) generics.set(key, { generic, group: row.grupo ?? null });
|
|
27
|
+
for (const alias of [generic, row.farmaco, ...lines(row.variantes)]) {
|
|
28
|
+
const aliasKey = drugKey(alias);
|
|
29
|
+
if (aliasKey && !aliases.has(aliasKey)) aliases.set(aliasKey, key);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return { generics, aliases };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function genericsInPart(words, identity) {
|
|
36
|
+
const found = new Set();
|
|
37
|
+
for (let at = 0; at < words.length;) {
|
|
38
|
+
let span = Math.min(MAX_ALIAS_WORDS, words.length - at);
|
|
39
|
+
for (; span > 0 && !identity.aliases.has(words.slice(at, at + span).join(' ')); span -= 1);
|
|
40
|
+
if (span) found.add(identity.aliases.get(words.slice(at, at + span).join(' ')));
|
|
41
|
+
at += span || 1;
|
|
42
|
+
}
|
|
43
|
+
return found;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// every drug the text names; unresolved when some part of it names none the catalog knows
|
|
47
|
+
function drugsNamed(text, identity) {
|
|
48
|
+
const whole = identity.aliases.get(drugKey(text));
|
|
49
|
+
if (whole) return { drugs: [identity.generics.get(whole)], unresolved: false };
|
|
50
|
+
const keys = new Set();
|
|
51
|
+
let unresolved = false;
|
|
52
|
+
for (const part of String(text ?? '').split(PART_SEPARATORS).map(drugKey).filter(Boolean)) {
|
|
53
|
+
const found = genericsInPart(part.split(' '), identity);
|
|
54
|
+
if (!found.size && !DOSE_OR_ROUTE.test(part)) unresolved = true;
|
|
55
|
+
found.forEach((key) => keys.add(key));
|
|
56
|
+
}
|
|
57
|
+
return { drugs: [...keys].map((key) => identity.generics.get(key)), unresolved: unresolved || !keys.size };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
module.exports = { drugKey, buildDrugIdentity, drugsNamed };
|
|
@@ -68,16 +68,16 @@ function gradeEstimateSchema(description) {
|
|
|
68
68
|
functional_anchor: {
|
|
69
69
|
type: 'string',
|
|
70
70
|
enum: FUNCTIONAL_ANCHORS,
|
|
71
|
-
description: 'What you ESTABLISHED about function, not what the clause says. Required whenever the rubric clause for your grade turns on ADL — grade 2 on instrumental ADL, grade 3 on self-care. `instrumental_adl_limited`: they told you the symptom stops them cooking, working, shopping, driving. `self_care_adl_limited`: it stops them bathing, dressing, feeding themselves. `not_limited`: you asked and it does NOT limit them — then
|
|
71
|
+
description: 'What you ESTABLISHED about function, not what the clause says. Required whenever the rubric clause for your grade turns on ADL — grade 2 on instrumental ADL, grade 3 on self-care. `instrumental_adl_limited`: they told you the symptom stops them cooking, working, shopping, driving. `self_care_adl_limited`: it stops them bathing, dressing, feeding themselves. `not_limited`: you asked and it does NOT limit them — the grade then stands only on another part of its clause (regular laxatives, moderate pain, a measured value); with nothing else met, record the grade below. `not_established`: you have not asked. Grade from the whole clause and the whole picture — a non-functional part of the clause that is met, or intensity, regimen, cycle day and trajectory that make that grade the most likely one — name in reasoning what supports it, keep the grade below in possible_range, and ask the patient the one functional question that would confirm it in your reply. Missing ADL information is not evidence that function is preserved, and it never moves a grade more than one step above what the evidence strictly shows. When the clause names a specific finding — manual evacuation indicated, at rest, IV fluids, hospitalization — that grade needs that finding: intensity words alone do not reach it, so record the grade the evidence meets and keep the higher one in possible_range.',
|
|
72
72
|
},
|
|
73
73
|
improvement_basis: {
|
|
74
74
|
type: ['string', 'null'],
|
|
75
|
-
description: 'REQUIRED when best_estimate is lower than the grade this case already holds. Name the finding that no longer holds, in the patient\'s own terms — what they can do again, or the symptom that stopped. A grade only comes down when something specific resolved; "mejoró un poco" is not that, and neither is the absence of new complaints.',
|
|
75
|
+
description: 'REQUIRED when best_estimate is lower than the grade this case already holds. Name the finding that no longer holds, in the patient\'s own terms — what they can do again, or the symptom that stopped. A grade only comes down when something specific resolved; "mejoró un poco" is not that, and neither is the absence of new complaints. Correcting an over-call is the same: name the finding that rules the higher grade out ("cocina y trabaja como siempre").',
|
|
76
76
|
},
|
|
77
77
|
source: {
|
|
78
78
|
type: 'string',
|
|
79
79
|
enum: GRADE_SOURCES,
|
|
80
|
-
description: 'Where this grade came from. Required whenever you set best_estimate. `proctcae_composite`: you are carrying over the number the PRO-CTCAE triage already computed — say this even when you agree with it. `agent_adjudicated`: you read the grade_scale clauses yourself against what the patient said. `carried_forward`: the case\'s previous grade, unchanged, with no new evidence this turn.',
|
|
80
|
+
description: 'Where this grade came from. Required whenever you set best_estimate. `proctcae_composite`: you are carrying over the number the PRO-CTCAE triage already computed — say this even when you agree with it. When what the patient tells you this turn contradicts that number (they can do today what the questionnaire said they could not), what they tell you now wins: when the term has a grade_scale, grade it yourself as `agent_adjudicated`. `agent_adjudicated`: you read the grade_scale clauses yourself against what the patient said. `carried_forward`: the case\'s previous grade, unchanged, with no new evidence this turn.',
|
|
81
81
|
},
|
|
82
82
|
matched_grade: {
|
|
83
83
|
type: ['integer', 'null'],
|
|
@@ -94,6 +94,19 @@ const DIMENSION_ES = {
|
|
|
94
94
|
amount: 'cantidad',
|
|
95
95
|
};
|
|
96
96
|
|
|
97
|
+
const ADHERENCE_ES = {
|
|
98
|
+
full: 'la siguió',
|
|
99
|
+
partial: 'la siguió en parte',
|
|
100
|
+
none: 'no la siguió',
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const CHANGE_ES = {
|
|
104
|
+
improved: 'mejoró',
|
|
105
|
+
unchanged: 'sigue igual',
|
|
106
|
+
worsened: 'empeoró',
|
|
107
|
+
mixed: 'mixto',
|
|
108
|
+
};
|
|
109
|
+
|
|
97
110
|
const GRADE_BASIS_ES = {
|
|
98
111
|
composite: 'la tabla compuesta del PRO-CTCAE resolvió el grado con las respuestas de arriba',
|
|
99
112
|
presence: 'sólo se preguntó si el síntoma estaba presente; el grado no sale de una escala de severidad',
|
|
@@ -272,9 +285,9 @@ function buildAdherenceBlock(priorResolutions = []) {
|
|
|
272
285
|
.map((row) => {
|
|
273
286
|
const symptom = row.symptoms_patient_facing || row.element_name_short || 'sin síntoma registrado';
|
|
274
287
|
const recommendation = row.patient_main_recommendation || 'sin texto registrado';
|
|
275
|
-
const adherence = row.adherence_level || 'sin respuesta';
|
|
276
|
-
const change = row.symptom_change || 'sin respuesta';
|
|
277
|
-
return `- Síntoma(s): ${symptom} · Recomendación previa: ${recommendation} · Adherencia reportada: ${adherence} · Cambio
|
|
288
|
+
const adherence = ADHERENCE_ES[row.adherence_level] || row.adherence_level || 'sin respuesta';
|
|
289
|
+
const change = CHANGE_ES[row.symptom_change] || row.symptom_change || 'sin respuesta';
|
|
290
|
+
return `- Síntoma(s): ${symptom} · Recomendación previa: ${recommendation} · Adherencia reportada: ${adherence} · Cambio que reportó después de esa recomendación: ${change}`;
|
|
278
291
|
})
|
|
279
292
|
.join('\n');
|
|
280
293
|
}
|
|
@@ -317,6 +317,7 @@ class BaseLLMProvider {
|
|
|
317
317
|
...this._buildFollowUpPolicyMessage(toolIds),
|
|
318
318
|
...this._buildFollowUpMessage(promptVariables),
|
|
319
319
|
...this._buildFollowUpCheckMessage(toolIds),
|
|
320
|
+
...this._buildContingencyCheckMessage(promptVariables, toolIds),
|
|
320
321
|
...this._buildClockMessage(promptVariables, interpolatedVariables),
|
|
321
322
|
...messages,
|
|
322
323
|
...this._buildOutreachBriefMessage({ outreachBrief, toolIds }),
|
|
@@ -377,7 +378,9 @@ class BaseLLMProvider {
|
|
|
377
378
|
'Si una contingencia activa ya cubre la preocupación, no la cruces con otro seguimiento. Si programas, primero usa schedulePatientReminder con reminder_type seguimiento y la misma utility_basis concreta; luego registra hold con el mismo next_check_at.',
|
|
378
379
|
'',
|
|
379
380
|
'Si escribes, que sea para ELLA: lo que te contó, lo que quedó abierto, lo que quieres saber ahora.',
|
|
380
|
-
'
|
|
381
|
+
'Tu texto llega dentro de una plantilla que ya empieza con «Hola {su nombre},»: no saludes ni escribas su nombre, entra directo a lo que quieres decirle, breve (menos de 500 caracteres) y con un emoji como máximo. Es un contacto sobre su cuidado: no le sumes invitaciones a charlas, sesiones ni actividades.',
|
|
382
|
+
'LÍMITE UTILITY: escribe sólo cuando puedas anclar el contacto en algo concreto que la paciente contó, preguntó o acordó, o en una interacción de cuidado todavía vigente. La inactividad por sí sola no basta. Si escribes, registra esa ancla en utility_basis; si sólo queda un saludo general para generar engagement, registra hold con hold_reason no_utility_anchor y utility_basis null. El mensaje tiene que nombrar esa ancla; preguntarle cómo se ha sentido o invitarla a escribir si tiene dudas no es un ancla.',
|
|
383
|
+
'Debe entenderse por sí mismo: si mencionas fechas, un documento o algo que le enviaste, di cuáles. No enumeres señales de alarma; si vigilas algo concreto, menciona sólo esa señal y pídele que te escriba en cuanto aparezca.',
|
|
381
384
|
'No repitas un mensaje que ya le enviaste, y no menciones automatizaciones, listas ni seguimientos programados.',
|
|
382
385
|
);
|
|
383
386
|
|
|
@@ -421,21 +424,37 @@ class BaseLLMProvider {
|
|
|
421
424
|
const windows = net?.patientReminder?.firesAfterSilenceMinutes
|
|
422
425
|
? `check-in al paciente tras ${net.patientReminder.firesAfterSilenceMinutes} min de silencio`
|
|
423
426
|
: '';
|
|
424
|
-
|
|
425
|
-
? ' El check-in ya se envió: si este mensaje lo contesta, resuelve la red o el caso.'
|
|
426
|
-
: '';
|
|
427
|
-
parts.push(`- ACTIVA ${plan.planId} — vigila: ${sanitizeInlineText(plan.concern)} (${target}). Espera observar: ${sanitizeInlineText(plan.awaitingCharacterization)}. ${windows}.${fired}`);
|
|
427
|
+
parts.push(`- ACTIVA ${plan.planId} — vigila: ${sanitizeInlineText(plan.concern)} (${target}). Espera observar: ${sanitizeInlineText(plan.awaitingCharacterization)}. ${windows}.`);
|
|
428
428
|
}
|
|
429
429
|
for (const net of cancelled) {
|
|
430
430
|
const plan = net?.carePlan || {};
|
|
431
431
|
parts.push(`- (este turno) ${plan.planId} — la red que vigilaba "${sanitizeInlineText(plan.concern)}" se desactivó automáticamente porque el paciente escribió. Si todavía falta un dato de la rúbrica que podría subir el grado, considera rearmarla con setContingencyPlan. Si ya no falta ese dato y sólo quieres saber cómo sigue, programa un seguimiento (schedulePatientReminder, reminder_type seguimiento) en lugar de rearmarla.`);
|
|
432
432
|
}
|
|
433
|
-
if (active.length) {
|
|
434
|
-
parts.push('DECISIÓN ESTE TURNO: si el mensaje del paciente responde lo que una red espera observar, llama setContingencyPlan {action: \'resolve\', plan_id: \'<plan>\', resolution_reasoning: \'…\'} o cierra el caso. Si cambió la preocupación o la ventana, usa {action: \'rearm\'}. Si el mensaje trata de otra cosa, no hagas nada con la red.');
|
|
435
|
-
}
|
|
436
433
|
return [{ role: 'developer', content: parts.join('\n') }];
|
|
437
434
|
}
|
|
438
435
|
|
|
436
|
+
// Rides behind the history like the follow-up check: the nets block above lists the nets, the decision lives here,
|
|
437
|
+
// because an unresolved net later asks the patient a question they had already answered.
|
|
438
|
+
// Only answers given after the net was armed count: an escalation net waits for how the reported symptom evolved.
|
|
439
|
+
_buildContingencyCheckMessage(promptVariables, toolIds = []) {
|
|
440
|
+
if (!(toolIds || []).includes('setContingencyPlan')) return [];
|
|
441
|
+
const active = Array.isArray(promptVariables?.active_contingencies) ? promptVariables.active_contingencies : [];
|
|
442
|
+
if (!active.length) return [];
|
|
443
|
+
const waiting = active.map(({ carePlan: plan = {} } = {}) => {
|
|
444
|
+
const fired = plan.status === 'fired_reminder' ? ' Su check-in ya se envió.' : '';
|
|
445
|
+
return `- ${plan.planId} (armada ${localFireTime(plan.createdAt)}) espera: ${sanitizeInlineText(plan.awaitingCharacterization)}.${fired}`;
|
|
446
|
+
});
|
|
447
|
+
return [{
|
|
448
|
+
role: 'developer',
|
|
449
|
+
content: [
|
|
450
|
+
'## Antes de entregar tu respuesta: redes activas',
|
|
451
|
+
...waiting,
|
|
452
|
+
'DECISIÓN ESTE TURNO: si el paciente ya respondió lo que una red espera después de que se armó — en este mensaje o en uno anterior, también cuando se lo contestó al equipo —, resuélvela ahora con setContingencyPlan {action: \'resolve\', plan_id: \'<plan>\', resolution_reasoning: \'…\'} o cierra el caso; si no, su check-in le volverá a preguntar lo mismo. Si cambió la preocupación o la ventana, usa {action: \'rearm\'}. Lo que el paciente contó antes de que se armara no cuenta, y una indicación del equipo tampoco es una respuesta. Si nada responde lo que espera, no hagas nada con la red.',
|
|
453
|
+
].join('\n'),
|
|
454
|
+
[TAIL_PLACEMENT]: true,
|
|
455
|
+
}];
|
|
456
|
+
}
|
|
457
|
+
|
|
439
458
|
// Rides behind the history, next to the turn: a rule buried in the policy block above was not applied.
|
|
440
459
|
_buildFollowUpCheckMessage(toolIds = []) {
|
|
441
460
|
if (!(toolIds || []).includes('schedulePatientReminder')) return [];
|
|
@@ -78,11 +78,18 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
|
|
|
78
78
|
const { datosClinicos, contextGaps } = await loadPatientContext(code);
|
|
79
79
|
const vagueWords = await getVagueEntityWords();
|
|
80
80
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
81
|
+
let timed;
|
|
82
|
+
try {
|
|
83
|
+
timed = await withTiming(() => provider.runStructured({
|
|
84
|
+
presetId,
|
|
85
|
+
input: [{ role: 'user', content: buildExtractorInput(text, detectedTags, curatedRows, template, { priorTurns, patientContext: datosClinicos }) }],
|
|
86
|
+
metadata: { extractor: 'clinical-mention', turnId },
|
|
87
|
+
}));
|
|
88
|
+
} catch (err) {
|
|
89
|
+
logger.error('[clinicalExtraction] extractor provider unavailable; returning deterministic safety flags only', { turnId, error: err?.message });
|
|
90
|
+
return { completed: false, unavailable: Boolean(patterns?.length), clinicalMentions: [], safetyFlags: [...flags], safetyFlagSources: sources() };
|
|
91
|
+
}
|
|
92
|
+
const { result, durationMs } = timed;
|
|
86
93
|
trace?.addSubCall({ response: result, durationMs, presetId });
|
|
87
94
|
|
|
88
95
|
if (result?.status && result.status !== 'completed') throw new Error(`clinical extraction incomplete: status=${result.status}`);
|
|
@@ -13,7 +13,8 @@ const { redactDirectIdentifiers } = require('../../utils/sanitizerUtils');
|
|
|
13
13
|
const { withTimeout } = require('../../utils/timeoutUtils');
|
|
14
14
|
const { composePrompt } = require('./promptComposerService');
|
|
15
15
|
|
|
16
|
-
const FLOOR_LEVELS = ['asap', 'stat'];
|
|
16
|
+
const FLOOR_LEVELS = ['urgent', 'asap', 'stat'];
|
|
17
|
+
const FLOOR_CEILING = 'urgent';
|
|
17
18
|
const PATTERN_NAME = /^[a-z0-9_]{1,64}$/;
|
|
18
19
|
const UNLABELLED_PATTERN = 'sin_etiqueta';
|
|
19
20
|
const MAX_TEXT_LENGTH = 500;
|
|
@@ -120,7 +121,7 @@ async function evaluatePatternFloor({ code, turnId, details, justification, prov
|
|
|
120
121
|
return degraded('unsupported_level', check);
|
|
121
122
|
}
|
|
122
123
|
return {
|
|
123
|
-
floor: { level:
|
|
124
|
+
floor: { level: FLOOR_CEILING, pattern: normalizePattern(parsed.pattern), evidence: clippedText(parsed.evidence), reason: clippedText(parsed.reason) },
|
|
124
125
|
degraded: null,
|
|
125
126
|
check,
|
|
126
127
|
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
const { chemoStatus } = require('../helpers/chemoContextHelper');
|
|
2
|
+
const { daysBetween, mexicoDay } = require('../../utils/dateUtils');
|
|
3
|
+
const { foldAccents } = require('../../utils/formatUtils');
|
|
4
|
+
|
|
5
|
+
// long enough for immunotherapy or a hormone depot given every three months
|
|
6
|
+
const UNIT_WINDOW_DAYS = 100;
|
|
7
|
+
const CONFIRMED_DAYS = 90;
|
|
8
|
+
const FACTS_WINDOW_DAYS = 60;
|
|
9
|
+
const ORAL_VARIABLE = 'oral_onco_summary';
|
|
10
|
+
const RADIOTHERAPY_VARIABLE = 'radiotherapy_summary';
|
|
11
|
+
const TREATMENT_VARIABLES = Object.freeze(['injectable_onco_summary', ORAL_VARIABLE, RADIOTHERAPY_VARIABLE]);
|
|
12
|
+
// order headings the unit's parser can leave in a regimen: a kind of treatment, not a drug
|
|
13
|
+
const GENERIC_ENTRY = /^(citotoxicos?|biologicos?|inmunoterapia|quimioterapia)$/;
|
|
14
|
+
|
|
15
|
+
const isTreatment = (row) => TREATMENT_VARIABLES.includes(row.variableId);
|
|
16
|
+
const isOral = (row) => row.variableId === ORAL_VARIABLE;
|
|
17
|
+
const within = (row, until, days) => {
|
|
18
|
+
const since = mexicoDay(row.validTime);
|
|
19
|
+
return since !== null && daysBetween(since, until) <= days;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// an ongoing oral is rarely restated, so an old one is kept but marked unconfirmed rather than dropped
|
|
23
|
+
const withOralAge = (row, today) => (within(row, today, CONFIRMED_DAYS) ? row : { ...row, unconfirmed: true });
|
|
24
|
+
|
|
25
|
+
function uniqueDrugs(esquema) {
|
|
26
|
+
const key = (drug) => foldAccents(drug).toLowerCase().replace(/[.\s]+$/, '');
|
|
27
|
+
const drugs = esquema.map((entry) => entry.farmaco.trim()).filter((drug) => !GENERIC_ENTRY.test(key(drug)));
|
|
28
|
+
return [...new Map(drugs.map((drug) => [key(drug), drug])).values()];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function unitRegimen(chemo, today) {
|
|
32
|
+
const last = chemo?.ultimaAplicacion?.fecha;
|
|
33
|
+
if (!last) return null;
|
|
34
|
+
const next = chemo.proximaSesion?.fecha >= today ? chemo.proximaSesion.fecha : null;
|
|
35
|
+
return {
|
|
36
|
+
drugs: uniqueDrugs(chemo.esquema),
|
|
37
|
+
since: chemo.inicioEsquema?.fecha ?? null,
|
|
38
|
+
lastApplication: last,
|
|
39
|
+
nextSession: next,
|
|
40
|
+
current: chemoStatus(chemo, today, UNIT_WINDOW_DAYS).active,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function currentRegimen({ chemo, facts, today = mexicoDay(new Date()) }) {
|
|
45
|
+
const rows = Array.isArray(facts) ? facts : [];
|
|
46
|
+
const others = rows.filter((row) => !isTreatment(row));
|
|
47
|
+
const orals = rows.filter(isOral).map((row) => withOralAge(row, today));
|
|
48
|
+
const unit = unitRegimen(chemo, today);
|
|
49
|
+
if (unit) {
|
|
50
|
+
const radiotherapy = rows.filter((row) => row.variableId === RADIOTHERAPY_VARIABLE && within(row, today, CONFIRMED_DAYS));
|
|
51
|
+
return { source: 'unit', unit, facts: [...orals, ...radiotherapy, ...others] };
|
|
52
|
+
}
|
|
53
|
+
const treatments = rows.filter(isTreatment);
|
|
54
|
+
const newest = treatments.map((row) => mexicoDay(row.validTime)).filter((day) => day && day <= today).sort().at(-1) ?? today;
|
|
55
|
+
const kept = treatments.filter((row) => !isOral(row) && within(row, newest, FACTS_WINDOW_DAYS));
|
|
56
|
+
const source = chemo === undefined ? 'unreadable' : kept.length || orals.length ? 'facts' : 'none';
|
|
57
|
+
return { source, unit: null, facts: [...kept, ...orals, ...others] };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
module.exports = { currentRegimen };
|
|
@@ -21,28 +21,31 @@ const MEDICAL_URGENCY_TO_SEVERITY = {
|
|
|
21
21
|
|
|
22
22
|
const EMERGENCY_LEVELS = new Set(['stat', 'asap']);
|
|
23
23
|
|
|
24
|
-
function pageNavigator({ severity, reason }) {
|
|
24
|
+
function pageNavigator({ severity, priority = null, reason }) {
|
|
25
25
|
return {
|
|
26
26
|
kind: 'page_navigator',
|
|
27
27
|
severity,
|
|
28
|
+
priority,
|
|
28
29
|
reason,
|
|
29
30
|
requiresAck: severity === 'critical' || severity === 'high',
|
|
30
31
|
};
|
|
31
32
|
}
|
|
32
33
|
|
|
33
|
-
function pageOncologist({ severity, reason }) {
|
|
34
|
+
function pageOncologist({ severity, priority = null, reason }) {
|
|
34
35
|
return {
|
|
35
36
|
kind: 'page_oncologist',
|
|
36
37
|
severity,
|
|
38
|
+
priority,
|
|
37
39
|
reason,
|
|
38
40
|
requiresAck: true,
|
|
39
41
|
};
|
|
40
42
|
}
|
|
41
43
|
|
|
42
|
-
function openTicket({ severity, title, reason }) {
|
|
44
|
+
function openTicket({ severity, priority = null, title, reason }) {
|
|
43
45
|
return {
|
|
44
46
|
kind: 'open_ticket',
|
|
45
47
|
severity,
|
|
48
|
+
priority,
|
|
46
49
|
title,
|
|
47
50
|
reason,
|
|
48
51
|
slaMinutes: SLA_MINUTES_BY_SEVERITY[severity] ?? null,
|
|
@@ -63,19 +66,21 @@ function planMedicalUrgent(signal) {
|
|
|
63
66
|
const level = (signal?.urgencyLevel || 'urgent').toLowerCase();
|
|
64
67
|
const indicators = Array.isArray(signal?.indicators) ? signal.indicators : [];
|
|
65
68
|
const label = signal?.category || signal?.symptom || signal?.suspectedCondition || 'medical';
|
|
69
|
+
const priority = MEDICAL_URGENCY_TO_SEVERITY[level] ? level : null;
|
|
66
70
|
if (EMERGENCY_LEVELS.has(level)) {
|
|
67
71
|
const severity = MEDICAL_URGENCY_TO_SEVERITY[level];
|
|
68
72
|
const reason = `emergency gate fired: ${indicators.join(', ') || 'unspecified'} (level=${level})`;
|
|
69
73
|
return [
|
|
70
|
-
pageOncologist({ severity, reason }),
|
|
71
|
-
pageNavigator({ severity, reason }),
|
|
72
|
-
openTicket({ severity, title: `EMERG: ${indicators.join(', ') || 'unspecified'}`, reason }),
|
|
74
|
+
pageOncologist({ severity, priority, reason }),
|
|
75
|
+
pageNavigator({ severity, priority, reason }),
|
|
76
|
+
openTicket({ severity, priority, title: `EMERG: ${indicators.join(', ') || 'unspecified'}`, reason }),
|
|
73
77
|
];
|
|
74
78
|
}
|
|
75
79
|
const severity = MEDICAL_URGENCY_TO_SEVERITY[level] || 'medium';
|
|
76
80
|
return [
|
|
77
81
|
openTicket({
|
|
78
82
|
severity,
|
|
83
|
+
priority,
|
|
79
84
|
title: `MED-${level.toUpperCase()}: ${String(label).slice(0, 60)}`,
|
|
80
85
|
reason: signal?.urgencyJustification || null,
|
|
81
86
|
}),
|
|
@@ -19,11 +19,13 @@ const CONVERSATION_TURNS = 40;
|
|
|
19
19
|
const TRIAGE_LIMIT = 3;
|
|
20
20
|
const CALL_LOG_LIMIT = 10;
|
|
21
21
|
|
|
22
|
+
const TECHNICAL_TOKEN = /\b(urgentIfPositive|blocksDrug|null)\b|\b[a-z]+_\w+|\\n/i;
|
|
23
|
+
|
|
22
24
|
const trimmed = (value) => String(value ?? '').trim();
|
|
23
25
|
|
|
24
26
|
function withholdReason(sections) {
|
|
25
27
|
const { present } = flagsByStatus(sections);
|
|
26
|
-
const modifiers = (Array.isArray(sections?.treatmentModifiers) ? sections.treatmentModifiers : []).map(trimmed).filter(Boolean);
|
|
28
|
+
const modifiers = (Array.isArray(sections?.treatmentModifiers) ? sections.treatmentModifiers : []).map((modifier) => trimmed(modifier).replace(/_/g, ' ')).filter(Boolean);
|
|
27
29
|
const reasons = [];
|
|
28
30
|
if (present.length) reasons.push(present.length === 1 ? 'hay una bandera roja presente' : 'hay banderas rojas presentes');
|
|
29
31
|
if (modifiers.length) reasons.push(`condición que cambia el algoritmo (${modifiers.join(', ')})`);
|
|
@@ -172,16 +174,20 @@ async function generateEscalationDraft({
|
|
|
172
174
|
return { completed: false, attempted: true, reason: `the treatment proposal broke the formulary rules: ${issues.join('; ')}` };
|
|
173
175
|
}
|
|
174
176
|
|
|
175
|
-
const
|
|
176
|
-
alarm: alarms[alarms.length - 1] ?? null,
|
|
177
|
+
const draft = {
|
|
177
178
|
shared: parsed,
|
|
178
179
|
symptoms: settled.map(({ block, proposal, withheldReason, conduct }) => ({ sections: block, proposal, withheldReason, conduct })),
|
|
179
|
-
}
|
|
180
|
+
};
|
|
181
|
+
const doctorText = composeDoctorBody({ ...draft, alarm: alarms[alarms.length - 1] ?? null });
|
|
180
182
|
|
|
181
183
|
if (!doctorText || !patientMessage) {
|
|
182
184
|
logger.warn('[escalationDraft] generation returned no usable text', { reviewId });
|
|
183
185
|
return { completed: false, attempted: true, reason: 'the model returned no usable text' };
|
|
184
186
|
}
|
|
187
|
+
if (TECHNICAL_TOKEN.test(`${composeDoctorBody({ ...draft, alarm: null })}\n${patientMessage}`)) {
|
|
188
|
+
logger.warn('[escalationDraft] generation leaked a technical token into the text', { reviewId });
|
|
189
|
+
return { completed: false, attempted: true, reason: 'the model wrote a field name or technical token into the doctor or patient text' };
|
|
190
|
+
}
|
|
185
191
|
|
|
186
192
|
return {
|
|
187
193
|
completed: true,
|