@peopl-health/nexus 6.0.8 → 6.0.10
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/helpers/knownCharacterizationHelper.js +73 -0
- package/lib/clinical/helpers/recommendationPlanHelper.js +8 -2
- package/lib/clinical/helpers/triageCaseBaseHelper.js +146 -12
- package/lib/clinical/models/triageRecommendationEventModel.js +1 -0
- package/lib/clinical/services/clinicalAirtableService.js +7 -4
- package/lib/clinical/services/ctcaeLadderService.js +25 -9
- package/lib/clinical/services/recommendationValidationService.js +4 -0
- package/lib/clinical/services/triageRecommendationService.js +8 -0
- package/lib/clinical/tools/submitRecommendationPlanTool.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
const { foldAccents } = require('../../utils/formatUtils');
|
|
2
|
+
const { termKey } = require('../../fhir/utils/normalizeUtils');
|
|
3
|
+
const { getSymptom } = require('../../fhir/helpers/terminologyHelper');
|
|
4
|
+
const { knownFor, withCurrentAnchor } = require('./triageCaseBaseHelper');
|
|
5
|
+
|
|
6
|
+
// Only the ADL question the anchor answers is dropped: "¿te impide bañarte o vestirte, o más bien cocinar o salir?".
|
|
7
|
+
// A false positive costs the patient a question, so the match is narrow and anything else on the line keeps it.
|
|
8
|
+
const LIMITS_RX = /\b(impide\w*|impedir\w*|limita\w*)\b/;
|
|
9
|
+
const SELF_CARE_RX = /\b(bana\w*|vest\w+)\b/;
|
|
10
|
+
const INSTRUMENTAL_RX = /\b(cocin\w+|compras|mandados|salir|trabaj\w+)\b/g;
|
|
11
|
+
const SAFETY_RX = new RegExp(`\\b(${[
|
|
12
|
+
'fiebre', 'febril', 'temperatura', 'escalofrios?', 'pecho', 'aire', 'respir\\w*', 'ahog\\w*', 'disnea', 'aliento',
|
|
13
|
+
'sangr\\w*', 'heces', 'negr\\w*', 'orina\\w*', 'vomit\\w*', 'liquidos?', 'beber', 'deshidrat\\w*', 'desmay\\w*',
|
|
14
|
+
'confus\\w*', 'convuls\\w*', 'ca[ei]\\w*', 'dano', 'suicid\\w*', 'morir', 'no estar aqui', 'sentido seguir', 'reposo',
|
|
15
|
+
].join('|')})\\b`);
|
|
16
|
+
|
|
17
|
+
function asksFunctionalImpact(question) {
|
|
18
|
+
const text = foldAccents(question).toLowerCase();
|
|
19
|
+
if (!LIMITS_RX.test(text) || SAFETY_RX.test(text) || /\d/.test(text)) return false;
|
|
20
|
+
if ((text.match(/\?/g) || []).length > 1) return false;
|
|
21
|
+
const instrumental = new Set(text.match(INSTRUMENTAL_RX) || []).size;
|
|
22
|
+
return SELF_CARE_RX.test(text) ? instrumental >= 1 : instrumental >= 2;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const keysOf = (catalog, term) => {
|
|
26
|
+
const ctcaeV5 = catalog?.symptoms ? getSymptom(catalog, term)?.ctcae_v5 : null;
|
|
27
|
+
return [term, ctcaeV5 && String(ctcaeV5).split('\n')[0]].map(termKey).filter(Boolean);
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
// Today's grade comes from the questionnaire, never from the grade the plan model wrote on its card.
|
|
31
|
+
function todayGradesByTerm(graded = [], catalog = null) {
|
|
32
|
+
const grades = new Map();
|
|
33
|
+
for (const { term, grade } of graded) {
|
|
34
|
+
if (!Number.isFinite(grade)) continue;
|
|
35
|
+
for (const key of keysOf(catalog, term)) grades.set(key, Math.max(grades.get(key) ?? grade, grade));
|
|
36
|
+
}
|
|
37
|
+
return grades;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function gradeFor(todayGrades, catalog, term) {
|
|
41
|
+
const key = keysOf(catalog, term).find((candidate) => todayGrades.has(candidate));
|
|
42
|
+
return key ? todayGrades.get(key) : null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Every term on the card needs today's grade and a current anchor: on a mixed card the question may be about the other term.
|
|
46
|
+
function anchorsCover(element, { known, catalog, todayGrades }) {
|
|
47
|
+
const terms = [...new Set([...element.targetedCtcaeTerms, ...element.symptoms.map((symptom) => symptom.ctcaeTerm)].filter(Boolean))];
|
|
48
|
+
if (!terms.length) return false;
|
|
49
|
+
return terms.every((term) => {
|
|
50
|
+
const todayGrade = gradeFor(todayGrades, catalog, term);
|
|
51
|
+
if (todayGrade === null) return false;
|
|
52
|
+
return Boolean(withCurrentAnchor(knownFor(known, term, catalog, null), todayGrade).entry?.functionalAnchor);
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function dropKnownFunctionalAsks(elements, { known, catalog, todayGrades } = {}, repairs = []) {
|
|
57
|
+
if (!known?.size || !todayGrades?.size) return 0;
|
|
58
|
+
let dropped = 0;
|
|
59
|
+
for (const element of elements) {
|
|
60
|
+
if (!element.minCharacterizationVariables.length || !anchorsCover(element, { known, catalog, todayGrades })) continue;
|
|
61
|
+
const kept = element.minCharacterizationVariables.filter((question) => !asksFunctionalImpact(question));
|
|
62
|
+
const removed = element.minCharacterizationVariables.length - kept.length;
|
|
63
|
+
if (!removed) continue;
|
|
64
|
+
dropped += removed;
|
|
65
|
+
element.minCharacterizationVariables = kept;
|
|
66
|
+
if (!kept.length) element.characterizationNeeded = false;
|
|
67
|
+
repairs.push(`min_characterization_variables (rank ${element.rank}): ${removed} pregunta(s) de impacto funcional `
|
|
68
|
+
+ 'eliminada(s); el caso abierto ya lo caracterizó en conversación y sigue vigente');
|
|
69
|
+
}
|
|
70
|
+
return dropped;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
module.exports = { asksFunctionalImpact, dropKnownFunctionalAsks, todayGradesByTerm };
|
|
@@ -71,6 +71,12 @@ function buildElement(raw, repairs) {
|
|
|
71
71
|
followupUrgency: nullableStr(rawRec?.followup_urgency),
|
|
72
72
|
};
|
|
73
73
|
const rawEsc = raw?.escalation || {};
|
|
74
|
+
const urgentUnder24h = rawEsc?.urgent_under_24h === true;
|
|
75
|
+
let maxActionTimeHours = num(rawEsc?.max_action_time_hours);
|
|
76
|
+
if (!urgentUnder24h && maxActionTimeHours !== null && (maxActionTimeHours < 1 || maxActionTimeHours > 24)) {
|
|
77
|
+
repairs.push(`max_action_time_hours (rank ${raw?.rank ?? '?'}) ${maxActionTimeHours}h descartado: fuera de 1-24h en un elemento no urgente`);
|
|
78
|
+
maxActionTimeHours = null;
|
|
79
|
+
}
|
|
74
80
|
return {
|
|
75
81
|
rank: num(raw?.rank) || 0,
|
|
76
82
|
type: str(raw?.type).trim(),
|
|
@@ -84,8 +90,8 @@ function buildElement(raw, repairs) {
|
|
|
84
90
|
characterizationNeeded: typeof raw?.characterization_is_needed === 'boolean' ? raw.characterization_is_needed : null,
|
|
85
91
|
minCharacterizationVariables: strList(raw?.min_characterization_variables),
|
|
86
92
|
escalation: {
|
|
87
|
-
urgentUnder24h
|
|
88
|
-
maxActionTimeHours
|
|
93
|
+
urgentUnder24h,
|
|
94
|
+
maxActionTimeHours,
|
|
89
95
|
routes: strList(rawEsc?.routes).map((route) => route.trim()).filter(Boolean),
|
|
90
96
|
clinicalCriteria: nullableStr(rawEsc?.clinical_criteria),
|
|
91
97
|
},
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
const { ladderFor, renderLadder } = require('../services/ctcaeLadderService');
|
|
2
2
|
const {
|
|
3
|
-
itemForQuestionId, affirmative, sentinelKind, dimensionsFor, isItemDimension,
|
|
3
|
+
itemForQuestionId, affirmative, sentinelKind, dimensionsFor, isItemDimension, getSymptom,
|
|
4
4
|
} = require('../../fhir/helpers/terminologyHelper');
|
|
5
|
-
const {
|
|
5
|
+
const { termKey } = require('../../fhir/utils/normalizeUtils');
|
|
6
|
+
const { daysSince, mexicoDay } = require('../../utils/dateUtils');
|
|
6
7
|
const { detectSafetyFlags } = require('./safetyFlagsHelper');
|
|
7
8
|
|
|
8
9
|
const GRADE_FLOOR = 3;
|
|
@@ -110,6 +111,114 @@ const CHANGE_ES = {
|
|
|
110
111
|
|
|
111
112
|
const ABSENT_CHANGE_RX = /^absent_(.+)_cluster$/;
|
|
112
113
|
|
|
114
|
+
const CHARACTERIZATION_WINDOW_DAYS = 14;
|
|
115
|
+
const CHARACTERIZATION_NOTE_LIMIT = 2;
|
|
116
|
+
const CHARACTERIZATION_NOTE_MAX_CHARS = 240;
|
|
117
|
+
|
|
118
|
+
const FUNCTIONAL_ANCHOR_ES = {
|
|
119
|
+
not_limited: 'no limita sus actividades',
|
|
120
|
+
instrumental_adl_limited: 'limita actividades instrumentales (cocinar, salir, trabajar)',
|
|
121
|
+
self_care_adl_limited: 'limita el autocuidado (bañarse, vestirse, comer)',
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const REASK_RULE = 'no lo vuelvas a pedir en min_characterization_variables salvo que hoy suba el grado o el '
|
|
125
|
+
+ 'paciente reporte un cambio';
|
|
126
|
+
|
|
127
|
+
// PRO-CTCAE G3 is the self-care clause: a composite that high re-opens any milder functional anchor.
|
|
128
|
+
const ANCHOR_REOPEN_GRADE = 3;
|
|
129
|
+
|
|
130
|
+
const KNOWN_HEADER = `Ya caracterizado en conversación (últimos ${CHARACTERIZATION_WINDOW_DAYS} días; es contexto, `
|
|
131
|
+
+ `no evidencia de hoy; ${REASK_RULE}):`;
|
|
132
|
+
|
|
133
|
+
const clip = (text) => {
|
|
134
|
+
const flat = String(text ?? '').replace(/\s+/g, ' ').trim();
|
|
135
|
+
return flat.length > CHARACTERIZATION_NOTE_MAX_CHARS ? `${flat.slice(0, CHARACTERIZATION_NOTE_MAX_CHARS - 1)}…` : flat;
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
// Grades are compared within the agent's own reads only; the questionnaire composite is a different scale.
|
|
139
|
+
function worsenedAfter(recent, anchored) {
|
|
140
|
+
const anchoredAt = Date.parse(anchored.performedAt);
|
|
141
|
+
const anchoredGrade = anchored.grade?.bestEstimate;
|
|
142
|
+
const later = recent
|
|
143
|
+
.filter((assessment) => Date.parse(assessment.performedAt) > anchoredAt)
|
|
144
|
+
.filter((assessment) => assessment.trajectory === 'worsening'
|
|
145
|
+
|| (Number.isFinite(anchoredGrade) && Number(assessment.grade?.bestEstimate) > anchoredGrade));
|
|
146
|
+
return later.length ? mexicoDay(later[later.length - 1].performedAt) : null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// The plan is otherwise blind to what the agent already characterized in chat and re-asks it every triage.
|
|
150
|
+
// A not_established anchor answers nothing, so the most recent established one inside the window wins.
|
|
151
|
+
function characterizationByTerm(openCases = [], now = Date.now()) {
|
|
152
|
+
const byTerm = new Map();
|
|
153
|
+
for (const { condition, latestAssessment, priorAssessments = [] } of openCases) {
|
|
154
|
+
const recent = [latestAssessment, ...priorAssessments]
|
|
155
|
+
.filter((assessment) => {
|
|
156
|
+
const age = assessment ? daysSince(assessment.performedAt, now) : null;
|
|
157
|
+
return age !== null && age <= CHARACTERIZATION_WINDOW_DAYS;
|
|
158
|
+
})
|
|
159
|
+
.sort((left, right) => Date.parse(right.performedAt) - Date.parse(left.performedAt));
|
|
160
|
+
const anchored = recent.find((assessment) => FUNCTIONAL_ANCHOR_ES[assessment.grade?.functionalAnchor]);
|
|
161
|
+
const notes = recent
|
|
162
|
+
.map((assessment) => ({ at: mexicoDay(assessment.performedAt), text: clip(assessment.reasoning || assessment.grade?.reasoning) }))
|
|
163
|
+
.filter((note) => note.text)
|
|
164
|
+
.slice(0, CHARACTERIZATION_NOTE_LIMIT);
|
|
165
|
+
if (!anchored && !notes.length) continue;
|
|
166
|
+
const key = termKey(condition.ctcaeTerm);
|
|
167
|
+
// Two open cases on one term: the one characterized most recently speaks for it.
|
|
168
|
+
const lastAt = Date.parse(recent[0].performedAt);
|
|
169
|
+
if (byTerm.has(key) && byTerm.get(key).lastAt >= lastAt) continue;
|
|
170
|
+
byTerm.set(key, {
|
|
171
|
+
lastAt,
|
|
172
|
+
functionalAnchor: anchored
|
|
173
|
+
? {
|
|
174
|
+
at: mexicoDay(anchored.performedAt),
|
|
175
|
+
kind: anchored.grade.functionalAnchor,
|
|
176
|
+
label: FUNCTIONAL_ANCHOR_ES[anchored.grade.functionalAnchor],
|
|
177
|
+
worsenedAt: worsenedAfter(recent, anchored),
|
|
178
|
+
}
|
|
179
|
+
: null,
|
|
180
|
+
notes,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
return byTerm;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function staleReason(anchor, todayGrade) {
|
|
187
|
+
if (anchor.worsenedAt) return `el caso empeoró después (${anchor.worsenedAt})`;
|
|
188
|
+
if (Number(todayGrade) >= ANCHOR_REOPEN_GRADE && anchor.kind !== 'self_care_adl_limited') {
|
|
189
|
+
return `hoy el cuestionario da grado ${todayGrade}`;
|
|
190
|
+
}
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// An anchor that worsening has overtaken no longer describes the patient and must be asked again.
|
|
195
|
+
function withCurrentAnchor(entry, todayGrade = null) {
|
|
196
|
+
const anchor = entry?.functionalAnchor;
|
|
197
|
+
const reason = anchor ? staleReason(anchor, todayGrade) : null;
|
|
198
|
+
return reason ? { entry: { ...entry, functionalAnchor: null }, stale: { ...anchor, reason } } : { entry, stale: null };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const staleLine = (stale) => `El impacto funcional se caracterizó el ${stale.at} («${stale.label}»), pero ${stale.reason}: `
|
|
202
|
+
+ 'ya no lo describe; vuelve a caracterizarlo.';
|
|
203
|
+
|
|
204
|
+
// Cases carry the CTCAE term ('anxiety') while the triage carries the PRO-CTCAE one ('anxious').
|
|
205
|
+
function knownFor(known, term, catalog, ladder) {
|
|
206
|
+
if (!known?.size) return null;
|
|
207
|
+
const ctcaeV5 = catalog?.symptoms ? getSymptom(catalog, term)?.ctcae_v5 : null;
|
|
208
|
+
const keys = [term, ladder?.ctcaeTerm, ctcaeV5 && String(ctcaeV5).split('\n')[0]].map(termKey).filter(Boolean);
|
|
209
|
+
const key = keys.find((candidate) => known.has(candidate));
|
|
210
|
+
return key ? known.get(key) : null;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function renderKnown(entry, indent, { noteLimit = CHARACTERIZATION_NOTE_LIMIT } = {}) {
|
|
214
|
+
const lines = [`${indent}${KNOWN_HEADER}`];
|
|
215
|
+
if (entry.functionalAnchor) {
|
|
216
|
+
lines.push(`${indent} impacto funcional (${entry.functionalAnchor.at}): ${entry.functionalAnchor.label}`);
|
|
217
|
+
}
|
|
218
|
+
for (const note of entry.notes.slice(0, noteLimit)) lines.push(`${indent} documentado el ${note.at}: «${note.text}»`);
|
|
219
|
+
return lines;
|
|
220
|
+
}
|
|
221
|
+
|
|
113
222
|
const GRADE_BASIS_ES = {
|
|
114
223
|
composite: 'la tabla compuesta del PRO-CTCAE resolvió el grado con las respuestas de arriba',
|
|
115
224
|
presence: 'sólo se preguntó si el síntoma estaba presente; el grado no sale de una escala de severidad',
|
|
@@ -117,8 +226,10 @@ const GRADE_BASIS_ES = {
|
|
|
117
226
|
partial: 'la tabla compuesta no resolvió la combinación completa; el grado es parcial',
|
|
118
227
|
};
|
|
119
228
|
|
|
120
|
-
function reportedSymptomEvidence(symptom, catalog) {
|
|
229
|
+
function reportedSymptomEvidence(symptom, catalog, known = null) {
|
|
121
230
|
const lines = [`- ${symptom.term} (grado ${symptom.grade})`];
|
|
231
|
+
const ladder = catalog?.symptoms ? ladderFor(catalog, symptom.term) : null;
|
|
232
|
+
const { entry: knownEntry, stale } = withCurrentAnchor(knownFor(known, symptom.term, catalog, ladder), symptom.grade);
|
|
122
233
|
const answers = symptom.dimensionAnswers || {};
|
|
123
234
|
const answered = Object.keys(answers);
|
|
124
235
|
if (answered.length) {
|
|
@@ -132,9 +243,18 @@ function reportedSymptomEvidence(symptom, catalog) {
|
|
|
132
243
|
.map(([dimension, answer]) => `${DIMENSION_ES[dimension] || dimension}: ${answer}`)
|
|
133
244
|
.join(' · ')}. Miden otra cosa que el ítem del PRO-CTCAE; no confirman ni descartan el síntoma.`);
|
|
134
245
|
}
|
|
246
|
+
if (knownEntry && (knownEntry.functionalAnchor || knownEntry.notes.length)) lines.push(...renderKnown(knownEntry, ' '));
|
|
247
|
+
if (stale) lines.push(` ${staleLine(stale)}`);
|
|
135
248
|
if (Array.isArray(catalog?.symptoms?.[symptom.term]?.dimensions)) {
|
|
136
|
-
const
|
|
249
|
+
const unasked = dimensionsFor(catalog, symptom.term)
|
|
137
250
|
.filter((dimension) => isItemDimension(catalog, symptom.term, dimension) && !answered.includes(dimension));
|
|
251
|
+
// The ADL anchor is not the PRO-CTCAE interference scale, so it is named as what covers it, never dropped silently.
|
|
252
|
+
const interferenceCovered = Boolean(knownEntry?.functionalAnchor) && unasked.includes('interference');
|
|
253
|
+
const missing = interferenceCovered ? unasked.filter((dimension) => dimension !== 'interference') : unasked;
|
|
254
|
+
if (interferenceCovered) {
|
|
255
|
+
lines.push(' Interferencia: este ítem del PRO-CTCAE no la preguntó, pero el impacto funcional en actividades ya '
|
|
256
|
+
+ 'se caracterizó en conversación (arriba); no la vuelvas a pedir por separado.');
|
|
257
|
+
}
|
|
138
258
|
if (missing.length) {
|
|
139
259
|
lines.push(` Atributos que este ítem del PRO-CTCAE no preguntó: ${missing
|
|
140
260
|
.map((dimension) => DIMENSION_ES[dimension] || dimension).join(', ')}. No preguntado no es `
|
|
@@ -143,8 +263,7 @@ function reportedSymptomEvidence(symptom, catalog) {
|
|
|
143
263
|
}
|
|
144
264
|
const basis = GRADE_BASIS_ES[symptom.gradeBasis];
|
|
145
265
|
if (basis) lines.push(` Base del grado (${symptom.gradeBasis}): ${basis}.`);
|
|
146
|
-
|
|
147
|
-
if (ladder) lines.push(...renderLadder(ladder, symptom.grade));
|
|
266
|
+
if (ladder) lines.push(...renderLadder(ladder, symptom.grade, { known: knownEntry }));
|
|
148
267
|
return lines.join('\n');
|
|
149
268
|
}
|
|
150
269
|
|
|
@@ -159,7 +278,10 @@ function buildSymptomsMetadata({
|
|
|
159
278
|
nonIdentifiedSymptoms = null,
|
|
160
279
|
stage = 'gate',
|
|
161
280
|
catalog = null,
|
|
281
|
+
openCases = [],
|
|
282
|
+
now = Date.now(),
|
|
162
283
|
}) {
|
|
284
|
+
const known = characterizationByTerm(openCases, now);
|
|
163
285
|
const { reported, denied, unanswered } = splitByEpistemics({
|
|
164
286
|
graded,
|
|
165
287
|
askedTerms,
|
|
@@ -175,7 +297,7 @@ function buildSymptomsMetadata({
|
|
|
175
297
|
+ '.',
|
|
176
298
|
);
|
|
177
299
|
if (reported.length) {
|
|
178
|
-
parts.push(reported.map((symptom) => reportedSymptomEvidence(symptom, catalog)).join('\n'));
|
|
300
|
+
parts.push(reported.map((symptom) => reportedSymptomEvidence(symptom, catalog, known)).join('\n'));
|
|
179
301
|
}
|
|
180
302
|
if (additionalSymptoms.length) {
|
|
181
303
|
parts.push(
|
|
@@ -245,7 +367,8 @@ const OPEN_CASE_RULE = 'Son contexto de razonamiento, NO evidencia de hoy ni mat
|
|
|
245
367
|
+ 'recommendation.symptoms_patient_facing, symptoms ni targeted_ctcae_terms. \'improving\' o días sin '
|
|
246
368
|
+ 'evidencia no significan resuelto: si ya se escaló y no hay cierre documentado, anótalo como '
|
|
247
369
|
+ 'pendiente del equipo en el resumen interno (summary en el gate, summary_internal en el plan), nunca '
|
|
248
|
-
+ 'como tarjeta ni urgencia.'
|
|
370
|
+
+ 'como tarjeta ni urgencia. Lo que un caso ya caracterizó en conversación (impacto funcional, carácter, '
|
|
371
|
+
+ `patrón, momento del día, alivio) sí sigue vigente durante ${CHARACTERIZATION_WINDOW_DAYS} días: ${REASK_RULE}.`;
|
|
249
372
|
|
|
250
373
|
const ESCALATION_RULE = 'Registran sólo lo que se ENVIÓ al equipo: nunca si respondió, qué indicó ni si se '
|
|
251
374
|
+ 'resolvió. Son contexto, no evidencia: una escalación pasada nunca crea, sostiene ni sube una urgencia '
|
|
@@ -255,8 +378,9 @@ const ESCALATION_RULE = 'Registran sólo lo que se ENVIÓ al equipo: nunca si re
|
|
|
255
378
|
+ 'tiempo transcurrido nunca justifica por sí solo una ruta mayor. En '
|
|
256
379
|
+ 'reason_for_escalation cita la evidencia de hoy y di si es nuevo, empeoramiento o persistencia.';
|
|
257
380
|
|
|
258
|
-
function buildOpenCaseBlock(openCases = []) {
|
|
381
|
+
function buildOpenCaseBlock(openCases = [], now = Date.now()) {
|
|
259
382
|
if (!openCases.length) return 'Sin casos clínicos abiertos.';
|
|
383
|
+
const known = characterizationByTerm(openCases, now);
|
|
260
384
|
const lines = openCases.map((managedSymptom) => {
|
|
261
385
|
const { condition, latestAssessment } = managedSymptom;
|
|
262
386
|
const grade = latestAssessment.grade;
|
|
@@ -265,9 +389,13 @@ function buildOpenCaseBlock(openCases = []) {
|
|
|
265
389
|
const parts = [condition.ctcaeTerm, condition.clinicalStatus, estimate];
|
|
266
390
|
if (grade.confidence) parts.push(`confianza ${grade.confidence}`);
|
|
267
391
|
if (latestAssessment.trajectory) parts.push(latestAssessment.trajectory);
|
|
268
|
-
const quiet = daysSince(latestAssessment.performedAt,
|
|
392
|
+
const quiet = daysSince(latestAssessment.performedAt, now);
|
|
269
393
|
if (quiet !== null) parts.push(`${quiet} d sin evidencia nueva`);
|
|
270
|
-
|
|
394
|
+
const { entry, stale } = withCurrentAnchor(known.get(termKey(condition.ctcaeTerm)));
|
|
395
|
+
const lines = [`- ${parts.join(' · ')}`];
|
|
396
|
+
if (entry && (entry.functionalAnchor || entry.notes.length)) lines.push(...renderKnown(entry, ' ', { noteLimit: 1 }));
|
|
397
|
+
if (stale) lines.push(` ${staleLine(stale)}`);
|
|
398
|
+
return lines.join('\n');
|
|
271
399
|
});
|
|
272
400
|
return `${lines.join('\n')}\n${OPEN_CASE_RULE}`;
|
|
273
401
|
}
|
|
@@ -407,6 +535,7 @@ function buildCasoBase({
|
|
|
407
535
|
stage = 'gate',
|
|
408
536
|
catalog = null,
|
|
409
537
|
symptomSignals = [],
|
|
538
|
+
now = Date.now(),
|
|
410
539
|
}) {
|
|
411
540
|
const cadenceLabel = CADENCE_LABEL[String(cadence || '').trim().toLowerCase()] || null;
|
|
412
541
|
const suffix = `${authored ? ` (${authored})` : ''}${triageRecordId ? ` [id: ${triageRecordId}]` : ''}.`;
|
|
@@ -434,6 +563,8 @@ function buildCasoBase({
|
|
|
434
563
|
nonIdentifiedSymptoms,
|
|
435
564
|
stage,
|
|
436
565
|
catalog,
|
|
566
|
+
openCases,
|
|
567
|
+
now,
|
|
437
568
|
}),
|
|
438
569
|
];
|
|
439
570
|
if (freeText) {
|
|
@@ -445,7 +576,7 @@ function buildCasoBase({
|
|
|
445
576
|
buildSymptomChangeBlock(symptomsChange),
|
|
446
577
|
'',
|
|
447
578
|
'### Casos clínicos abiertos del paciente',
|
|
448
|
-
buildOpenCaseBlock(openCases),
|
|
579
|
+
buildOpenCaseBlock(openCases, now),
|
|
449
580
|
'',
|
|
450
581
|
'### Escalaciones ya enviadas al equipo (últimos 14 días)',
|
|
451
582
|
buildEscalationBlock(escalations),
|
|
@@ -467,6 +598,9 @@ function buildCasoBase({
|
|
|
467
598
|
}
|
|
468
599
|
|
|
469
600
|
module.exports = {
|
|
601
|
+
characterizationByTerm,
|
|
602
|
+
knownFor,
|
|
603
|
+
withCurrentAnchor,
|
|
470
604
|
buildExposureBlock,
|
|
471
605
|
buildOpenCaseBlock,
|
|
472
606
|
buildEscalationBlock,
|
|
@@ -54,6 +54,7 @@ const triageRecommendationEventSchema = new mongoose.Schema({
|
|
|
54
54
|
deniedCardsDropped: { type: Number, default: null },
|
|
55
55
|
deniedTargetsStripped: { type: Number, default: null },
|
|
56
56
|
cardsTruncated: { type: Number, default: null },
|
|
57
|
+
knownAsksDropped: { type: Number, default: null },
|
|
57
58
|
adherenceRecorded: { type: Number, default: null },
|
|
58
59
|
adherenceSkipped: { type: Number, default: null },
|
|
59
60
|
adherenceNoTask: { type: Number, default: null },
|
|
@@ -50,6 +50,9 @@ const REMINDER_TYPE_TO_AIRTABLE = {
|
|
|
50
50
|
const PENDING_ROW_FILTER = 'IF({is_active}, "true", "false") = "true", IF({is_sent}, "true", "false") = "false"';
|
|
51
51
|
const ROUTINE_OUTREACH_FILTER = 'OR({type} = "seguimiento", LEFT({schedule_id}, 9) = "recovery_")';
|
|
52
52
|
const RECOVERY_FILTER = 'LEFT({schedule_id}, 9) = "recovery_"';
|
|
53
|
+
// `reminder` and `contingency` have no `source`; the lookup through the patient link carries it.
|
|
54
|
+
const ROW_PROGRAM_FIELD = 'source (from patient_id)';
|
|
55
|
+
const patientRowsOf = (code) => `${fieldEquals('whatsapp_id', code)}, ${programSourceFormula({ field: ROW_PROGRAM_FIELD, allowBlank: true })}`;
|
|
53
56
|
const FIRE_TRIGGER_GRACE_MS = 10 * 60 * 1000;
|
|
54
57
|
|
|
55
58
|
// intake.source only offers self|doctor; team_relay carries "según médico" authority.
|
|
@@ -456,7 +459,7 @@ async function readPendingFollowUpsForPatient({ code, now = new Date() }) {
|
|
|
456
459
|
const rows = await airtableService.getRecordByFilter(
|
|
457
460
|
Monitoreo_ID,
|
|
458
461
|
'reminder',
|
|
459
|
-
`AND(${
|
|
462
|
+
`AND(${patientRowsOf(code)}, ${ROUTINE_OUTREACH_FILTER}, ${PENDING_ROW_FILTER})`,
|
|
460
463
|
null,
|
|
461
464
|
['schedule_id', 'reminder_date', 'description', 'expires_at', 'window_reasoning'],
|
|
462
465
|
);
|
|
@@ -482,7 +485,7 @@ async function hasCheckInNear({ code, withinMinutes, excludeReminderId, fireAt =
|
|
|
482
485
|
const rows = await airtableService.getRecordByFilter(
|
|
483
486
|
Monitoreo_ID,
|
|
484
487
|
'reminder',
|
|
485
|
-
`AND(${
|
|
488
|
+
`AND(${patientRowsOf(code)}, OR(RIGHT({schedule_id}, 8) = "-patient", ${ROUTINE_OUTREACH_FILTER}), NOT(${fieldEquals('schedule_id', excludeReminderId)}), OR(${pending}, ${sent}))`,
|
|
486
489
|
null,
|
|
487
490
|
['schedule_id', 'reminder_date', 'is_sent'],
|
|
488
491
|
);
|
|
@@ -522,7 +525,7 @@ async function cancelPendingFollowUps({ code, trace = null, reason = 'patient_re
|
|
|
522
525
|
table: 'reminder',
|
|
523
526
|
planId: null,
|
|
524
527
|
standDownReason: reason,
|
|
525
|
-
filter: `AND(${
|
|
528
|
+
filter: `AND(${patientRowsOf(code)}, ${recoveryOnly ? RECOVERY_FILTER : ROUTINE_OUTREACH_FILTER}, ${PENDING_ROW_FILTER})`,
|
|
526
529
|
});
|
|
527
530
|
}
|
|
528
531
|
|
|
@@ -648,7 +651,7 @@ async function standDownRow({ code, trace, table, filter, planId, standDownReaso
|
|
|
648
651
|
|
|
649
652
|
// Stands down every pending reminder and contingency row of a patient, whatever their type.
|
|
650
653
|
async function standDownAllPendingRows({ code, reason }) {
|
|
651
|
-
const filter = `AND(${
|
|
654
|
+
const filter = `AND(${patientRowsOf(code)}, ${PENDING_ROW_FILTER})`;
|
|
652
655
|
const remindersOk = await standDownRow({ code, trace: null, planId: null, standDownReason: reason, table: 'reminder', filter });
|
|
653
656
|
const escalationsOk = await standDownRow({ code, trace: null, planId: null, table: 'contingency', filter });
|
|
654
657
|
return remindersOk && escalationsOk;
|
|
@@ -40,7 +40,30 @@ function ladderFor(catalog, term) {
|
|
|
40
40
|
return { ctcaeTerm: key, grades, criticalField: entry.criticalField || null };
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
|
|
43
|
+
const KNOWN_FIELD_RULE = 'No lo vuelvas a pedir: úsalo para contrastar el grado. Pídelo de nuevo sólo si el '
|
|
44
|
+
+ 'grado de hoy es mayor que el del caso o el paciente reporta un cambio.';
|
|
45
|
+
|
|
46
|
+
// known: what the conversation already characterized for this term (see characterizationByTerm).
|
|
47
|
+
function criticalFieldLine(ladder, known) {
|
|
48
|
+
const gap = CRITICAL_FIELD_GAPS[ladder.criticalField] || QUESTIONNAIRE_GAP;
|
|
49
|
+
if (ladder.criticalField === 'functional_impact' && known?.functionalAnchor) {
|
|
50
|
+
return `Dato que decide el grado de ${ladder.ctcaeTerm} (critical_field): functional_impact. `
|
|
51
|
+
+ `El cuestionario no lo captura (${gap}), pero YA se caracterizó en conversación `
|
|
52
|
+
+ `(${known.functionalAnchor.at}): ${known.functionalAnchor.label}. ${KNOWN_FIELD_RULE}`;
|
|
53
|
+
}
|
|
54
|
+
const base = `Dato que decide el grado de ${ladder.ctcaeTerm} (critical_field): ${ladder.criticalField}. `
|
|
55
|
+
+ `No capturado por el cuestionario (${gap}): `;
|
|
56
|
+
if (known?.notes?.length) {
|
|
57
|
+
return `${base}antes de pedir caracterización, revisa lo ya caracterizado en conversación para este síntoma. `
|
|
58
|
+
+ 'Si ya responde este dato, no lo vuelvas a pedir salvo que el grado de hoy sea mayor que el del caso o el '
|
|
59
|
+
+ 'paciente reporte un cambio; si no lo responde, pide caracterización. En ambos casos el grado es una '
|
|
60
|
+
+ 'aproximación del cuestionario; no lo presentes como grado CTCAE ni lo uses para confirmar un umbral.';
|
|
61
|
+
}
|
|
62
|
+
return `${base}pide caracterización en vez de asumirlo; el grado es una aproximación del cuestionario; no lo `
|
|
63
|
+
+ 'presentes como grado CTCAE ni lo uses para confirmar un umbral.';
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function renderLadder(ladder, grade, { indent = ' ', known = null } = {}) {
|
|
44
67
|
const lines = [
|
|
45
68
|
`${indent}Escala CTCAE de ${ladder.ctcaeTerm}. El grado de arriba es una APROXIMACIÓN calculada a partir `
|
|
46
69
|
+ 'del PRO-CTCAE, no una lectura de estas cláusulas: contrasta lo que el paciente describe contra '
|
|
@@ -52,14 +75,7 @@ function renderLadder(ladder, grade, { indent = ' ' } = {}) {
|
|
|
52
75
|
const marker = Number(level) === Number(grade) ? ' <- grado calculado' : '';
|
|
53
76
|
lines.push(`${indent} G${level}: ${description}${marker}`);
|
|
54
77
|
}
|
|
55
|
-
if (ladder.criticalField) {
|
|
56
|
-
lines.push(
|
|
57
|
-
`${indent}Dato que decide el grado de ${ladder.ctcaeTerm} (critical_field): ${ladder.criticalField}. `
|
|
58
|
-
+ `No capturado por el cuestionario (${CRITICAL_FIELD_GAPS[ladder.criticalField] || QUESTIONNAIRE_GAP}): `
|
|
59
|
-
+ 'pide caracterización en vez de asumirlo; el grado es una aproximación del cuestionario; no lo '
|
|
60
|
-
+ 'presentes como grado CTCAE ni lo uses para confirmar un umbral.',
|
|
61
|
-
);
|
|
62
|
-
}
|
|
78
|
+
if (ladder.criticalField) lines.push(`${indent}${criticalFieldLine(ladder, known)}`);
|
|
63
79
|
return lines;
|
|
64
80
|
}
|
|
65
81
|
|
|
@@ -127,6 +127,10 @@ function validate(elements, options = {}) {
|
|
|
127
127
|
problem: 'no puede contener puntos suspensivos ni texto truncado',
|
|
128
128
|
});
|
|
129
129
|
}
|
|
130
|
+
const hours = element.escalation.maxActionTimeHours;
|
|
131
|
+
if (hours !== null && (hours < 1 || hours > 24)) {
|
|
132
|
+
issues.push({ path: `${path}.escalation.max_action_time_hours`, problem: `max_action_time_hours debe estar entre 1 y 24; recibido ${hours}` });
|
|
133
|
+
}
|
|
130
134
|
if (element.escalation.urgentUnder24h && !element.escalation.routes.length) {
|
|
131
135
|
issues.push({ path: `${path}.escalation.routes`, problem: 'elemento con escalamiento <24h ⇒ routes debe llevar al menos una ruta' });
|
|
132
136
|
}
|
|
@@ -19,7 +19,9 @@ const {
|
|
|
19
19
|
buildCasoBase,
|
|
20
20
|
buildSafetySignals,
|
|
21
21
|
hasActionableFindings,
|
|
22
|
+
characterizationByTerm,
|
|
22
23
|
} = require('../helpers/triageCaseBaseHelper');
|
|
24
|
+
const { dropKnownFunctionalAsks, todayGradesByTerm } = require('../helpers/knownCharacterizationHelper');
|
|
23
25
|
const { buildLegacyStep1, buildLegacyStep2, buildLegacyStep3 } = require('../helpers/legacyRecommendationFormatHelper');
|
|
24
26
|
const { chemoContextLive } = require('../flags/clinicalContextFlags');
|
|
25
27
|
const { mexicoDay } = require('../../utils/dateUtils');
|
|
@@ -599,6 +601,8 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
|
|
|
599
601
|
uncodedKeys: new Set(freeTextUnmatchedSymptoms.map(keyOf).filter(Boolean)),
|
|
600
602
|
deniedAeKeys: deniedAeKeySet(catalog, gate),
|
|
601
603
|
reported: reportedSymptoms(catalog, reportedTerms),
|
|
604
|
+
known: characterizationByTerm(openCases),
|
|
605
|
+
todayGrades: todayGradesByTerm(graded, catalog),
|
|
602
606
|
};
|
|
603
607
|
const rankContext = buildRankContext({ catalog, graded, reportedTerms, priorResolutions, openCases });
|
|
604
608
|
const symptomSignals = buildSymptomSignals({
|
|
@@ -623,6 +627,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
|
|
|
623
627
|
settle.deniedCardsDropped = planOutcome.deniedCardsDropped;
|
|
624
628
|
settle.cardsTruncated = planOutcome.cardsTruncated;
|
|
625
629
|
settle.deniedTargetsStripped = planOutcome.deniedTargetsStripped;
|
|
630
|
+
settle.knownAsksDropped = planOutcome.knownAsksDropped;
|
|
626
631
|
|
|
627
632
|
try {
|
|
628
633
|
await storeRecommendationPlan({
|
|
@@ -927,6 +932,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
927
932
|
let deniedCardsDropped = 0;
|
|
928
933
|
let deniedTargetsStripped = 0;
|
|
929
934
|
let cardsTruncated = 0;
|
|
935
|
+
let knownAsksDropped = 0;
|
|
930
936
|
const budget = newTransientBudget();
|
|
931
937
|
for (let attempt = 1; attempt <= PLAN_MAX_ATTEMPTS; attempt += 1) {
|
|
932
938
|
const content = attempt === 1 || !lastIssues.length
|
|
@@ -987,6 +993,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
987
993
|
}
|
|
988
994
|
rankReordered = applyRankOrder(elements, gate, repairs, rankContext);
|
|
989
995
|
cardsTruncated = truncateToCardLimit(elements, repairs);
|
|
996
|
+
knownAsksDropped = dropKnownFunctionalAsks(elements, boundary || {}, repairs);
|
|
990
997
|
const issues = validate(elements, { gate, lane: 'triage', urgentReframed });
|
|
991
998
|
const blocking = blockingIssues(issues);
|
|
992
999
|
if (blocking.length) {
|
|
@@ -1012,6 +1019,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
1012
1019
|
deniedCardsDropped,
|
|
1013
1020
|
deniedTargetsStripped,
|
|
1014
1021
|
cardsTruncated,
|
|
1022
|
+
knownAsksDropped,
|
|
1015
1023
|
modelInput: content,
|
|
1016
1024
|
model: typeof result?.model === 'string' ? result.model : null,
|
|
1017
1025
|
});
|
|
@@ -26,7 +26,7 @@ const definition = {
|
|
|
26
26
|
},
|
|
27
27
|
elements: {
|
|
28
28
|
type: 'array',
|
|
29
|
-
description: 'Ranked plan elements (contiguous ranks 1..N). Each: `{rank, type(cluster|individual), name_short, time_window, symptoms[{ctcae_term, grade, verification_status}], targeted_ctcae_terms[], why_relevant, qol_impact, improvement_capacity, escalation{urgent_under_24h, max_action_time_hours, routes[], clinical_criteria}, recommendation{symptoms_patient_facing[], is_pharmacological_med_needed, patient{main_recommendation, when_to_escalate, contraindications, expected_effectiveness}, otc_offer?, followup?, followup_urgency?}, grounded_in[]}`.',
|
|
29
|
+
description: 'Ranked plan elements (contiguous ranks 1..N). Each: `{rank, type(cluster|individual), name_short, time_window, symptoms[{ctcae_term, grade, verification_status}], targeted_ctcae_terms[], why_relevant, qol_impact, improvement_capacity, escalation{urgent_under_24h, max_action_time_hours, routes[], clinical_criteria} (max_action_time_hours: integer 1-24 or null), recommendation{symptoms_patient_facing[], is_pharmacological_med_needed, patient{main_recommendation, when_to_escalate, contraindications, expected_effectiveness}, otc_offer?, followup?, followup_urgency?}, grounded_in[]}`.',
|
|
30
30
|
items: { type: 'object' },
|
|
31
31
|
},
|
|
32
32
|
},
|