@peopl-health/nexus 5.72.0-dev.14114 → 5.72.0-dev.14403
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/AssistantProcessor.js +44 -0
- package/lib/clinical/context/ToolRuntimeContext.js +5 -0
- package/lib/clinical/flags/clinicalContextFlags.js +5 -0
- package/lib/clinical/helpers/clinicalContextHelper.js +27 -2
- package/lib/clinical/services/contextSyncRunner.js +10 -2
- package/lib/clinical/services/regimenCloserService.js +76 -15
- package/lib/clinical/services/turnRiskBriefService.js +24 -3
- package/lib/clinical/tools/deliverPatientMessageTool.js +1 -1
- package/lib/clinical/tools/getPatientRiskAssessmentTool.js +8 -4
- package/lib/clinical/tools/getRouterContextBundleTool.js +8 -4
- package/lib/clinical/tools/reportMedicalEscalationTool.js +1 -1
- package/lib/controllers/healthController.js +16 -0
- package/lib/core/NexusMessaging.js +3 -0
- package/lib/fhir/config/fhirConfig.js +16 -12
- package/lib/fhir/constants/variableRegistry.js +1 -1
- package/lib/helpers/airtableFormulaHelper.js +3 -0
- package/lib/helpers/healthHelper.js +40 -0
- package/lib/index.d.ts +16 -4
- package/lib/index.js +2 -1
- package/lib/routes/index.js +10 -0
- package/lib/services/carePlanHistoryService.js +4 -2
- package/lib/services/escalationCaseTaskService.js +1 -1
- package/lib/services/healthService.js +249 -0
- package/lib/services/inboundRecoveryService.js +1 -0
- package/lib/utils/dateUtils.js +13 -0
- package/package.json +1 -1
|
@@ -45,6 +45,12 @@ const deliveryOutcome = (result) => {
|
|
|
45
45
|
return 'unknown';
|
|
46
46
|
};
|
|
47
47
|
|
|
48
|
+
const NO_ASSISTANT = 'no_assistant';
|
|
49
|
+
|
|
50
|
+
// The model call is built from the preset or the prompt id; with neither the provider rejects it
|
|
51
|
+
// (`prompt.id` null). These threads are human-run (onboarding, office contacts) and ops is alerted upstream.
|
|
52
|
+
const hasPromptSource = (thread) => Boolean(thread?.preset_id || thread?.getAssistantId?.() || thread?.prompt_id);
|
|
53
|
+
|
|
48
54
|
class AssistantProcessor {
|
|
49
55
|
constructor({ mode = 'local', queueAdapter = null, sendMessage = null, phiProcessor = null, storeRunMetrics = null, llmMonitor = null, toolRuntimeRepos = {} }) {
|
|
50
56
|
Object.assign(this, { mode, queueAdapter, sendMessage, phiProcessor, storeRunMetrics, llmMonitor, toolRuntimeRepos });
|
|
@@ -64,6 +70,8 @@ class AssistantProcessor {
|
|
|
64
70
|
}
|
|
65
71
|
|
|
66
72
|
async executeLLM(thread, assistant, runOptions = {}, message = null) {
|
|
73
|
+
if (!hasPromptSource(thread)) return this._skipUnassignedTurn(thread, runOptions, message);
|
|
74
|
+
|
|
67
75
|
// Proactive outreach is not shadowed: the fork carries turnKind but not the outreach brief, so
|
|
68
76
|
// the shadow would answer a different question than production and any comparison would be an
|
|
69
77
|
// artefact of the missing block.
|
|
@@ -298,6 +306,42 @@ class AssistantProcessor {
|
|
|
298
306
|
};
|
|
299
307
|
}
|
|
300
308
|
|
|
309
|
+
async _skipUnassignedTurn(thread, runOptions, message) {
|
|
310
|
+
logger.info('[AssistantProcessor] thread has no preset or prompt; skipping the model call', {
|
|
311
|
+
code: thread?.code, turnId: runOptions.runId || null,
|
|
312
|
+
});
|
|
313
|
+
let ctx = runOptions.toolRuntimeContext || null;
|
|
314
|
+
if (!ctx && !runOptions.shadow && runOptions.runId && thread?.code) {
|
|
315
|
+
try {
|
|
316
|
+
ctx = new ToolRuntimeContext({
|
|
317
|
+
patientCode: thread.code,
|
|
318
|
+
turnId: runOptions.runId,
|
|
319
|
+
shouldContinue: runOptions.shouldContinue,
|
|
320
|
+
repos: this.toolRuntimeRepos,
|
|
321
|
+
shadow: false,
|
|
322
|
+
...resolveTurnContext({ turnKind: runOptions.turnKind, message }),
|
|
323
|
+
});
|
|
324
|
+
} catch (error) {
|
|
325
|
+
logger.warn('[AssistantProcessor] skipped turn will run untraced', { code: thread.code, error: error.message });
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
try {
|
|
329
|
+
await ctx?.storeSkipped?.(NO_ASSISTANT);
|
|
330
|
+
} catch (error) {
|
|
331
|
+
logger.warn('[AssistantProcessor] skipped turn left no trace', { turnId: runOptions.runId, error: error.message });
|
|
332
|
+
}
|
|
333
|
+
return {
|
|
334
|
+
output: null,
|
|
335
|
+
tools_executed: [],
|
|
336
|
+
turnId: runOptions.runId || null,
|
|
337
|
+
traceId: ctx?.trace?._id ? String(ctx.trace._id) : null,
|
|
338
|
+
completed: false,
|
|
339
|
+
skipped: NO_ASSISTANT,
|
|
340
|
+
retries: 0,
|
|
341
|
+
predictionTimeMs: 0,
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
|
|
301
345
|
async process({ code, runOptions = {}, message = null }) {
|
|
302
346
|
if (!code) throw new Error('code is required for assistant processing');
|
|
303
347
|
|
|
@@ -127,6 +127,11 @@ class ToolRuntimeContext {
|
|
|
127
127
|
await this.trace.save();
|
|
128
128
|
}
|
|
129
129
|
|
|
130
|
+
async storeSkipped(reason) {
|
|
131
|
+
this.trace.setStatus('skipped', { reason });
|
|
132
|
+
await this.trace.save();
|
|
133
|
+
}
|
|
134
|
+
|
|
130
135
|
setSafetyArtifact(artifact) {
|
|
131
136
|
this.safetyArtifact = this._requireArtifact('safetyArtifact', artifact);
|
|
132
137
|
}
|
|
@@ -22,6 +22,10 @@ function profileSyncOn() {
|
|
|
22
22
|
return flagOn('PATIENT_PROFILE_SYNC');
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
function regimenCloserLive() {
|
|
26
|
+
return flagOn('REGIMEN_CLOSER_WRITE_LIVE');
|
|
27
|
+
}
|
|
28
|
+
|
|
25
29
|
function contextMirrorLive() {
|
|
26
30
|
return flagOn('CLINICAL_CONTEXT_MIRROR_LIVE') && contextReadLive();
|
|
27
31
|
}
|
|
@@ -33,4 +37,5 @@ module.exports = {
|
|
|
33
37
|
contextVerifierLive,
|
|
34
38
|
profileFromMongo,
|
|
35
39
|
profileSyncOn,
|
|
40
|
+
regimenCloserLive,
|
|
36
41
|
};
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
const { LEGACY_CONCEPT, NO_KNOWN_ALLERGY } = require('../../fhir/constants/variableRegistry');
|
|
2
2
|
const { ageFrom, genderFrom } = require('../../fhir/resources/Patient');
|
|
3
|
-
const {
|
|
3
|
+
const {
|
|
4
|
+
ageInYears, daysBetween, isoDay, mexicoDay,
|
|
5
|
+
} = require('../../utils/dateUtils');
|
|
4
6
|
const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
|
|
5
7
|
const { decodePair } = require('./encodedPairHelper');
|
|
6
8
|
|
|
@@ -11,6 +13,7 @@ const FIELD_LABELS = {
|
|
|
11
13
|
diagnostico: 'Diagnóstico',
|
|
12
14
|
tratamiento_actual: 'Tratamiento actual',
|
|
13
15
|
medicacion_actual: 'Medicación',
|
|
16
|
+
tratamiento_suspendido: 'Suspendido recientemente',
|
|
14
17
|
alergias_medicamentos: 'Alergias',
|
|
15
18
|
comorbilidades: 'Comorbilidades',
|
|
16
19
|
episodios_intercurrentes: 'Episodios',
|
|
@@ -35,8 +38,26 @@ const RETRACTED = new Set(['resolved', 'inactive', 'stopped', 'not-done']);
|
|
|
35
38
|
// still stored and covering the field, but not rendered as what the patient has now
|
|
36
39
|
const NOT_CURRENT = new Set(['completed', 'not-taking', 'preparation']);
|
|
37
40
|
|
|
41
|
+
// a stopped drug stays in view while its late toxicity may still show: the sign-off of 2026-10-14 asks a year for
|
|
42
|
+
// checkpoint inhibitors, anthracyclines, ADCs and anti-HER2; every injectable gets it to avoid a catalog read, and
|
|
43
|
+
// an oral anti-HER2 inhibitor gets the 90 days of any oral
|
|
44
|
+
const RECENTLY_STOPPED_DAYS = Object.freeze({
|
|
45
|
+
injectable_onco_summary: 365,
|
|
46
|
+
oral_onco_summary: 90,
|
|
47
|
+
other_meds_summary: 90,
|
|
48
|
+
});
|
|
49
|
+
|
|
38
50
|
const isRetracted = (status) => RETRACTED.has(status);
|
|
39
51
|
|
|
52
|
+
function isRecentlyStopped(row, today = mexicoDay(new Date())) {
|
|
53
|
+
const windowDays = RECENTLY_STOPPED_DAYS[row.variableId];
|
|
54
|
+
if (!windowDays || row.status !== 'stopped') return false;
|
|
55
|
+
const days = daysBetween(isoDay(row.validTime), today);
|
|
56
|
+
return days >= 0 && days <= windowDays;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const dmy = (iso) => `${iso.slice(8, 10)}/${iso.slice(5, 7)}/${iso.slice(0, 4)}`;
|
|
60
|
+
|
|
40
61
|
function ageOf(patient) {
|
|
41
62
|
const derived = ageInYears(patient?.birthDate);
|
|
42
63
|
if (derived !== null && derived > 0 && derived < MAX_PLAUSIBLE_AGE) return derived;
|
|
@@ -54,9 +75,11 @@ function renderableValues(bucket) {
|
|
|
54
75
|
return preferring(current, NO_KNOWN_ALLERGY.concept).map((row) => decodePair(row.value));
|
|
55
76
|
}
|
|
56
77
|
|
|
57
|
-
function fieldsFromFhir(rows, patient) {
|
|
78
|
+
function fieldsFromFhir(rows, patient, today = mexicoDay(new Date())) {
|
|
58
79
|
const byVariable = new Map();
|
|
80
|
+
const stopped = [];
|
|
59
81
|
for (const row of rows) {
|
|
82
|
+
if (row.value && isRecentlyStopped(row, today)) stopped.push(`${decodePair(row.value)} (a más tardar ${dmy(isoDay(row.validTime))})`);
|
|
60
83
|
if (!row.value || isRetracted(row.status)) continue;
|
|
61
84
|
const bucket = byVariable.get(row.variableId) || [];
|
|
62
85
|
bucket.push(row);
|
|
@@ -70,6 +93,7 @@ function fieldsFromFhir(rows, patient) {
|
|
|
70
93
|
const values = renderableValues(variables.flatMap((variableId) => byVariable.get(variableId) || []));
|
|
71
94
|
if (values.length) fields[field] = values.join(VALUE_SEPARATOR);
|
|
72
95
|
}
|
|
96
|
+
if (stopped.length) fields.tratamiento_suspendido = stopped.join(VALUE_SEPARATOR);
|
|
73
97
|
return fields;
|
|
74
98
|
}
|
|
75
99
|
|
|
@@ -131,6 +155,7 @@ module.exports = {
|
|
|
131
155
|
withLegacyDemographics,
|
|
132
156
|
hasClinicalContent,
|
|
133
157
|
isRetracted,
|
|
158
|
+
isRecentlyStopped,
|
|
134
159
|
renderContextBlock,
|
|
135
160
|
swapProfilePortion,
|
|
136
161
|
VALUE_SEPARATOR,
|
|
@@ -1,12 +1,20 @@
|
|
|
1
|
+
const { regimenCloserLive } = require('../flags/clinicalContextFlags');
|
|
1
2
|
const { syncContextFacts } = require('./contextSyncService');
|
|
2
3
|
const { syncLegacyContext } = require('./legacyContextSyncService');
|
|
4
|
+
const { closeStoppedRegimens } = require('./regimenCloserService');
|
|
3
5
|
|
|
4
6
|
// Tier 1 reads what tier 2 wrote, so running them concurrently races a real fact against a floor on one key.
|
|
5
7
|
async function syncClinicalContext(options = {}) {
|
|
6
8
|
const facts = await syncContextFacts(options);
|
|
7
|
-
if (!facts.ok) return { ok: false, facts, legacy: null };
|
|
9
|
+
if (!facts.ok) return { ok: false, facts, legacy: null, closer: null };
|
|
8
10
|
const legacy = await syncLegacyContext(options);
|
|
9
|
-
|
|
11
|
+
// closes what the unit stopped giving after the facts tier wrote, so a fact restated this pass is seen; the
|
|
12
|
+
// per-patient list stays out of the result, which callers log
|
|
13
|
+
const closer = regimenCloserLive()
|
|
14
|
+
? await closeStoppedRegimens({ dryRun: options.dryRun ?? false, patientScope: options.patientScope ?? null })
|
|
15
|
+
: null;
|
|
16
|
+
const { patients: _patients, ...closerCounts } = closer ?? {};
|
|
17
|
+
return { ok: legacy.ok && (closer?.ok ?? true), facts, legacy, closer: closer ? closerCounts : null };
|
|
10
18
|
}
|
|
11
19
|
|
|
12
20
|
module.exports = { syncClinicalContext };
|
|
@@ -4,7 +4,8 @@ const { readRecordedChemo } = require('../helpers/clinicalProfileHelper');
|
|
|
4
4
|
const { getRecordByFilter } = require('../../services/airtableService');
|
|
5
5
|
const { Quimio_Ops_ID } = require('../../config/airtableConfig');
|
|
6
6
|
const { MATCH_ALL } = require('../../helpers/airtableFormulaHelper');
|
|
7
|
-
const { readContextFacts, listContextFactPatients } = require('../../fhir');
|
|
7
|
+
const { readContextFacts, listContextFactPatients, storeContextFacts } = require('../../fhir');
|
|
8
|
+
const { compareClaims } = require('../../fhir/helpers/contextArbitrationHelper');
|
|
8
9
|
const { mapConcurrent } = require('../../utils/concurrencyUtils');
|
|
9
10
|
const { daysBetween, mexicoDay } = require('../../utils/dateUtils');
|
|
10
11
|
const { maskSensitiveValue } = require('../../utils/sanitizerUtils');
|
|
@@ -18,6 +19,9 @@ const REGIMEN_MIN_DAYS = 21;
|
|
|
18
19
|
// a checkpoint inhibitor is often given every 6 weeks, or held for an immune toxicity
|
|
19
20
|
const CHECKPOINT_REGIMEN_MIN_DAYS = 84;
|
|
20
21
|
const INJECTABLE_VARIABLE = 'injectable_onco_summary';
|
|
22
|
+
// the unit's own record: a doctor's role, as trusted as the most trusted extractor source
|
|
23
|
+
const CLOSURE_SOURCE = 'unit';
|
|
24
|
+
const CLOSURE_TRUST = 0.95;
|
|
21
25
|
const CURRENT_STATUSES = new Set([null, 'taking', 'unknown']);
|
|
22
26
|
const PROPOSED_STATUS = 'stopped';
|
|
23
27
|
// the unit's catalog files support care and premedication apart; only its own antineoplastics are closed
|
|
@@ -38,6 +42,7 @@ const DEFAULT_PATIENT_CONCURRENCY = 10;
|
|
|
38
42
|
// a co-formulation such as pertuzumab/trastuzumab is each of its drugs
|
|
39
43
|
const keysOf = (drug) => drug.generic.split('/').map(drugKey);
|
|
40
44
|
const isCheckpoint = (key) => CHECKPOINT_INHIBITORS.has(key);
|
|
45
|
+
const endInstant = (day) => `${day}T00:00:00.000Z`;
|
|
41
46
|
const closable = (drug) => drug.group === CLOSABLE_GROUP && !NEVER_CLOSED.has(drugKey(drug.generic));
|
|
42
47
|
// the day as stated: a date-only report is stored at UTC midnight, which Mexico time would move to the day before
|
|
43
48
|
const dayOf = (row) => {
|
|
@@ -46,7 +51,7 @@ const dayOf = (row) => {
|
|
|
46
51
|
};
|
|
47
52
|
|
|
48
53
|
async function loadDrugIdentity() {
|
|
49
|
-
const catalog = await getRecordByFilter(Quimio_Ops_ID, CATALOG_TABLE, MATCH_ALL, null, CATALOG_FIELDS);
|
|
54
|
+
const catalog = await getRecordByFilter(Quimio_Ops_ID, CATALOG_TABLE, MATCH_ALL, null, CATALOG_FIELDS).catch(() => null);
|
|
50
55
|
return catalog?.length ? buildDrugIdentity(catalog) : null;
|
|
51
56
|
}
|
|
52
57
|
|
|
@@ -62,12 +67,15 @@ function skipReason(row, { chemo, identity, regimen, regimenDays, replacedInClas
|
|
|
62
67
|
return null;
|
|
63
68
|
}
|
|
64
69
|
|
|
70
|
+
// a closure dated on or before the slot's own statement could lose arbitration to it; the regimen start always
|
|
71
|
+
// falls after it, and the drug is absent from that regimen
|
|
65
72
|
function endOf(row, chemo, identity) {
|
|
66
73
|
const previous = new Set((chemo.esquemaPrevio?.farmacos ?? []).flatMap((name) => drugsNamed(name, identity).drugs).flatMap(keysOf));
|
|
67
74
|
const named = drugsNamed(row.concept ?? row.value, identity).drugs.flatMap(keysOf);
|
|
68
|
-
|
|
75
|
+
const end = previous.size && named.every((key) => previous.has(key))
|
|
69
76
|
? { endDate: chemo.esquemaPrevio.hasta, endFrom: 'esquemaPrevio' }
|
|
70
77
|
: { endDate: chemo.inicioEsquema.fecha, endFrom: 'inicioEsquema' };
|
|
78
|
+
return end.endDate <= dayOf(row) ? { endDate: chemo.inicioEsquema.fecha, endFrom: 'inicioEsquema' } : end;
|
|
71
79
|
}
|
|
72
80
|
|
|
73
81
|
// an injectable antineoplastic the unit stopped giving: absent from its current regimen and stated before that regimen began
|
|
@@ -97,17 +105,22 @@ function proposeClosures({ chemo, facts, identity, today = mexicoDay(new Date())
|
|
|
97
105
|
for (const row of facts) {
|
|
98
106
|
if (row.variableId !== INJECTABLE_VARIABLE || !CURRENT_STATUSES.has(row.status ?? null)) continue;
|
|
99
107
|
const reason = skipReason(row, { chemo, identity, regimen, regimenDays, replacedInClass });
|
|
100
|
-
|
|
101
|
-
|
|
108
|
+
const end = reason ? null : endOf(row, chemo, identity);
|
|
109
|
+
// a closure that loses arbitration to the slot would change nothing and be rewritten every pass
|
|
110
|
+
const claim = end && { source: CLOSURE_SOURCE, trust: CLOSURE_TRUST, validTime: endInstant(end.endDate) };
|
|
111
|
+
const skip = reason || (compareClaims(claim, row, INJECTABLE_VARIABLE, new Date().toISOString()) > 0 ? null : 'outranked');
|
|
112
|
+
if (skip) {
|
|
113
|
+
skipped[skip] = (skipped[skip] ?? 0) + 1;
|
|
102
114
|
continue;
|
|
103
115
|
}
|
|
104
116
|
closures.push({
|
|
105
117
|
conceptKey: row.conceptKey,
|
|
118
|
+
concept: row.concept,
|
|
106
119
|
drug: row.value,
|
|
107
120
|
status: row.status ?? null,
|
|
108
121
|
since: dayOf(row),
|
|
109
122
|
proposedStatus: PROPOSED_STATUS,
|
|
110
|
-
...
|
|
123
|
+
...end,
|
|
111
124
|
evidence: {
|
|
112
125
|
ultimaAplicacion: chemo.ultimaAplicacion,
|
|
113
126
|
esquema: chemo.esquema.map((entry) => entry.farmaco),
|
|
@@ -119,26 +132,74 @@ function proposeClosures({ chemo, facts, identity, today = mexicoDay(new Date())
|
|
|
119
132
|
return { closures, skipped };
|
|
120
133
|
}
|
|
121
134
|
|
|
122
|
-
|
|
135
|
+
const closureOf = (patientId, closure, recordTime) => ({
|
|
136
|
+
patientId,
|
|
137
|
+
variableId: INJECTABLE_VARIABLE,
|
|
138
|
+
concept: closure.concept,
|
|
139
|
+
value: closure.drug,
|
|
140
|
+
status: closure.proposedStatus,
|
|
141
|
+
source: CLOSURE_SOURCE,
|
|
142
|
+
trust: CLOSURE_TRUST,
|
|
143
|
+
validTime: endInstant(closure.endDate),
|
|
144
|
+
recordTime,
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
// an async scope answers with a promise, which is truthy, so every patient would pass
|
|
148
|
+
function inScope(patientIds, patientScope) {
|
|
149
|
+
if (!patientScope) return patientIds;
|
|
150
|
+
const answers = patientIds.map((patientId) => patientScope(patientId));
|
|
151
|
+
return answers.every((answer) => typeof answer === 'boolean') ? patientIds.filter((_, i) => answers[i]) : null;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// writes only with a patient scope, like the other context passes; a dry run lists what it would write
|
|
155
|
+
async function closeStoppedRegimens({ dryRun = true, patientScope = null, today = mexicoDay(new Date()) } = {}) {
|
|
156
|
+
const empty = { dryRun, closures: 0, written: 0, failed: 0, unreadable: 0, skipped: {}, patients: [] };
|
|
157
|
+
if (patientScope !== null && typeof patientScope !== 'function') return { ...empty, ok: false, reason: 'patient-scope-must-be-a-function' };
|
|
158
|
+
if (!patientScope && !dryRun) return { ...empty, ok: false, reason: 'patient-scope-required' };
|
|
123
159
|
const identity = await loadDrugIdentity();
|
|
124
|
-
if (!identity) return { ok: false,
|
|
160
|
+
if (!identity) return { ...empty, ok: false, reason: 'drug-catalog-unreadable' };
|
|
161
|
+
const listed = await listContextFactPatients().catch((error) => {
|
|
162
|
+
logger.error('[regimenCloser] Patients unreadable', { error: error.message });
|
|
163
|
+
return null;
|
|
164
|
+
});
|
|
165
|
+
if (!listed) return { ...empty, ok: false, reason: 'patients-unreadable' };
|
|
166
|
+
const scoped = inScope(listed, patientScope);
|
|
167
|
+
if (!scoped) return { ...empty, ok: false, reason: 'patient-scope-must-return-boolean' };
|
|
125
168
|
const patients = [];
|
|
126
169
|
const skipped = {};
|
|
127
170
|
let unreadable = 0;
|
|
128
|
-
|
|
171
|
+
let written = 0;
|
|
172
|
+
let failed = 0;
|
|
173
|
+
await mapConcurrent(scoped, DEFAULT_PATIENT_CONCURRENCY, async (patientId) => {
|
|
174
|
+
let result;
|
|
129
175
|
try {
|
|
130
176
|
const [chemo, facts] = await Promise.all([readRecordedChemo(patientId), readContextFacts({ patientId })]);
|
|
131
|
-
|
|
132
|
-
Object.entries(result.skipped).forEach(([reason, n]) => { skipped[reason] = (skipped[reason] ?? 0) + n; });
|
|
133
|
-
if (result.closures.length) patients.push({ patientId, closures: result.closures });
|
|
177
|
+
result = proposeClosures({ chemo, facts, identity, today });
|
|
134
178
|
} catch (error) {
|
|
135
179
|
unreadable += 1;
|
|
136
180
|
logger.error('[regimenCloser] Patient unreadable', { code: maskSensitiveValue(patientId), error: error.message });
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
Object.entries(result.skipped).forEach(([reason, n]) => { skipped[reason] = (skipped[reason] ?? 0) + n; });
|
|
184
|
+
if (!result.closures.length) return;
|
|
185
|
+
patients.push({ patientId, closures: result.closures });
|
|
186
|
+
if (dryRun) return;
|
|
187
|
+
const recordTime = new Date().toISOString();
|
|
188
|
+
for (const closure of result.closures) {
|
|
189
|
+
try {
|
|
190
|
+
await storeContextFacts({ patientId, assertions: [closureOf(patientId, closure, recordTime)] });
|
|
191
|
+
written += 1;
|
|
192
|
+
} catch (error) {
|
|
193
|
+
failed += 1;
|
|
194
|
+
logger.error('[regimenCloser] Closure rejected', { code: maskSensitiveValue(patientId), error: error.message });
|
|
195
|
+
}
|
|
137
196
|
}
|
|
138
197
|
});
|
|
139
198
|
const closures = patients.reduce((n, patient) => n + patient.closures.length, 0);
|
|
140
|
-
logger.info('[regimenCloser]
|
|
141
|
-
return { ok: !unreadable, dryRun
|
|
199
|
+
logger.info('[regimenCloser] Pass complete', { dryRun, patients: patients.length, closures, written, failed, unreadable, skipped });
|
|
200
|
+
return { ok: !unreadable && !failed, dryRun, closures, written, failed, unreadable, skipped, patients };
|
|
142
201
|
}
|
|
143
202
|
|
|
144
|
-
|
|
203
|
+
const dryRunRegimenClosures = ({ today } = {}) => closeStoppedRegimens({ dryRun: true, today });
|
|
204
|
+
|
|
205
|
+
module.exports = { proposeClosures, closeStoppedRegimens, dryRunRegimenClosures };
|
|
@@ -10,10 +10,11 @@ const SEVERITY_RANK = { emergency: 3, safety_relevant: 2, moderate: 1 };
|
|
|
10
10
|
|
|
11
11
|
const NOT_REPORTED_NOTE = 'El paciente no reportó ningún síntoma actual en este turno. Todo lo que aparezca en el perfil de riesgo son eventos PREVISTOS del tratamiento, no síntomas reportados: nunca afirmes que el paciente los reportó ni le atribuyas un grado.';
|
|
12
12
|
|
|
13
|
-
const emptyBrief = (escalations) => ({
|
|
13
|
+
const emptyBrief = (escalations, teamCases) => ({
|
|
14
14
|
current_concerns: [],
|
|
15
15
|
symptom_history: [],
|
|
16
16
|
recent_escalations: escalations,
|
|
17
|
+
team_cases: teamCases,
|
|
17
18
|
relevant_risks: [],
|
|
18
19
|
checks_now: [],
|
|
19
20
|
selection: 'no_current_concerns',
|
|
@@ -98,6 +99,24 @@ function escalationsFor(escalations, now) {
|
|
|
98
99
|
}));
|
|
99
100
|
}
|
|
100
101
|
|
|
102
|
+
// Every case the team still holds, and those it closed within the escalation window.
|
|
103
|
+
function teamCasesFor(escalationCases, now) {
|
|
104
|
+
if (!Array.isArray(escalationCases)) return [];
|
|
105
|
+
const since = escalationLookbackSince(now);
|
|
106
|
+
return escalationCases
|
|
107
|
+
.filter((escalationCase) => escalationCase.isOpen || Date.parse(escalationCase.closedAt ?? escalationCase.lastModified) >= since)
|
|
108
|
+
.slice(0, MAX_ESCALATIONS)
|
|
109
|
+
.map((escalationCase) => ({
|
|
110
|
+
status: escalationCase.label,
|
|
111
|
+
is_open: escalationCase.isOpen,
|
|
112
|
+
level: escalationCase.priority,
|
|
113
|
+
opened_at: isoDay(escalationCase.openedAt),
|
|
114
|
+
days_since: daysSince(escalationCase.openedAt, now),
|
|
115
|
+
doctor_decision: escalationCase.decision,
|
|
116
|
+
case_ids: escalationCase.conditionIds,
|
|
117
|
+
}));
|
|
118
|
+
}
|
|
119
|
+
|
|
101
120
|
const graded = (assessment) => Number.isInteger(assessment?.grade?.bestEstimate);
|
|
102
121
|
const at = (assessment) => Date.parse(assessment?.performedAt) || 0;
|
|
103
122
|
|
|
@@ -131,10 +150,11 @@ function historyFor(concerns, symptomCases, now) {
|
|
|
131
150
|
});
|
|
132
151
|
}
|
|
133
152
|
|
|
134
|
-
function buildTurnRiskBrief(profile, clinicalMentions = [], { symptomCases = [], escalations = [], now = Date.now() } = {}) {
|
|
153
|
+
function buildTurnRiskBrief(profile, clinicalMentions = [], { symptomCases = [], escalations = [], escalationCases = [], now = Date.now() } = {}) {
|
|
135
154
|
const recentEscalations = escalationsFor(escalations, now);
|
|
155
|
+
const teamCases = teamCasesFor(escalationCases, now);
|
|
136
156
|
const concerns = currentConcerns(clinicalMentions);
|
|
137
|
-
if (!concerns.length) return emptyBrief(recentEscalations);
|
|
157
|
+
if (!concerns.length) return emptyBrief(recentEscalations, teamCases);
|
|
138
158
|
|
|
139
159
|
const candidates = riskCandidates(profile).map((risk, index) => {
|
|
140
160
|
const riskTokens = tokens([risk.concern, risk.why, ...risk.warning_signs].join(' '));
|
|
@@ -181,6 +201,7 @@ function buildTurnRiskBrief(profile, clinicalMentions = [], { symptomCases = [],
|
|
|
181
201
|
current_concerns: concerns.map((concern) => concern.display),
|
|
182
202
|
symptom_history: historyFor(concerns, symptomCases, now),
|
|
183
203
|
recent_escalations: recentEscalations,
|
|
204
|
+
team_cases: teamCases,
|
|
184
205
|
relevant_risks: selected,
|
|
185
206
|
checks_now: dedupe(selected.flatMap((risk) => risk.checks_now)).slice(0, MAX_CHECKS),
|
|
186
207
|
selection: !candidates.length
|
|
@@ -9,7 +9,7 @@ const EMPTY_OUTBOUND_FALLBACK = 'Recibí tu mensaje. Si quieres contarme más o
|
|
|
9
9
|
const definition = {
|
|
10
10
|
name: 'DeliverPatientMessage',
|
|
11
11
|
replayArgs: ['message_text', 'purpose'],
|
|
12
|
-
description: '**Does:** Delivers the final, patient-facing message in Spanish — the only tool that produces text the patient sees. Call exactly ONCE as the last action of every CHAT turn.\n\n**Required inputs:** `message_text` (the message itself, in Spanish); `purpose` (the conversational purpose); `reasoning` (one short sentence, never shown to the patient, explaining why this is the right message for this turn).\n\n**When to call:** at the end of every chat turn — once. Every substantive inbound must first complete an intake/classification decision. When that decision extracts clinical mentions, code enforces: processed risk through `getRouterContextBundle` (or its dedicated recovery) → `submitRoutingDecision` → this tool. A committed non-clinical terminal workflow may deliver without clinical risk/routing. A rejected call returns the missing step in `data.recovery`; perform it and regenerate the message.\n\n**When NOT to call:**\n- More than once per turn — only ONE patient-facing message per turn.\n- Before the required classification or clinical chain is complete. A rejected call does not set outbound text.\n\n**Returns:** a RECORD, not a send — `{purpose, recorded, delivered:false, still_active, means}`. The reply is stored as the outbound of this turn and leaves only when the turn finishes as the active run; a newer patient message drops it and `still_active` is `false`. Never treat the patient as informed because this call succeeded.\n\n**Side effects:** records the final patient-facing message on the turn trace; delivery to the patient is handled downstream.',
|
|
12
|
+
description: '**Does:** Delivers the final, patient-facing message in Spanish — the only tool that produces text the patient sees. Call exactly ONCE as the last action of every CHAT turn.\n\n**Required inputs:** `message_text` (the message itself, in Spanish); `purpose` (the conversational purpose); `reasoning` (one short sentence, never shown to the patient, explaining why this is the right message for this turn).\n\n**When to call:** at the end of every chat turn — once. Every substantive inbound must first complete an intake/classification decision. When that decision extracts clinical mentions, code enforces: processed risk through `getRouterContextBundle` (or its dedicated recovery) → `submitRoutingDecision` → this tool. A committed non-clinical terminal workflow may deliver without clinical risk/routing. A rejected call returns the missing step in `data.recovery`; perform it and regenerate the message.\n\n**When NOT to call:**\n- More than once per turn — only ONE patient-facing message per turn.\n- Before the required classification or clinical chain is complete. A rejected call does not set outbound text.\n\n**When the patient asks what the care team answered:** say where the case stands from `turn_focus.team_cases` (load `getRouterContextBundle` first if you have not this turn). Never add a time, and never say the team already reviewed or saw something unless the status is one where the team answered (`Esperando paciente`, `Indicaciones dadas`, `En vigilancia`).\n\n**Returns:** a RECORD, not a send — `{purpose, recorded, delivered:false, still_active, means}`. The reply is stored as the outbound of this turn and leaves only when the turn finishes as the active run; a newer patient message drops it and `still_active` is `false`. Never treat the patient as informed because this call succeeded.\n\n**Side effects:** records the final patient-facing message on the turn trace; delivery to the patient is handled downstream.',
|
|
13
13
|
strict: false,
|
|
14
14
|
parameters: {
|
|
15
15
|
type: 'object',
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
const { assembleRiskProfile } = require('../services/riskAssessmentService');
|
|
2
2
|
const { buildTurnRiskBrief, escalationLookbackSince } = require('../services/turnRiskBriefService');
|
|
3
|
-
const { readDispatchedEscalations, readSymptomCases } = require('../../fhir');
|
|
3
|
+
const { readDispatchedEscalations, readEscalationCases, readSymptomCases } = require('../../fhir');
|
|
4
4
|
const { logger } = require('../../utils/logger');
|
|
5
5
|
|
|
6
6
|
const definition = {
|
|
7
7
|
name: 'getPatientRiskAssessment',
|
|
8
|
-
description: '**Does:** Returns the patient\'s latest full risk assessment and a deterministic `turn_focus` for the symptoms extracted in this turn. Read-only; no model call.\n\n**Required inputs:** none.\n\n**When to call:** immediately before `submitRoutingDecision` only when `getRouterContextBundle.sections_returned` does not contain `risk`, including a bundle result with `_diagnostics.risk_error`. The routine load is the bundle\'s mandatory `risk` section, which resolves the same assessment through the same code path.\n\n**When NOT to call:** when `getRouterContextBundle` already returned `risk` this turn — it is the same assessment, and a second read cannot change it. Nor again in the same turn after a `not_generated` result — generation runs between turns and the result cannot change mid-turn.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT
|
|
8
|
+
description: '**Does:** Returns the patient\'s latest full risk assessment and a deterministic `turn_focus` for the symptoms extracted in this turn. Read-only; no model call.\n\n**Required inputs:** none.\n\n**When to call:** immediately before `submitRoutingDecision` only when `getRouterContextBundle.sections_returned` does not contain `risk`, including a bundle result with `_diagnostics.risk_error`. The routine load is the bundle\'s mandatory `risk` section, which resolves the same assessment through the same code path.\n\n**When NOT to call:** when `getRouterContextBundle` already returned `risk` this turn — it is the same assessment, and a second read cannot change it. Nor again in the same turn after a `not_generated` result — generation runs between turns and the result cannot change mid-turn.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT; where the team is with it is in `team_cases`. A complaint unchanged since an escalation a day ago rarely needs a second dispatch; one still uncontrolled days after its escalation needs one at a HIGHER urgency, and `urgency_justification` should say which of the two this is. Empty means nothing was escalated in the window.\n\n**`turn_focus.team_cases` — where the care team is with each case.** Every case the team still holds, and those it closed in the last 14 days, newest first: `status`, `is_open`, `level`, `opened_at`, `days_since`, `doctor_decision` and `case_ids` (the symptom cases it covers).\n- `Por revisar`, `En evaluación`, `Con el médico`, `Indicación por enviar`, `Requiere valoración`: the team has it and has not answered yet. Tell the patient it is with the team, without promising a time. A new escalation is for a new symptom, a higher grade, a new red flag, or a symptom that persists or worsens while it waits (send it as an update).\n- `Esperando paciente`, `Indicaciones dadas`, `En vigilancia`: the team already answered (an indication on its way to the patient, given, or under watch). This comes first: ask how the indication is going before escalating again.\n- `Cerrado`, `No requiere`: the team closed it. A new complaint is a new decision.\n`doctor_decision` is internal (`approved`, `edited_approved`, `monitor`, `needs_intervention` = the doctor asked for an in-person evaluation, `returned`, `direct_chat`): use it to understand the case, never quote it. `team_cases` never says whether the problem resolved; ask the patient. An escalation in `recent_escalations` with no case here has an unknown team status, not an absent one.\n\n**Use `turn_focus.symptom_history` before grading or escalating.** It carries what no other section does: how this patient compares to their own past. `worst_grade` and `worst_reported_at` are the worst they have ever been recorded, `at_personal_worst` says whether they are back at it, and `days_since_last_report` says how stale `last_grade` is. (The current grade and trajectory are already in `landscape.active_cases` — do not expect them repeated here.) Escalate on the comparison, not on severity alone: a patient at their personal worst is a different decision from one below it, and a grade unchanged for weeks is different from the same grade reported yesterday. When you ask about it, anchor the question in the value and the date so the patient can compare. Empty means no graded case on record. \n\n**How to use:** read `turn_focus.current_concerns`, then each `relevant_risks[].checks_now` and `escalation_threshold`. It preserves concurrent symptoms. Any `selection` containing `fallback` marks a precaution to check, not a confirmed explanation. When `selection` is `no_current_concerns` the patient reported no current symptom this turn. Use `profile` only for supporting detail.\n\n**`profile` is a forecast, not history:** `predicted_aes[].minimum_symptom_set`, `disease_risks[].warning_symptoms` and every other profile list name symptoms to watch for, none of which the patient has reported. Never tell the patient a profile symptom appears in their report, and never attach a CTCAE grade to one. Reported symptoms come only from `turn_focus.current_concerns`.\n\n**Returns:** `status` — `final` when an assessment exists and carries findings, `no_signal` when one exists but the synthesis found nothing usable, or `not_generated`; `turn_focus`, always present; and the full `profile` (`predicted_aes[]`, `disease_risks[]`, `comorbidity_amplifiers[]`, lifecycle and missing-information fields). `profile` is null when not yet generated.',
|
|
9
9
|
strict: false,
|
|
10
10
|
replayScope: 'turn',
|
|
11
11
|
parameters: {
|
|
@@ -21,7 +21,7 @@ async function handler(_args = {}, context = {}) {
|
|
|
21
21
|
if (!runtime?.turnId || !runtime?.patientCode) {
|
|
22
22
|
return JSON.stringify({ success: false, error: 'getPatientRiskAssessment requires an active turn context (turnId, patientCode).', data: {} });
|
|
23
23
|
}
|
|
24
|
-
const [data, symptomCases, escalations] = await Promise.all([
|
|
24
|
+
const [data, symptomCases, escalations, escalationCases] = await Promise.all([
|
|
25
25
|
assembleRiskProfile(runtime.patientCode),
|
|
26
26
|
readSymptomCases({ patientId: runtime.patientCode }).catch((error) => {
|
|
27
27
|
logger.warn('[getPatientRiskAssessment] symptom history unavailable', { code: runtime.patientCode, error: error?.message });
|
|
@@ -32,8 +32,12 @@ async function handler(_args = {}, context = {}) {
|
|
|
32
32
|
logger.warn('[getPatientRiskAssessment] escalation recall unavailable', { code: runtime.patientCode, error: error?.message });
|
|
33
33
|
return [];
|
|
34
34
|
}),
|
|
35
|
+
readEscalationCases({ patientId: runtime.patientCode }).catch((error) => {
|
|
36
|
+
logger.warn('[getPatientRiskAssessment] team cases unavailable', { code: runtime.patientCode, error: error?.message });
|
|
37
|
+
return [];
|
|
38
|
+
}),
|
|
35
39
|
]);
|
|
36
|
-
const turnFocus = buildTurnRiskBrief(data.profile, runtime.trace?.signals?.clinicalMentions, { symptomCases, escalations });
|
|
40
|
+
const turnFocus = buildTurnRiskBrief(data.profile, runtime.trace?.signals?.clinicalMentions, { symptomCases, escalations, escalationCases });
|
|
37
41
|
const result = { ...data, turn_focus: turnFocus };
|
|
38
42
|
runtime.trace?.setSignals?.({
|
|
39
43
|
riskAssessmentChecked: true,
|
|
@@ -2,7 +2,7 @@ const { assembleLandscape } = require('../services/symptomLandscapeService');
|
|
|
2
2
|
const { assembleHistory, SUPPORTED_SCOPES, TIMEFRAME_DAYS } = require('../services/patientHistoryService');
|
|
3
3
|
const { assembleRiskProfile } = require('../services/riskAssessmentService');
|
|
4
4
|
const { buildTurnRiskBrief, escalationLookbackSince } = require('../services/turnRiskBriefService');
|
|
5
|
-
const { readDispatchedEscalations, readSymptomCases } = require('../../fhir');
|
|
5
|
+
const { readDispatchedEscalations, readEscalationCases, readSymptomCases } = require('../../fhir');
|
|
6
6
|
const { logger } = require('../../utils/logger');
|
|
7
7
|
|
|
8
8
|
const ALLOWED_SECTIONS = ['landscape', 'history', 'risk'];
|
|
@@ -10,7 +10,7 @@ const REQUIRED_SECTION = 'risk';
|
|
|
10
10
|
|
|
11
11
|
const definition = {
|
|
12
12
|
name: 'getRouterContextBundle',
|
|
13
|
-
description: '**Does:** Batched router-context fetch — always evaluates and returns the mandatory `risk` section, plus the requested `landscape` and/or `history` sections. Read-only.\n\n**Required inputs:** none. Optional `include` selects additional sections (`landscape`, `history`; a supplied `risk` value is accepted but redundant), plus optional `landscape_min_priority`, `history_scope`, `history_filter`. Omitting `include` returns all three sections.\n\n**When to call:** after intake at the start of every routing turn, as the single load of the patient\'s clinical context. Do not call it in parallel with `Skill(clinical_routing)`: first read the skill body, then call this bundle. The patient\'s risk disposition cannot be excluded by `include`. Prefer this over calling `getActiveSymptomLandscape`, `getPatientHistory` or `getPatientRiskAssessment` for the same context.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT
|
|
13
|
+
description: '**Does:** Batched router-context fetch — always evaluates and returns the mandatory `risk` section, plus the requested `landscape` and/or `history` sections. Read-only.\n\n**Required inputs:** none. Optional `include` selects additional sections (`landscape`, `history`; a supplied `risk` value is accepted but redundant), plus optional `landscape_min_priority`, `history_scope`, `history_filter`. Omitting `include` returns all three sections.\n\n**When to call:** after intake at the start of every routing turn, as the single load of the patient\'s clinical context. Do not call it in parallel with `Skill(clinical_routing)`: first read the skill body, then call this bundle. The patient\'s risk disposition cannot be excluded by `include`. Prefer this over calling `getActiveSymptomLandscape`, `getPatientHistory` or `getPatientRiskAssessment` for the same context.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT; where the team is with it is in `team_cases`. A complaint unchanged since an escalation a day ago rarely needs a second dispatch; one still uncontrolled days after its escalation needs one at a HIGHER urgency, and `urgency_justification` should say which of the two this is. Empty means nothing was escalated in the window.\n\n**`turn_focus.team_cases` — where the care team is with each case.** Every case the team still holds, and those it closed in the last 14 days, newest first: `status`, `is_open`, `level`, `opened_at`, `days_since`, `doctor_decision` and `case_ids` (the symptom cases it covers).\n- `Por revisar`, `En evaluación`, `Con el médico`, `Indicación por enviar`, `Requiere valoración`: the team has it and has not answered yet. Tell the patient it is with the team, without promising a time. A new escalation is for a new symptom, a higher grade, a new red flag, or a symptom that persists or worsens while it waits (send it as an update).\n- `Esperando paciente`, `Indicaciones dadas`, `En vigilancia`: the team already answered (an indication on its way to the patient, given, or under watch). This comes first: ask how the indication is going before escalating again.\n- `Cerrado`, `No requiere`: the team closed it. A new complaint is a new decision.\n`doctor_decision` is internal (`approved`, `edited_approved`, `monitor`, `needs_intervention` = the doctor asked for an in-person evaluation, `returned`, `direct_chat`): use it to understand the case, never quote it. `team_cases` never says whether the problem resolved; ask the patient. An escalation in `recent_escalations` with no case here has an unknown team status, not an absent one.\n\n**Use `turn_focus.symptom_history` before grading or escalating.** It carries what no other section does: how this patient compares to their own past. `worst_grade` and `worst_reported_at` are the worst they have ever been recorded, `at_personal_worst` says whether they are back at it, and `days_since_last_report` says how stale `last_grade` is. (The current grade and trajectory are already in `landscape.active_cases` — do not expect them repeated here.) Escalate on the comparison, not on severity alone: a patient at their personal worst is a different decision from one below it, and a grade unchanged for weeks is different from the same grade reported yesterday. When you ask about it, anchor the question in the value and the date so the patient can compare. Empty means no graded case on record. \n\n**A case flagged `stale_no_recent_evidence` has had no new evidence for two weeks or more.** `days_since_evidence` says how long. Ask whether the symptom is still there, and close the case with `recordClinicalImpression` `close` when it is not: an open case keeps consuming the landscape and keeps the symptom reading as active on the record.\n\n**How to use risk:** read `risk.turn_focus` first — it is always present. It deterministically keeps every current symptom and maps it to relevant full-profile risks, `checks_now`, and `escalation_threshold`; use the full `risk.profile` only for supporting detail. A highest-severity fallback is labelled explicitly when no direct symptom match exists. When `turn_focus.selection` is `no_current_concerns` the patient reported no current symptom this turn.\n\n**`risk.profile` is a forecast, not history:** `predicted_aes[].minimum_symptom_set`, `disease_risks[].warning_symptoms` and every other profile list name symptoms to watch for, none of which the patient has reported. Never tell the patient a profile symptom appears in their report, and never attach a CTCAE grade to one. Reported symptoms come only from `landscape`, `history` and `turn_focus.current_concerns`.\n\n**Recovery:** verify `sections_returned` contains `risk`. If it does not, inspect `_diagnostics.risk_error` and call `getPatientRiskAssessment` before `submitRoutingDecision`.\n\n**Returns:** `patient_id`, `sections_requested[]`, `sections_returned[]` (only sections that succeeded), mandatory `risk` (always including `turn_focus`), and requested `landscape` / `history`. A section that errors is omitted and its error reported under `_diagnostics`. The attempted risk read and deterministic turn processing are recorded on the turn trace even when no profile exists.',
|
|
14
14
|
strict: false,
|
|
15
15
|
replayScope: 'turn',
|
|
16
16
|
parameters: {
|
|
@@ -65,7 +65,7 @@ async function handler(args = {}, context = {}) {
|
|
|
65
65
|
if (args.history_scope != null) historyArgs.scope = args.history_scope;
|
|
66
66
|
if (args.history_filter != null) historyArgs.filter = args.history_filter;
|
|
67
67
|
|
|
68
|
-
const [symptomCases, escalations] = await Promise.all([
|
|
68
|
+
const [symptomCases, escalations, escalationCases] = await Promise.all([
|
|
69
69
|
readSymptomCases({ patientId }).catch((error) => {
|
|
70
70
|
logger.warn('[routerContextBundle] symptom cases unavailable', { code: patientId, error: error?.message });
|
|
71
71
|
return null;
|
|
@@ -74,6 +74,10 @@ async function handler(args = {}, context = {}) {
|
|
|
74
74
|
logger.warn('[routerContextBundle] escalation recall unavailable', { code: patientId, error: error?.message });
|
|
75
75
|
return [];
|
|
76
76
|
}),
|
|
77
|
+
readEscalationCases({ patientId }).catch((error) => {
|
|
78
|
+
logger.warn('[routerContextBundle] team cases unavailable', { code: patientId, error: error?.message });
|
|
79
|
+
return [];
|
|
80
|
+
}),
|
|
77
81
|
]);
|
|
78
82
|
|
|
79
83
|
const readers = {
|
|
@@ -93,7 +97,7 @@ async function handler(args = {}, context = {}) {
|
|
|
93
97
|
bundle[section] = outcome.value;
|
|
94
98
|
bundle.sections_returned.push(section);
|
|
95
99
|
if (section === 'risk') {
|
|
96
|
-
const turnFocus = buildTurnRiskBrief(outcome.value.profile, runtime.trace?.signals?.clinicalMentions, { symptomCases: symptomCases || [], escalations });
|
|
100
|
+
const turnFocus = buildTurnRiskBrief(outcome.value.profile, runtime.trace?.signals?.clinicalMentions, { symptomCases: symptomCases || [], escalations, escalationCases });
|
|
97
101
|
bundle[section] = { ...outcome.value, turn_focus: turnFocus };
|
|
98
102
|
// Same signal shape as getPatientRiskAssessmentTool: utilization metrics must count both read paths.
|
|
99
103
|
runtime.trace?.setSignals?.({
|
|
@@ -25,7 +25,7 @@ const FEVER_RULE = 'Fever that is `stat`: ≥38.0 °C within 8 weeks of cytotoxi
|
|
|
25
25
|
|
|
26
26
|
const definition = {
|
|
27
27
|
'name': 'reportMedicalEscalation',
|
|
28
|
-
'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; the payload is INTERNAL — the patient never sees it.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate without a further clarifying question: `asap` by default, `stat` if there is an acute deficit (can\'t walk/stand, sphincter loss, bilateral leg weakness → possible cord compression) or any instability.\n\n**When NOT to call:**\n- Unconfirmed/unspecific symptom — ask ONE characterization question via `DeliverPatientMessage` first.\n- Active mental-health crisis — use `reportCrisis`.\n- Patient shared lab/imaging/values/files — use `reportResultsReceived`.\n- Administrative / operative matter (appointments, insurance, authorizations, letters, transport, scheduling, out-of-scope request) or a non-clinical referral (psico-oncología, paliativos, non-oncology medical) — use `reportUnresolvedRequestv2`.\n- Twice in the same turn for the same episode — already committed; a later datum belongs to the same open escalation.\n\n**After the commit:** the escalation does not end the conversation.\n- **Patient message** (`DeliverPatientMessage`, calm, ≤60 words): acknowledge what they told you → \'Ya avisé al equipo médico\' → ONE concrete next step → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside `stat` and the fever rule, no warning signs by default: naming a sign the patient did not mention makes them watch for it and feel it. If one is truly needed, give at most ONE per episode, about the symptom they already reported getting worse or not easing (\'si el dolor no cede con lo que tomas, escríbeme y lo vemos\') — never another body part or symptom, never a list (not even of related symptoms), never the last line. Outside `stat` never write \'de inmediato\', \'con urgencia\', \'máxima urgencia\', \'no esperes\', \'por si acaso\' or \'es poco probable, pero\' — not in \'escríbeme de inmediato\' nor in \'ya avisé con urgencia\': the priority travels to the team, not to the patient. Explain the purpose only in general words (\'para revisar qué está pasando y ver si necesitas algo más\'): never name an organ, a complication, a mechanism or what is being ruled out (\'descartar que sea del corazón\', \'una presión en la columna\') — to an oncology patient that reads as a diagnosis. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` is the ONLY level that sends the patient now — calm and unambiguous: ve a urgencias ahora, acompañado; 911 (or an ambulance) if they are alone with no one to take them, cannot move safely, or are unstable — being alone counts as unsafe transport, and they never drive themselves. ' + FEVER_RULE + '`asap` and `urgent`: no urgencias and no 911 in the message, not even as a condition — the team decides where they are seen (two exceptions: the fever rule, and chest pain with only mild or doubtful shortness of breath, kept at `asap`, where one calm conditional line stays: \'si te cuesta más respirar o el dolor aumenta, ve a urgencias acompañado\'). If they ask whether to go to urgencias or what to watch, answer honestly with 1–2 points about their symptom — the only case where more than one sign is fine. Chest pain alone is not `stat` (anxiety, gastritis, muscle); chest pain WITH clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw IS `stat` (on checkpoint-inhibitor immunotherapy, chest pain is at least `asap`) — even if the patient sounds calm, and even if the two come in different messages of the same episode; otherwise ask ONE question first. `routine`: acknowledgement and when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, after the instruction only confirm they are on their way and accompanied.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and make the fallback explicit to the patient whenever nothing is armed. `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
|
|
28
|
+
'description': '**Does:** Escalates a MEDICAL situation to the oncology care team at a chosen urgency, with an explicit justification for the level. Covers the full medical-urgency spectrum — immediate emergencies through asynchronous team review. One-way commit; the payload is INTERNAL — the patient never sees it.\n\n**Required inputs:** `urgency_level` — the FHIR request-priority code (`stat` | `asap` | `urgent` | `routine`), `urgency_justification` (one or two sentences: why this level AND why not the tier above/below — the auditable decision record), `details` (object — `symptom` + `evidence_quote` required; pass `null` when unknown for `category`, `indicators`, `suspected_condition`, `recommended_action`).\n\n**Urgency levels:** FHIR request-priority, a RELATIVE order `routine` < `urgent` < `asap` < `stat` (priority/speed, not a fixed clock). The full per-tier rubric with clinical examples lives on the `urgency_level` input enum — read it there. Out-of-enum values are coerced to `urgent` and disclosed via `coerced_urgency` on the result.\n\n**Neurological constellation override:** TWO OR MORE of — visual change, dizziness/vertigo/loss of balance, inability to walk/stand, focal weakness/numbness, acute confusion, sudden severe headache — reported this turn or across the last 2–3 turns → escalate without a further clarifying question: `asap` by default, `stat` if there is an acute deficit (can\'t walk/stand, sphincter loss, bilateral leg weakness → possible cord compression) or any instability.\n\n**When NOT to call:**\n- An open case in `turn_focus.team_cases` already covers this symptom at this level or higher. Read it before calling (load `getRouterContextBundle` first if you have not this turn). Call again, as an update, only for a new symptom, a higher grade, a new red flag, a detail that makes something more serious plausible, or a symptom that persists or worsens while the team has not answered; a characterization detail that changes none of these needs no call. Otherwise tell the patient where the case stands.\n- Unconfirmed/unspecific symptom — ask ONE characterization question via `DeliverPatientMessage` first.\n- Active mental-health crisis — use `reportCrisis`.\n- Patient shared lab/imaging/values/files — use `reportResultsReceived`.\n- Administrative / operative matter (appointments, insurance, authorizations, letters, transport, scheduling, out-of-scope request) or a non-clinical referral (psico-oncología, paliativos, non-oncology medical) — use `reportUnresolvedRequestv2`.\n- Twice in the same turn for the same episode — already committed; a later datum belongs to the same open escalation.\n\n**After the commit:** the escalation does not end the conversation.\n- **Patient message** (`DeliverPatientMessage`, calm, ≤60 words): acknowledge what they told you → \'Ya avisé al equipo médico\' → ONE concrete next step → availability: \'si algo cambia o te preocupa, escríbeme por aquí\'. Outside `stat` and the fever rule, no warning signs by default: naming a sign the patient did not mention makes them watch for it and feel it. If one is truly needed, give at most ONE per episode, about the symptom they already reported getting worse or not easing (\'si el dolor no cede con lo que tomas, escríbeme y lo vemos\') — never another body part or symptom, never a list (not even of related symptoms), never the last line. Outside `stat` never write \'de inmediato\', \'con urgencia\', \'máxima urgencia\', \'no esperes\', \'por si acaso\' or \'es poco probable, pero\' — not in \'escríbeme de inmediato\' nor in \'ya avisé con urgencia\': the priority travels to the team, not to the patient. Explain the purpose only in general words (\'para revisar qué está pasando y ver si necesitas algo más\'): never name an organ, a complication, a mechanism or what is being ruled out (\'descartar que sea del corazón\', \'una presión en la columna\') — to an oncology patient that reads as a diagnosis. Reassure with the plan (\'ya le avisé al equipo médico para que lo revise\', \'vamos a darle seguimiento contigo\'), never with promises (\'no es nada\', \'no te preocupes\'). No diagnosis names, no lists of alarming symptoms, no \'grave/peligroso\', no timed fallback (\'si en 15 minutos…\'), and no promised contact time — not even \'te contactan hoy en las próximas horas\'; say what the team was asked to do (\'le pedí al equipo médico que lo revise\'), never that someone is already reviewing it, and not when they will reach out.\n- **By level:** `stat` is the ONLY level that sends the patient now — calm and unambiguous: ve a urgencias ahora, acompañado; 911 (or an ambulance) if they are alone with no one to take them, cannot move safely, or are unstable — being alone counts as unsafe transport, and they never drive themselves. ' + FEVER_RULE + '`asap` and `urgent`: no urgencias and no 911 in the message, not even as a condition — the team decides where they are seen (two exceptions: the fever rule, and chest pain with only mild or doubtful shortness of breath, kept at `asap`, where one calm conditional line stays: \'si te cuesta más respirar o el dolor aumenta, ve a urgencias acompañado\'). If they ask whether to go to urgencias or what to watch, answer honestly with 1–2 points about their symptom — the only case where more than one sign is fine. Chest pain alone is not `stat` (anxiety, gastritis, muscle); chest pain WITH clear shortness of breath, cold sweat, fainting or spreading to the arm or jaw IS `stat` (on checkpoint-inhibitor immunotherapy, chest pain is at least `asap`) — even if the patient sounds calm, and even if the two come in different messages of the same episode; otherwise ask ONE question first. `routine`: acknowledgement and when to write again.\n- **Keep characterizing (except `stat`):** in the same message ask the ONE question that most helps the team; in later turns keep going, one question per message, and give high-value guidance that does not prescribe (comfort measures already in their plan or indicated by the team, what to have at hand, how to monitor). Each new datum goes to the SAME open escalation, not a new one: raise the level if it makes something more serious plausible; never lower it. In `stat`, after the instruction only confirm they are on their way and accompanied.\n\n**Returns:** a RECEIPT, not a resolution — `{urgency_level, queued_for_team, safety_net_armed, safety_net_reason, team_has_reviewed, means, follow_up}`. `safety_net_armed` is `true`/`false`/`null`, where **`null` means this urgency tier gets no automatic check-in at all** (`routine`); read `follow_up` and make the fallback explicit to the patient whenever nothing is armed. `queued_for_team` says only that the ticket was written; `team_has_reviewed` is always `false` here because nothing on this path can know otherwise. Treat the escalation as OPEN and still your responsibility for the rest of the conversation: never tell the patient the team already reviewed it, and never close the topic because this call succeeded. If `queued_for_team` is `false` the team was NOT notified — say so instead of implying they were. When your `urgency_level` was out-of-enum it is coerced to `urgent` and disclosed via `{coerced_urgency, requested_urgency_level}`. A `details.category` outside the enum is dropped to `null` and disclosed via `{coerced_category, requested_category}`.\n\n**Side effects:** Emits `MEDICAL_ESCALATION_TRIGGERED`; the runtime routes it to the team by level (pages at `stat`/`asap`, ticket at `urgent`/`routine`).',
|
|
29
29
|
'strict': true,
|
|
30
30
|
'parameters': {
|
|
31
31
|
'type': 'object',
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const { logger } = require('../utils/logger');
|
|
2
|
+
|
|
3
|
+
const { getHealthSummary } = require('../services/healthService');
|
|
4
|
+
|
|
5
|
+
const getHealthSummaryController = async (req, res) => {
|
|
6
|
+
res.set('Cache-Control', 'private, no-store');
|
|
7
|
+
try {
|
|
8
|
+
const summary = await getHealthSummary({ force: req.query.force === 'true' });
|
|
9
|
+
res.json({ success: true, ...summary });
|
|
10
|
+
} catch (error) {
|
|
11
|
+
logger.error('[HealthController] Error computing the health summary:', { error: error.message });
|
|
12
|
+
res.status(500).json({ success: false, error: error.message || 'Failed to compute the health summary' });
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
module.exports = { getHealthSummaryController };
|
|
@@ -1058,6 +1058,9 @@ class NexusMessaging {
|
|
|
1058
1058
|
if (!runResult) {
|
|
1059
1059
|
return { decision: 'skipped', rationale: '', holdReason: 'turn_not_run', nextCheckAt: null, delivered: false, turnId: null, traceId: null };
|
|
1060
1060
|
}
|
|
1061
|
+
if (runResult.skipped) {
|
|
1062
|
+
return { decision: 'skipped', rationale: '', holdReason: runResult.skipped, nextCheckAt: null, delivered: false, turnId: runResult.turnId || null, traceId: runResult.traceId || null };
|
|
1063
|
+
}
|
|
1061
1064
|
|
|
1062
1065
|
const decision = runResult.signals?.outreachDecision || null;
|
|
1063
1066
|
if (!decision) throw new Error('OUTREACH_DECISION_MISSING');
|
|
@@ -3,12 +3,17 @@ const { Config_ID } = require('../../config/airtableConfig');
|
|
|
3
3
|
const { getRecordByFilter } = require('../../services/airtableService');
|
|
4
4
|
|
|
5
5
|
const { safeParse, safeParseArray } = require('../../utils/jsonUtils');
|
|
6
|
+
const { logger } = require('../../utils/logger');
|
|
6
7
|
|
|
7
8
|
const FHIR_CONFIG_TABLE = 'fhir';
|
|
9
|
+
// Every stored resource key, extension url and code system is built on these. They are identity, not
|
|
10
|
+
// configuration: an edited base would fork the corpus into duplicates and orphan every stored extension.
|
|
11
|
+
const BASES = {
|
|
12
|
+
IDENT_BASE: 'https://peopl.health/fhir/identifier',
|
|
13
|
+
EXT_BASE: 'https://peopl.health/fhir/StructureDefinition',
|
|
14
|
+
CODESYSTEM_BASE: 'https://peopl.health/fhir/CodeSystem',
|
|
15
|
+
};
|
|
8
16
|
const REQUIRED_KEYS = [
|
|
9
|
-
'IDENT_BASE',
|
|
10
|
-
'EXT_BASE',
|
|
11
|
-
'CODESYSTEM_BASE',
|
|
12
17
|
'SYSTEMS',
|
|
13
18
|
'SUSPECTED_GRADE_DISPLAYS',
|
|
14
19
|
'QUESTIONNAIRE_CANONICAL_URL',
|
|
@@ -18,9 +23,6 @@ const REQUIRED_KEYS = [
|
|
|
18
23
|
];
|
|
19
24
|
|
|
20
25
|
const state = {
|
|
21
|
-
identBase: null,
|
|
22
|
-
extBase: null,
|
|
23
|
-
codesystemBase: null,
|
|
24
26
|
systems: null,
|
|
25
27
|
suspectedGradeDisplays: null,
|
|
26
28
|
questionnaireCanonicalUrl: null,
|
|
@@ -43,9 +45,11 @@ async function initialize() {
|
|
|
43
45
|
const suspectedGradeDisplays = safeParseArray(byKey.SUSPECTED_GRADE_DISPLAYS, null);
|
|
44
46
|
if (!suspectedGradeDisplays) throw new Error('fhir config SUSPECTED_GRADE_DISPLAYS is not a JSON array');
|
|
45
47
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
48
|
+
for (const [key, value] of Object.entries(BASES)) {
|
|
49
|
+
if (byKey[key] && byKey[key] !== value) {
|
|
50
|
+
logger.error('[fhirConfig] Config base value ignored: FHIR identity bases are fixed in code', { key, configured: byKey[key], used: value });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
49
53
|
state.systems = systems;
|
|
50
54
|
state.suspectedGradeDisplays = suspectedGradeDisplays;
|
|
51
55
|
state.questionnaireCanonicalUrl = byKey.QUESTIONNAIRE_CANONICAL_URL;
|
|
@@ -60,9 +64,9 @@ function assertLoaded() {
|
|
|
60
64
|
|
|
61
65
|
module.exports = {
|
|
62
66
|
initialize,
|
|
63
|
-
getIdentBase: () =>
|
|
64
|
-
getExtBase: () =>
|
|
65
|
-
getCodesystemBase: () =>
|
|
67
|
+
getIdentBase: () => BASES.IDENT_BASE,
|
|
68
|
+
getExtBase: () => BASES.EXT_BASE,
|
|
69
|
+
getCodesystemBase: () => BASES.CODESYSTEM_BASE,
|
|
66
70
|
getSystems: () => { assertLoaded(); return state.systems; },
|
|
67
71
|
getSuspectedGradeDisplays: () => { assertLoaded(); return state.suspectedGradeDisplays; },
|
|
68
72
|
getQuestionnaireCanonicalUrl: () => { assertLoaded(); return state.questionnaireCanonicalUrl; },
|
|
@@ -15,7 +15,7 @@ const NO_KNOWN_ALLERGY = {
|
|
|
15
15
|
};
|
|
16
16
|
|
|
17
17
|
const SOURCE_ROLES = {
|
|
18
|
-
specialist: DOCTOR, doctor: DOCTOR, oncologist: DOCTOR, auna: DOCTOR, note: DOCTOR, operator: DOCTOR,
|
|
18
|
+
specialist: DOCTOR, doctor: DOCTOR, oncologist: DOCTOR, auna: DOCTOR, note: DOCTOR, operator: DOCTOR, unit: DOCTOR,
|
|
19
19
|
'legacy-clinician': DOCTOR,
|
|
20
20
|
self: PATIENT, patient: PATIENT, chat: PATIENT,
|
|
21
21
|
'legacy-self': PATIENT,
|
|
@@ -8,9 +8,12 @@ const recordIdIn = (ids) => (ids.length
|
|
|
8
8
|
? `OR(${ids.map((id) => `RECORD_ID()='${escapeFormulaValue(id)}'`).join(',')})`
|
|
9
9
|
: 'FALSE()');
|
|
10
10
|
|
|
11
|
+
const createdBetween = (since, until) => `AND(IS_AFTER(CREATED_TIME(), '${since.toISOString()}'), IS_BEFORE(CREATED_TIME(), '${until.toISOString()}'))`;
|
|
12
|
+
|
|
11
13
|
module.exports = {
|
|
12
14
|
MATCH_ALL,
|
|
13
15
|
escapeFormulaValue,
|
|
14
16
|
fieldEquals,
|
|
15
17
|
recordIdIn,
|
|
18
|
+
createdBetween,
|
|
16
19
|
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
const HOUR_MS = 60 * 60 * 1000;
|
|
2
|
+
|
|
3
|
+
const STATUS = { GREEN: 'green', AMBER: 'amber', RED: 'red', UNKNOWN: 'unknown' };
|
|
4
|
+
// A check that cannot run outranks a warning, so a broken monitor is never hidden behind amber.
|
|
5
|
+
const SEVERITY = { green: 0, amber: 1, unknown: 2, red: 3 };
|
|
6
|
+
|
|
7
|
+
const worst = (...statuses) => statuses.reduce((a, b) => (SEVERITY[b] > SEVERITY[a] ? b : a), STATUS.GREEN);
|
|
8
|
+
|
|
9
|
+
// Display-only: drops JSON bodies, quoted values, URLs and record ids, which is where patient data lives.
|
|
10
|
+
const scrub = (text) => String(text || '').split('{')[0]
|
|
11
|
+
.replace(/https?:\/\/\S+/g, '<url>')
|
|
12
|
+
.replace(/rec[A-Za-z0-9]{14}/g, '<rec>')
|
|
13
|
+
.replace(/"[^"]*"|“[^”]*”/g, '"…"')
|
|
14
|
+
.replace(/\d+/g, '#')
|
|
15
|
+
.replace(/\s+/g, ' ')
|
|
16
|
+
.trim();
|
|
17
|
+
|
|
18
|
+
const signatureOf = (text) => scrub(text).slice(0, 120) || 'sin mensaje';
|
|
19
|
+
|
|
20
|
+
function countBySignature(texts) {
|
|
21
|
+
const counts = new Map();
|
|
22
|
+
for (const text of texts) {
|
|
23
|
+
const key = signatureOf(text);
|
|
24
|
+
counts.set(key, (counts.get(key) || 0) + 1);
|
|
25
|
+
}
|
|
26
|
+
return [...counts.entries()].sort((a, b) => b[1] - a[1]);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const lastDigits = (code) => String(code || '').replace(/\D/g, '').slice(-4) || '????';
|
|
30
|
+
|
|
31
|
+
const hoursAgo = (ms) => `${Math.round(ms / HOUR_MS * 10) / 10} h`;
|
|
32
|
+
|
|
33
|
+
module.exports = {
|
|
34
|
+
STATUS,
|
|
35
|
+
worst,
|
|
36
|
+
signatureOf,
|
|
37
|
+
countBySignature,
|
|
38
|
+
lastDigits,
|
|
39
|
+
hoursAgo,
|
|
40
|
+
};
|
package/lib/index.d.ts
CHANGED
|
@@ -451,6 +451,8 @@ declare module '@peopl-health/nexus' {
|
|
|
451
451
|
ok: boolean;
|
|
452
452
|
facts: ContextSyncResult;
|
|
453
453
|
legacy: ContextSyncResult | null;
|
|
454
|
+
/** The regimen closer's counts, without the per-patient list; null while REGIMEN_CLOSER_WRITE_LIVE is off. */
|
|
455
|
+
closer: Omit<RegimenCloserResult, 'patients'> | null;
|
|
454
456
|
}
|
|
455
457
|
|
|
456
458
|
export function syncContextFacts(options?: ContextSyncOptions): Promise<ContextSyncResult>;
|
|
@@ -573,6 +575,7 @@ declare module '@peopl-health/nexus' {
|
|
|
573
575
|
|
|
574
576
|
export interface RegimenClosure {
|
|
575
577
|
conceptKey: string;
|
|
578
|
+
concept: string | null;
|
|
576
579
|
drug: string;
|
|
577
580
|
status: string | null;
|
|
578
581
|
since: string;
|
|
@@ -582,16 +585,23 @@ declare module '@peopl-health/nexus' {
|
|
|
582
585
|
evidence: { ultimaAplicacion: ChemoContext['ultimaAplicacion']; esquema: string[]; inicioEsquema: ChemoContext['inicioEsquema']; esquemaPrevio: ChemoContext['esquemaPrevio'] };
|
|
583
586
|
}
|
|
584
587
|
|
|
585
|
-
|
|
586
|
-
export function dryRunRegimenClosures(options?: { today?: string }): Promise<{
|
|
588
|
+
export interface RegimenCloserResult {
|
|
587
589
|
ok: boolean;
|
|
588
|
-
dryRun:
|
|
590
|
+
dryRun: boolean;
|
|
589
591
|
closures: number;
|
|
592
|
+
written: number;
|
|
593
|
+
failed: number;
|
|
590
594
|
unreadable: number;
|
|
591
595
|
reason?: string;
|
|
592
596
|
skipped: Record<string, number>;
|
|
593
597
|
patients: Array<{ patientId: string; closures: RegimenClosure[] }>;
|
|
594
|
-
}
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/** Read-only: the injectable antineoplastic slots the chemo unit's current regimen shows as stopped. Writes nothing. */
|
|
601
|
+
export function dryRunRegimenClosures(options?: { today?: string }): Promise<RegimenCloserResult>;
|
|
602
|
+
|
|
603
|
+
/** Writes those closures as `stopped` facts (source `unit`, validTime = end date); a dry run unless `dryRun: false` with a `patientScope`. */
|
|
604
|
+
export function closeStoppedRegimens(options?: { dryRun?: boolean; patientScope?: (patientId: string) => boolean; today?: string }): Promise<RegimenCloserResult>;
|
|
595
605
|
|
|
596
606
|
export const routes: any;
|
|
597
607
|
export function setupDefaultRoutes(app: any): void;
|
|
@@ -1389,6 +1399,8 @@ declare module '@peopl-health/nexus' {
|
|
|
1389
1399
|
predictionTimeMs?: number;
|
|
1390
1400
|
retries?: number;
|
|
1391
1401
|
completed?: boolean;
|
|
1402
|
+
/** Set when the turn never reached the model, e.g. a thread with no preset or prompt. */
|
|
1403
|
+
skipped?: 'no_assistant';
|
|
1392
1404
|
/** Internal delivery ownership receipt; never contains the directive body. */
|
|
1393
1405
|
deliveryDirective?: { operationId: string; claimed: boolean; settled: boolean };
|
|
1394
1406
|
}
|
package/lib/index.js
CHANGED
|
@@ -48,7 +48,7 @@ const { syncLegacyContext } = require('./clinical/services/legacyContextSyncServ
|
|
|
48
48
|
const { syncClinicalContext } = require('./clinical/services/contextSyncRunner');
|
|
49
49
|
const { runProactiveOutreachSweep } = require('./clinical/services/outreachSweepRunner');
|
|
50
50
|
const { currentRegimen } = require('./clinical/services/currentRegimenService');
|
|
51
|
-
const { dryRunRegimenClosures } = require('./clinical/services/regimenCloserService');
|
|
51
|
+
const { closeStoppedRegimens, dryRunRegimenClosures } = require('./clinical/services/regimenCloserService');
|
|
52
52
|
const { readRecordedChemo } = require('./clinical/helpers/clinicalProfileHelper');
|
|
53
53
|
const { registerTool, hasTool, getToolSchemas, clearRegistry } = require('./services/toolRegistryService');
|
|
54
54
|
const { MapCache } = require('./utils/MapCache');
|
|
@@ -364,6 +364,7 @@ module.exports = {
|
|
|
364
364
|
runProactiveOutreachSweep,
|
|
365
365
|
currentRegimen,
|
|
366
366
|
dryRunRegimenClosures,
|
|
367
|
+
closeStoppedRegimens,
|
|
367
368
|
readRecordedChemo,
|
|
368
369
|
syncContextFacts,
|
|
369
370
|
retractContentlessFacts,
|
package/lib/routes/index.js
CHANGED
|
@@ -102,6 +102,10 @@ const dashboardRouteDefinitions = {
|
|
|
102
102
|
'POST /:id': 'updateDashboardControllerById'
|
|
103
103
|
};
|
|
104
104
|
|
|
105
|
+
const healthRouteDefinitions = {
|
|
106
|
+
'GET /summary': 'getHealthSummaryController'
|
|
107
|
+
};
|
|
108
|
+
|
|
105
109
|
const prescriptionRouteDefinitions = {
|
|
106
110
|
'POST /create': 'createPrescriptionController'
|
|
107
111
|
};
|
|
@@ -181,6 +185,7 @@ const templateFlowController = require('../controllers/templateFlowController');
|
|
|
181
185
|
const flowDataExchangeController = require('../controllers/flowDataExchangeController');
|
|
182
186
|
const uploadController = require('../controllers/uploadController');
|
|
183
187
|
const dashboardController = require('../controllers/dashboardController');
|
|
188
|
+
const healthController = require('../controllers/healthController');
|
|
184
189
|
const prescriptionController = require('../controllers/prescriptionController');
|
|
185
190
|
const traceController = require('../controllers/traceController');
|
|
186
191
|
const escalationReviewController = require('../controllers/escalationReviewController');
|
|
@@ -292,6 +297,9 @@ const builtInControllers = {
|
|
|
292
297
|
getDashboardTrendController: dashboardController.getDashboardTrendController,
|
|
293
298
|
updateDashboardControllerById: dashboardController.updateDashboardControllerById,
|
|
294
299
|
|
|
300
|
+
// Health controllers
|
|
301
|
+
getHealthSummaryController: healthController.getHealthSummaryController,
|
|
302
|
+
|
|
295
303
|
// Trace controllers
|
|
296
304
|
getTraceController: traceController.getTraceController,
|
|
297
305
|
|
|
@@ -341,6 +349,7 @@ const setupDefaultRoutes = (app) => {
|
|
|
341
349
|
app.use('/api/template', createRouter(templateRouteDefinitions, builtInControllers));
|
|
342
350
|
app.use('/api/prescription', createRouter(prescriptionRouteDefinitions, builtInControllers));
|
|
343
351
|
app.use('/api/dashboard', createRouter(dashboardRouteDefinitions, builtInControllers));
|
|
352
|
+
app.use('/api/health', createRouter(healthRouteDefinitions, builtInControllers));
|
|
344
353
|
app.use('/api/trace', createRouter(traceRouteDefinitions, builtInControllers));
|
|
345
354
|
app.use('/api/escalation-review', createRouter(escalationReviewRouteDefinitions, builtInControllers));
|
|
346
355
|
app.use('/api/office', createRouter(officeAssistantRouteDefinitions, builtInControllers));
|
|
@@ -360,6 +369,7 @@ module.exports = {
|
|
|
360
369
|
templateRoutes: templateRouteDefinitions,
|
|
361
370
|
prescriptionRoutes: prescriptionRouteDefinitions,
|
|
362
371
|
dashboardRoutes: dashboardRouteDefinitions,
|
|
372
|
+
healthRoutes: healthRouteDefinitions,
|
|
363
373
|
traceRoutes: traceRouteDefinitions,
|
|
364
374
|
escalationReviewRoutes: escalationReviewRouteDefinitions,
|
|
365
375
|
officeAssistantRoutes: officeAssistantRouteDefinitions,
|
|
@@ -21,7 +21,7 @@ const { isNetActive } = require('../shared/dtos/ContingencySafetyNet');
|
|
|
21
21
|
const { identifierValue } = require('../fhir/helpers/fhirReadHelper');
|
|
22
22
|
const { resourceDisplayText } = require('../fhir/helpers/resourceDisplayHelper');
|
|
23
23
|
const { RESULT_SLUG, MENTION_SLUG } = require('../fhir/constants/projectionSlugs');
|
|
24
|
-
const { FIELD_VARIABLES, isRetracted } = require('../clinical/helpers/clinicalContextHelper');
|
|
24
|
+
const { FIELD_VARIABLES, isRetracted, isRecentlyStopped } = require('../clinical/helpers/clinicalContextHelper');
|
|
25
25
|
const { decodePair } = require('../clinical/helpers/encodedPairHelper');
|
|
26
26
|
const { warningRecord } = require('../fhir/projections/recommendationPlanProjection');
|
|
27
27
|
const { getTriageRecommendationEventModel } = require('../clinical/models/triageRecommendationEventModel');
|
|
@@ -281,6 +281,7 @@ const emptyClinicalContext = () => ({
|
|
|
281
281
|
diagnoses: [],
|
|
282
282
|
treatments: [],
|
|
283
283
|
medications: [],
|
|
284
|
+
recentlyStopped: [],
|
|
284
285
|
allergies: [],
|
|
285
286
|
comorbidities: [],
|
|
286
287
|
performanceStatus: [],
|
|
@@ -315,8 +316,9 @@ function projectClinicalContext(contextFacts = [], riskAssessments = [], snapsho
|
|
|
315
316
|
const group = CONTEXT_GROUPS[fact.variableId];
|
|
316
317
|
const inactiveFollowup = group === 'followup' && ['revoked', 'completed'].includes(fact.status);
|
|
317
318
|
if (group && !isRetracted(fact.status) && !inactiveFollowup) context[group].push(projectContextFact(fact));
|
|
319
|
+
if (isRecentlyStopped(fact)) context.recentlyStopped.push(projectContextFact(fact));
|
|
318
320
|
}
|
|
319
|
-
for (const group of new Set(Object.values(CONTEXT_GROUPS))) {
|
|
321
|
+
for (const group of new Set([...Object.values(CONTEXT_GROUPS), 'recentlyStopped'])) {
|
|
320
322
|
context[group].sort((a, b) => Date.parse(b.validAt || b.recordedAt || 0) - Date.parse(a.validAt || a.recordedAt || 0));
|
|
321
323
|
}
|
|
322
324
|
|
|
@@ -10,7 +10,7 @@ const { updatePatientTask } = require('./patientTaskService');
|
|
|
10
10
|
const MIRROR_OPERATOR = 'bot:escalationCase';
|
|
11
11
|
const MIRROR_SOURCE = 'escalation_case';
|
|
12
12
|
|
|
13
|
-
const caseTaskLive = () => String(runtimeConfig.get('ESCALATION_CASE_TASK_LIVE', '
|
|
13
|
+
const caseTaskLive = () => String(runtimeConfig.get('ESCALATION_CASE_TASK_LIVE', 'true')).trim().toLowerCase() !== 'false';
|
|
14
14
|
|
|
15
15
|
function conditionIdsOf(review) {
|
|
16
16
|
const impressed = (review.updates ?? []).flatMap((update) => (update.impressions ?? []).map((impression) => impression.caseId));
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
const { Logging_ID, Symptoms_ID } = require('../config/airtableConfig');
|
|
2
|
+
const { logger } = require('../utils/logger');
|
|
3
|
+
const { mapConcurrent } = require('../utils/concurrencyUtils');
|
|
4
|
+
const { mexicoClock, mexicoWeekStart } = require('../utils/dateUtils');
|
|
5
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
6
|
+
const { createdBetween } = require('../helpers/airtableFormulaHelper');
|
|
7
|
+
const { STATUS, worst, signatureOf, countBySignature, lastDigits, hoursAgo } = require('../helpers/healthHelper');
|
|
8
|
+
const { getTurnTraceModel } = require('../clinical/models/turnTraceModel');
|
|
9
|
+
|
|
10
|
+
const { getRecordByFilter } = require('./airtableService');
|
|
11
|
+
const { stillUnanswered, unansweredThreads, threadIsOwnedByAHuman, silenceWasWavedOff } = require('./inboundRecoveryService');
|
|
12
|
+
|
|
13
|
+
const MINUTE_MS = 60 * 1000;
|
|
14
|
+
const HOUR_MS = 60 * MINUTE_MS;
|
|
15
|
+
const CACHE_TTL_MS = MINUTE_MS;
|
|
16
|
+
const CHECK_TIMEOUT_MS = 10 * 1000;
|
|
17
|
+
|
|
18
|
+
const CREDITS_PATTERN = /no credits|insufficient_quota|exceeded your current quota|credit balance|spend limit|usage limit|billing/i;
|
|
19
|
+
const CREDITS_WINDOW_MS = 24 * HOUR_MS;
|
|
20
|
+
const CREDITS_RED_MS = 6 * HOUR_MS;
|
|
21
|
+
|
|
22
|
+
const BUG_REPORTS_TABLE = 'bug_reports';
|
|
23
|
+
const BUG_REPORTS_LINK = `https://airtable.com/${Logging_ID}/tblnhMcSKQV92tPdp`;
|
|
24
|
+
const SYSTEM_ERRORS = '{server} != \'\', {reporterToGithub} = \'system\', {devServer} = 0';
|
|
25
|
+
|
|
26
|
+
const PATIENTS_TABLE = 'estado_general';
|
|
27
|
+
const QUESTIONNAIRES_TABLE = 'weekly_questionnaires';
|
|
28
|
+
const WEEKLY_VIEW = 'viwEm1YhVDDf8ACQR';
|
|
29
|
+
const WEEKLY_LINK = `https://airtable.com/${Symptoms_ID}/tblUi9KbsefAbrvK2/${WEEKLY_VIEW}`;
|
|
30
|
+
const WEEKLY_TARGET = 0.95;
|
|
31
|
+
|
|
32
|
+
const FAILED_TURN_WINDOW_MS = HOUR_MS;
|
|
33
|
+
const FAILED_PATIENTS_RED = 3;
|
|
34
|
+
const UNANSWERED_MIN_AGE_MS = 30 * MINUTE_MS;
|
|
35
|
+
const UNANSWERED_MAX_AGE_MS = 24 * HOUR_MS;
|
|
36
|
+
const UNANSWERED_LATE_MS = 2 * HOUR_MS;
|
|
37
|
+
const UNANSWERED_RED = 5;
|
|
38
|
+
const UNANSWERED_SCAN_LIMIT = 200;
|
|
39
|
+
const UNANSWERED_CONCURRENCY = 20;
|
|
40
|
+
|
|
41
|
+
const BUG_WINDOW_MS = 24 * HOUR_MS;
|
|
42
|
+
const BUG_SIGNATURE_AMBER = 5;
|
|
43
|
+
const BUG_SIGNATURE_RED = 20;
|
|
44
|
+
const DETAIL_LIMIT = 10;
|
|
45
|
+
|
|
46
|
+
let cached = null;
|
|
47
|
+
let inflight = null;
|
|
48
|
+
|
|
49
|
+
async function checkLlmCredits(now) {
|
|
50
|
+
const since = new Date(now.getTime() - CREDITS_WINDOW_MS);
|
|
51
|
+
const [reports, traces] = await Promise.all([
|
|
52
|
+
getRecordByFilter(Logging_ID, BUG_REPORTS_TABLE, createdBetween(since, now), null, ['description', 'server'], true),
|
|
53
|
+
getTurnTraceModel()
|
|
54
|
+
.find({ shadow: false, createdAt: { $gte: since, $lte: now }, 'abort.message': CREDITS_PATTERN })
|
|
55
|
+
.select({ 'abort.message': 1, createdAt: 1 })
|
|
56
|
+
.lean(),
|
|
57
|
+
]);
|
|
58
|
+
const events = [
|
|
59
|
+
...reports
|
|
60
|
+
.filter((r) => CREDITS_PATTERN.test(String(r.description || '')))
|
|
61
|
+
.map((r) => ({ at: new Date(r._createdTime), text: `${r.server || 'servidor'}: ${r.description}` })),
|
|
62
|
+
...traces
|
|
63
|
+
.filter((t) => CREDITS_PATTERN.test(String(t.abort?.message || '')))
|
|
64
|
+
.map((t) => ({ at: new Date(t.createdAt), text: `agente: ${t.abort?.message}` })),
|
|
65
|
+
];
|
|
66
|
+
const newest = events.reduce((max, e) => (e.at > max ? e.at : max), null);
|
|
67
|
+
const sinceNewestMs = newest ? now.getTime() - newest.getTime() : null;
|
|
68
|
+
|
|
69
|
+
let status = STATUS.GREEN;
|
|
70
|
+
if (newest && sinceNewestMs <= CREDITS_RED_MS) status = STATUS.RED;
|
|
71
|
+
else if (newest) status = STATUS.AMBER;
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
check: 'H1',
|
|
75
|
+
key: 'llm_credits',
|
|
76
|
+
label: 'Saldo de los proveedores de IA',
|
|
77
|
+
status,
|
|
78
|
+
value: events.length,
|
|
79
|
+
threshold: 'un error de saldo o cuota en las últimas 6 h (rojo) o 24 h (ámbar)',
|
|
80
|
+
summary: newest
|
|
81
|
+
? `${events.length} errores de saldo o cuota en 24 h · el último hace ${hoursAgo(sinceNewestMs)}`
|
|
82
|
+
: 'Sin errores de saldo en las últimas 24 h',
|
|
83
|
+
detail: countBySignature(events.map((e) => e.text)).slice(0, DETAIL_LIMIT).map(([sig, n]) => `${n} × ${sig}`),
|
|
84
|
+
link: BUG_REPORTS_LINK,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function checkWeeklyCoverage(now) {
|
|
89
|
+
const weekStart = mexicoWeekStart(now);
|
|
90
|
+
const [patients, weeklies] = await Promise.all([
|
|
91
|
+
getRecordByFilter(Symptoms_ID, PATIENTS_TABLE, '{tipo} = \'prod\'', WEEKLY_VIEW, ['whatsapp_id', 'first_triage_date_received'], true),
|
|
92
|
+
getRecordByFilter(Symptoms_ID, QUESTIONNAIRES_TABLE, `AND({type_quest} = 'weekly', ${createdBetween(weekStart, now)})`, null, ['patient_id']),
|
|
93
|
+
]);
|
|
94
|
+
const covered = new Set(weeklies.flatMap((q) => q.patient_id || []));
|
|
95
|
+
// A patient whose first triage landed this week is not due a weekly until next Sunday.
|
|
96
|
+
const expected = patients.filter((p) => !(p.first_triage_date_received && new Date(p.first_triage_date_received) >= weekStart));
|
|
97
|
+
const base = {
|
|
98
|
+
check: 'H2',
|
|
99
|
+
key: 'weekly_coverage',
|
|
100
|
+
label: 'Cobertura del cuestionario semanal',
|
|
101
|
+
threshold: `<${WEEKLY_TARGET * 100}% (rojo el domingo desde las 06:00 y el lunes, MX)`,
|
|
102
|
+
link: WEEKLY_LINK,
|
|
103
|
+
};
|
|
104
|
+
if (!expected.length) {
|
|
105
|
+
return { ...base, status: STATUS.UNKNOWN, value: null, summary: 'La vista no devolvió pacientes', detail: [] };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const missing = expected.filter((p) => !covered.has(p._recordId));
|
|
109
|
+
const ratio = (expected.length - missing.length) / expected.length;
|
|
110
|
+
const { weekday, hour } = mexicoClock(now);
|
|
111
|
+
const isEnforced = (weekday === 0 && hour >= 6) || weekday === 1;
|
|
112
|
+
|
|
113
|
+
let status = STATUS.GREEN;
|
|
114
|
+
if (ratio < WEEKLY_TARGET) status = isEnforced ? STATUS.RED : STATUS.AMBER;
|
|
115
|
+
|
|
116
|
+
return {
|
|
117
|
+
...base,
|
|
118
|
+
status,
|
|
119
|
+
value: Math.round(ratio * 100),
|
|
120
|
+
summary: `${expected.length - missing.length} de ${expected.length} pacientes con weekly esta semana`,
|
|
121
|
+
detail: missing.slice(0, DETAIL_LIMIT * 3).map((p) => `Sin weekly: …${lastDigits(p.whatsapp_id)}`),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function unansweredPatients(now) {
|
|
126
|
+
const threads = await unansweredThreads(now, {
|
|
127
|
+
minAgeMs: UNANSWERED_MIN_AGE_MS, maxAgeMs: UNANSWERED_MAX_AGE_MS, limit: UNANSWERED_SCAN_LIMIT,
|
|
128
|
+
});
|
|
129
|
+
const waiting = [];
|
|
130
|
+
await mapConcurrent(threads, UNANSWERED_CONCURRENCY, async ({ code }) => {
|
|
131
|
+
const newest = await stillUnanswered(code, now, { minAgeMs: UNANSWERED_MIN_AGE_MS, maxAgeMs: UNANSWERED_MAX_AGE_MS });
|
|
132
|
+
if (!newest) return;
|
|
133
|
+
if (await threadIsOwnedByAHuman(code)) return;
|
|
134
|
+
if (await silenceWasWavedOff(code, newest.createdAt)) return;
|
|
135
|
+
waiting.push({ code, ageMs: now.getTime() - new Date(newest.createdAt).getTime() });
|
|
136
|
+
});
|
|
137
|
+
return waiting.sort((a, b) => b.ageMs - a.ageMs);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function checkUnansweredMessages(now) {
|
|
141
|
+
const since = new Date(now.getTime() - FAILED_TURN_WINDOW_MS);
|
|
142
|
+
const [failed, waiting] = await Promise.all([
|
|
143
|
+
getTurnTraceModel()
|
|
144
|
+
.find({ shadow: false, status: 'failed', createdAt: { $gte: since, $lte: now } })
|
|
145
|
+
.select({ 'abort.message': 1, patientCode: 1 })
|
|
146
|
+
.lean(),
|
|
147
|
+
unansweredPatients(now),
|
|
148
|
+
]);
|
|
149
|
+
const patientsBySignature = new Map();
|
|
150
|
+
for (const t of failed) {
|
|
151
|
+
const sig = signatureOf(t.abort?.message);
|
|
152
|
+
if (!patientsBySignature.has(sig)) patientsBySignature.set(sig, new Set());
|
|
153
|
+
patientsBySignature.get(sig).add(t.patientCode);
|
|
154
|
+
}
|
|
155
|
+
const signatures = countBySignature(failed.map((t) => t.abort?.message));
|
|
156
|
+
const isWidespread = [...patientsBySignature.values()].some((codes) => codes.size >= FAILED_PATIENTS_RED);
|
|
157
|
+
const late = waiting.filter((w) => w.ageMs >= UNANSWERED_LATE_MS);
|
|
158
|
+
|
|
159
|
+
let failedStatus = STATUS.GREEN;
|
|
160
|
+
if (isWidespread) failedStatus = STATUS.RED;
|
|
161
|
+
else if (failed.length) failedStatus = STATUS.AMBER;
|
|
162
|
+
let lateStatus = STATUS.GREEN;
|
|
163
|
+
if (late.length >= UNANSWERED_RED) lateStatus = STATUS.RED;
|
|
164
|
+
else if (late.length) lateStatus = STATUS.AMBER;
|
|
165
|
+
|
|
166
|
+
return {
|
|
167
|
+
check: 'H5',
|
|
168
|
+
key: 'unanswered_messages',
|
|
169
|
+
label: 'Pacientes sin respuesta',
|
|
170
|
+
status: worst(failedStatus, lateStatus),
|
|
171
|
+
value: late.length,
|
|
172
|
+
threshold: `≥1 sin respuesta >2 h (ámbar), ≥${UNANSWERED_RED} (rojo); la misma falla del agente en ≥${FAILED_PATIENTS_RED} pacientes en 1 h (rojo)`,
|
|
173
|
+
summary: `${late.length} sin respuesta hace más de 2 h · ${failed.length} turnos del agente fallidos en 1 h`,
|
|
174
|
+
detail: [
|
|
175
|
+
...signatures.slice(0, 3).map(([sig, n]) => `Agente: ${n} × ${sig} (${patientsBySignature.get(sig)?.size || 0} pacientes)`),
|
|
176
|
+
...late.slice(0, DETAIL_LIMIT).map((w) => `…${lastDigits(w.code)} lleva ${hoursAgo(w.ageMs)} sin respuesta`),
|
|
177
|
+
],
|
|
178
|
+
link: null,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function checkNewErrors(now) {
|
|
183
|
+
const since = new Date(now.getTime() - BUG_WINDOW_MS);
|
|
184
|
+
const rows = await getRecordByFilter(
|
|
185
|
+
Logging_ID, BUG_REPORTS_TABLE, `AND(${createdBetween(since, now)}, ${SYSTEM_ERRORS})`, null, ['description', 'server'],
|
|
186
|
+
);
|
|
187
|
+
const signatures = countBySignature(rows.map((r) => `${r.server}: ${r.description}`));
|
|
188
|
+
const top = signatures[0]?.[1] || 0;
|
|
189
|
+
|
|
190
|
+
let status = STATUS.GREEN;
|
|
191
|
+
if (top >= BUG_SIGNATURE_RED) status = STATUS.RED;
|
|
192
|
+
else if (top >= BUG_SIGNATURE_AMBER) status = STATUS.AMBER;
|
|
193
|
+
|
|
194
|
+
return {
|
|
195
|
+
check: 'H10',
|
|
196
|
+
key: 'new_errors',
|
|
197
|
+
label: 'Errores automáticos de servidor',
|
|
198
|
+
status,
|
|
199
|
+
value: rows.length,
|
|
200
|
+
threshold: `una misma falla ≥${BUG_SIGNATURE_AMBER} (ámbar) o ≥${BUG_SIGNATURE_RED} (rojo) en 24 h`,
|
|
201
|
+
summary: `${rows.length} errores de servidor en 24 h, ${signatures.length} distintos`,
|
|
202
|
+
detail: signatures.slice(0, 3).map(([sig, n]) => `${n} × ${sig}`),
|
|
203
|
+
link: BUG_REPORTS_LINK,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const CHECKS = [
|
|
208
|
+
{ check: 'H1', key: 'llm_credits', label: 'Saldo de los proveedores de IA', run: checkLlmCredits },
|
|
209
|
+
{ check: 'H2', key: 'weekly_coverage', label: 'Cobertura del cuestionario semanal', run: checkWeeklyCoverage },
|
|
210
|
+
{ check: 'H5', key: 'unanswered_messages', label: 'Pacientes sin respuesta', run: checkUnansweredMessages },
|
|
211
|
+
{ check: 'H10', key: 'new_errors', label: 'Errores automáticos de servidor', run: checkNewErrors },
|
|
212
|
+
];
|
|
213
|
+
|
|
214
|
+
// H2 and H5 read current state, so only H1 and H10 can be evaluated at a past `now`.
|
|
215
|
+
async function computeHealthSummary(now = new Date()) {
|
|
216
|
+
const computedAt = now.toISOString();
|
|
217
|
+
const settled = await Promise.allSettled(CHECKS.map(({ check, run }) => withTimeout(Promise.resolve().then(() => run(now)), CHECK_TIMEOUT_MS, check)));
|
|
218
|
+
const checks = settled.map((result, i) => {
|
|
219
|
+
if (result.status === 'fulfilled') return { ...result.value, computedAt };
|
|
220
|
+
const { check, key, label } = CHECKS[i];
|
|
221
|
+
logger.warn('[HealthService] check failed', { check, error: result.reason?.message });
|
|
222
|
+
return { check, key, label, status: STATUS.UNKNOWN, value: null, threshold: null, summary: 'No se pudo calcular', detail: [], link: null, computedAt };
|
|
223
|
+
});
|
|
224
|
+
return { computedAt, status: worst(...checks.map((c) => c.status)), checks };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async function getHealthSummary({ force = false, now = new Date() } = {}) {
|
|
228
|
+
if (!force && cached && now.getTime() - cached.at < CACHE_TTL_MS) return cached.summary;
|
|
229
|
+
if (inflight) return inflight;
|
|
230
|
+
inflight = computeHealthSummary(now)
|
|
231
|
+
.then((summary) => {
|
|
232
|
+
cached = { at: now.getTime(), summary };
|
|
233
|
+
return summary;
|
|
234
|
+
})
|
|
235
|
+
.finally(() => { inflight = null; });
|
|
236
|
+
return inflight;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const _resetHealthCache = () => { cached = null; inflight = null; };
|
|
240
|
+
|
|
241
|
+
module.exports = {
|
|
242
|
+
getHealthSummary,
|
|
243
|
+
computeHealthSummary,
|
|
244
|
+
checkLlmCredits,
|
|
245
|
+
checkWeeklyCoverage,
|
|
246
|
+
checkUnansweredMessages,
|
|
247
|
+
checkNewErrors,
|
|
248
|
+
_resetHealthCache,
|
|
249
|
+
};
|
package/lib/utils/dateUtils.js
CHANGED
|
@@ -68,6 +68,17 @@ const daysSince = (from, now = Date.now()) => {
|
|
|
68
68
|
return Number.isNaN(at) ? null : Math.max(0, Math.floor((now - at) / 86400000));
|
|
69
69
|
};
|
|
70
70
|
|
|
71
|
+
const mexicoClock = (at) => {
|
|
72
|
+
const mx = moment.tz(at, MEXICO_TZ);
|
|
73
|
+
return { weekday: mx.day(), hour: mx.hour() };
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
// Sunday 00:00 in Mexico City; day() ignores the locale's first day of the week.
|
|
77
|
+
const mexicoWeekStart = (at) => {
|
|
78
|
+
const mx = moment.tz(at, MEXICO_TZ).startOf('day');
|
|
79
|
+
return mx.subtract(mx.day(), 'days').toDate();
|
|
80
|
+
};
|
|
81
|
+
|
|
71
82
|
const MAX_WORKING_DAY_STEPS = 400;
|
|
72
83
|
|
|
73
84
|
const addWorkingMinutes = (start, minutes, { timeZone, days, startHour, endHour }) => {
|
|
@@ -100,7 +111,9 @@ module.exports = {
|
|
|
100
111
|
isoDay,
|
|
101
112
|
daysBetween,
|
|
102
113
|
mexicoDay,
|
|
114
|
+
mexicoClock,
|
|
103
115
|
mexicoIsoWeek,
|
|
116
|
+
mexicoWeekStart,
|
|
104
117
|
mexicoStamp,
|
|
105
118
|
daysSince
|
|
106
119
|
};
|