@peopl-health/nexus 5.51.0-dev.7632 → 5.51.0-dev.7633
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/README.md +0 -21
- package/lib/clinical/AssistantProcessor.js +12 -156
- package/lib/clinical/context/ToolRuntimeContext.js +1 -39
- package/lib/clinical/context/turnContext.js +0 -10
- package/lib/clinical/models/triageRecommendationEventModel.js +0 -28
- package/lib/clinical/providers/BaseLLMProvider.js +5 -45
- package/lib/clinical/services/clinicalAirtableService.js +5 -8
- package/lib/clinical/services/divergenceService.js +2 -9
- package/lib/clinical/services/triageRecommendationService.js +251 -453
- package/lib/clinical/tools/deliverPatientMessageTool.js +23 -82
- package/lib/clinical/tools/registerClinicalTools.js +0 -2
- package/lib/controllers/dashboardController.js +2 -5
- package/lib/controllers/escalationReviewController.js +12 -0
- package/lib/core/BatchingManager.js +9 -20
- package/lib/core/NexusMessaging.js +6 -25
- package/lib/core/ProcessingPipeline.js +3 -32
- package/lib/index.d.ts +6 -334
- package/lib/index.js +0 -22
- package/lib/models/escalationReviewModel.js +4 -0
- package/lib/routes/index.js +2 -0
- package/lib/services/airtableService.js +1 -8
- package/lib/services/dashboardService.js +3 -30
- package/lib/services/escalationReviewService.js +43 -11
- package/package.json +1 -1
- package/lib/clinical/models/supportCandidateModel.js +0 -90
- package/lib/clinical/services/deliverySettlementService.js +0 -39
- package/lib/clinical/services/supportActionService.js +0 -129
- package/lib/clinical/services/supportCandidateService.js +0 -532
- package/lib/clinical/services/supportRoutingAgentService.js +0 -118
- package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +0 -200
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +0 -142
- package/lib/core/runtimeToolPolicy.js +0 -3
- package/lib/services/dashboard-provider-registry.js +0 -38
- package/lib/shared/dtos/NutritionSafetyDecision.js +0 -128
- package/lib/shared/dtos/SupportAction.js +0 -28
- package/lib/shared/dtos/SupportRoutingRecommendation.js +0 -124
|
@@ -2,7 +2,6 @@ const { getTriageGate, getTriagePlan } = require('../config/subAgentsConfig');
|
|
|
2
2
|
const { getSafetyFlagPatterns, getRedFlagMinRoutes } = require('../config/divergenceConfig');
|
|
3
3
|
const { requireGatewayProvider } = require('../config/llmConfig');
|
|
4
4
|
const { getTriageRecommendationEventModel } = require('../models/triageRecommendationEventModel');
|
|
5
|
-
const { getSupportCandidateModel } = require('../models/supportCandidateModel');
|
|
6
5
|
const { isShadowRun } = require('../helpers/shadowHelper');
|
|
7
6
|
const { readOutputText } = require('../helpers/clinicalMentionHelper');
|
|
8
7
|
const {
|
|
@@ -60,9 +59,6 @@ const { validate, blockingIssues, urgentGateIssues } = require('./recommendation
|
|
|
60
59
|
const { escalationLookbackSince } = require('./turnRiskBriefService');
|
|
61
60
|
const { applyRankOrder, buildRankContext, buildSymptomSignals } = require('./recommendationRankService');
|
|
62
61
|
const { recordClusterRecommendationsMirror } = require('./clinicalAirtableService');
|
|
63
|
-
const { evaluateSupportRouting } = require('./supportRoutingAgentService');
|
|
64
|
-
const { recordSupportRoutingRecommendation, settleInvitation, updateSupportOperationalReview } = require('./supportCandidateService');
|
|
65
|
-
const { prepareSupportAction } = require('./supportActionService');
|
|
66
62
|
|
|
67
63
|
const GENERATION_BACKOFF_MS = 10 * 60 * 1000;
|
|
68
64
|
const GATE_MAX_ATTEMPTS = 2;
|
|
@@ -74,7 +70,7 @@ const PATIENT_LOOKUP_FIELD = 'patient_id (from triaje_symptoms) (from cluster_re
|
|
|
74
70
|
const generationState = new MapCache({ maxSize: 2000, ttl: GENERATION_BACKOFF_MS });
|
|
75
71
|
const FREE_TEXT_SYMPTOM_FIELDS = ['freetext_derived', 'corresponding_CTCAE', 'grade_num'];
|
|
76
72
|
|
|
77
|
-
function handleTriageCompleted(rawPayload, { trigger = 'auna', runId = null
|
|
73
|
+
function handleTriageCompleted(rawPayload, { trigger = 'auna', runId = null } = {}) {
|
|
78
74
|
let payload;
|
|
79
75
|
try {
|
|
80
76
|
payload = new TriageCompletion(rawPayload);
|
|
@@ -117,15 +113,12 @@ function handleTriageCompleted(rawPayload, { trigger = 'auna', runId = null, sup
|
|
|
117
113
|
generationState.set(payload.triageRecordId, true);
|
|
118
114
|
const startedAt = Date.now();
|
|
119
115
|
Promise.resolve()
|
|
120
|
-
.then(() => generateTriageRecommendations({ payload, provider: requireGatewayProvider(), runId
|
|
116
|
+
.then(() => generateTriageRecommendations({ payload, provider: requireGatewayProvider(), runId }))
|
|
121
117
|
.then((settle) => {
|
|
122
118
|
logger.info('[triageRecommendation] settled', { code: payload.patientCode, triageRecordId: payload.triageRecordId, status: settle.status, reason: settle.reason });
|
|
123
119
|
// A failed run releases the claim so a deliberate redelivery can retry
|
|
124
120
|
// immediately; success keeps it for the dedupe window.
|
|
125
|
-
if (settle.status === 'failed'
|
|
126
|
-
|| settle.supportPendingCandidateIds?.length) {
|
|
127
|
-
generationState.delete(payload.triageRecordId);
|
|
128
|
-
}
|
|
121
|
+
if (settle.status === 'failed') generationState.delete(payload.triageRecordId);
|
|
129
122
|
return recordSettleEvent({ payload, trigger, totalLatencyMs: Date.now() - startedAt, ...settle });
|
|
130
123
|
})
|
|
131
124
|
.catch((err) => {
|
|
@@ -166,459 +159,258 @@ async function recordSettleEvent({ payload, trigger, totalLatencyMs, ...settle }
|
|
|
166
159
|
}
|
|
167
160
|
}
|
|
168
161
|
|
|
169
|
-
async function generateTriageRecommendations({ payload, provider, runId = null
|
|
162
|
+
async function generateTriageRecommendations({ payload, provider, runId = null }) {
|
|
170
163
|
const rid = runId || defaultRunId(payload);
|
|
171
164
|
const code = payload.patientCode;
|
|
172
165
|
const settle = { runId: rid };
|
|
173
166
|
|
|
167
|
+
const [{ presetId: gatePresetId }, { presetId: planPresetId }] = await Promise.all([getTriageGate(), getTriagePlan()]);
|
|
168
|
+
if (!gatePresetId || !planPresetId || typeof provider?.runStructured !== 'function') {
|
|
169
|
+
return { ...settle, status: 'failed', stage: 'assemble', reason: 'preset_unavailable' };
|
|
170
|
+
}
|
|
171
|
+
settle.methodVersion = `${gatePresetId}+${planPresetId}`;
|
|
172
|
+
|
|
173
|
+
if (await recommendationPlanExists({ runId: rid })) {
|
|
174
|
+
const pending = await pendingMirrorPayload(rid);
|
|
175
|
+
if (!pending) return { ...settle, status: 'skipped_duplicate', reason: 'already_generated' };
|
|
176
|
+
settle.mirrorAttempted = true;
|
|
177
|
+
const mirror = await recordClusterRecommendationsMirror({ code, ...pending });
|
|
178
|
+
settle.mirrorOk = mirror.ok;
|
|
179
|
+
settle.mirrorRecordId = mirror.recordId;
|
|
180
|
+
if (!mirror.ok) {
|
|
181
|
+
settle.mirrorError = 'write_failed';
|
|
182
|
+
settle.mirrorPayload = pending;
|
|
183
|
+
return { ...settle, status: 'failed', stage: 'mirror', reason: 'mirror_failed' };
|
|
184
|
+
}
|
|
185
|
+
return { ...settle, status: 'success', reason: 'mirror_repaired' };
|
|
186
|
+
}
|
|
187
|
+
|
|
174
188
|
const classifier = await readFreeTextDerivedSymptoms(payload.triageRecordId, code);
|
|
175
189
|
if (classifier === null) {
|
|
176
190
|
return { ...settle, status: 'failed', stage: 'assemble', reason: 'triage_patient_mismatch' };
|
|
177
191
|
}
|
|
178
192
|
const freeTextDerivedSymptoms = classifier.terms;
|
|
179
193
|
settle.classifierPending = classifier.pending;
|
|
194
|
+
|
|
180
195
|
const catalog = getCatalog();
|
|
181
196
|
const { triageResponse, unmappedQuestionIds } = buildTriageResponse(catalog, payload);
|
|
182
197
|
settle.unmappedAnswerCount = unmappedQuestionIds.length;
|
|
183
198
|
|
|
184
|
-
let
|
|
185
|
-
let supportPromise;
|
|
186
|
-
let existingClinicalMirrorId = null;
|
|
187
|
-
const startSupport = () => {
|
|
188
|
-
if (!supportPromise) {
|
|
189
|
-
supportPromise = settleSupportRouting({ payload, provider, supportRouting, context: supportContext, runId: rid });
|
|
190
|
-
}
|
|
191
|
-
return supportPromise;
|
|
192
|
-
};
|
|
193
|
-
const finish = async (result, clinicalMirror = null) => {
|
|
194
|
-
const support = await startSupport();
|
|
195
|
-
Object.assign(settle, support.audit);
|
|
196
|
-
const priorSupport = support.previous;
|
|
197
|
-
const mirroredActions = [...(priorSupport?.supportMirroredActions
|
|
198
|
-
|| (priorSupport?.supportActionMirrored ? priorSupport.supportAction?.actions || [] : []))]
|
|
199
|
-
.map(({ candidateId, type }) => ({ candidateId, type }));
|
|
200
|
-
const mirroredGroupIds = mirroredActions.filter((item) => item.type === 'group_registration').map((item) => item.candidateId);
|
|
201
|
-
if (support.ok) {
|
|
202
|
-
settle.supportMirroredActions = mirroredActions;
|
|
203
|
-
settle.supportPendingCandidateIds = priorSupport?.supportPendingCandidateIds
|
|
204
|
-
|| support.audit.supportDeliveryCandidateIds.filter((id) => !mirroredGroupIds.includes(id));
|
|
205
|
-
settle.supportMirrorRecordIds = [...(priorSupport?.supportMirrorRecordIds || [])];
|
|
206
|
-
}
|
|
207
|
-
if (priorSupport?.supportAction) settle.supportAction = priorSupport.supportAction;
|
|
208
|
-
if (priorSupport?.supportActionMirrored) settle.supportActionMirrored = true;
|
|
209
|
-
if (priorSupport?.supportActionMirrorUnknown) settle.supportActionMirrorUnknown = true;
|
|
210
|
-
if (priorSupport?.supportPendingSettlements?.length) {
|
|
211
|
-
const recovery = await settleSupportClaims(priorSupport.supportPendingSettlements);
|
|
212
|
-
Object.assign(settle, recovery);
|
|
213
|
-
if (recovery.supportPendingSettlements.length) {
|
|
214
|
-
return { ...settle, status: 'failed', stage: 'support', reason: 'support_settlement_failed',
|
|
215
|
-
mirrorAttempted: true, mirrorOk: false, mirrorPayload: clinicalMirror || priorSupport.mirrorPayload,
|
|
216
|
-
mirrorError: 'support_settlement_failed' };
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
if (settle.supportActionMirrorUnknown) {
|
|
220
|
-
if (clinicalMirror) {
|
|
221
|
-
return { ...settle, status: 'failed', stage: 'mirror', reason: 'mirror_failed', mirrorAttempted: true,
|
|
222
|
-
mirrorOk: false, mirrorPayload: clinicalMirror, mirrorError: 'support_mirror_outcome_unknown' };
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
let action = null;
|
|
226
|
-
let candidates = null;
|
|
227
|
-
if (support.ok) {
|
|
228
|
-
try {
|
|
229
|
-
candidates = priorSupport
|
|
230
|
-
? await getSupportCandidateModel().find({ patientId: code, latestSourceId: payload.triageRecordId, candidateId: { $in: settle.supportPendingCandidateIds } }).lean()
|
|
231
|
-
: support.candidates;
|
|
232
|
-
if (settle.urgentUnder24h !== true) {
|
|
233
|
-
for (const candidate of candidates) await updateSupportOperationalReview({
|
|
234
|
-
patientId: code, service: candidate.service, sourceId: payload.triageRecordId,
|
|
235
|
-
reasonCode: 'safety_unconfirmed', resolved: settle.supportSafetyCleared === true,
|
|
236
|
-
});
|
|
237
|
-
}
|
|
238
|
-
} catch (error) {
|
|
239
|
-
settle.supportReviewError = error?.message || 'support review persistence failed';
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
if (support.ok && candidates && settle.supportPendingCandidateIds.length && !settle.supportActionMirrorUnknown
|
|
243
|
-
&& supportRouting.autoEligible === true && settle.supportSafetyCleared === true) {
|
|
244
|
-
try {
|
|
245
|
-
const remaining = remainingSupportCandidates(candidates, mirroredActions);
|
|
246
|
-
settle.supportPendingCandidateIds = remaining.map((candidate) => candidate.candidateId);
|
|
247
|
-
action = await prepareSupportAction({
|
|
248
|
-
patientId: code,
|
|
249
|
-
sourceId: payload.triageRecordId,
|
|
250
|
-
candidates: remaining,
|
|
251
|
-
resolveDeliveryContext: supportRouting.resolveDeliveryContext,
|
|
252
|
-
});
|
|
253
|
-
} catch (err) {
|
|
254
|
-
settle.supportActionError = err?.message || 'unknown';
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
if (action) settle.supportAction = action;
|
|
258
|
-
const pendingAction = action;
|
|
259
|
-
const mirrorPayload = clinicalMirror ? { ...clinicalMirror } : pendingAction ? {
|
|
260
|
-
triageRecordId: payload.triageRecordId,
|
|
261
|
-
step2: {},
|
|
262
|
-
step3: { step3_careplan: { recommendations: [] } },
|
|
263
|
-
} : null;
|
|
264
|
-
if (mirrorPayload) {
|
|
265
|
-
const completedMirrorIds = [...new Set([
|
|
266
|
-
...(settle.supportMirrorRecordIds || []), ...(mirrorPayload.excludeRecordIds || []),
|
|
267
|
-
existingClinicalMirrorId, mirrorPayload.excludeRecordId,
|
|
268
|
-
].filter(Boolean))];
|
|
269
|
-
if (completedMirrorIds.length) mirrorPayload.excludeRecordIds = completedMirrorIds;
|
|
270
|
-
if (support.ok) settle.supportMirrorRecordIds = completedMirrorIds;
|
|
271
|
-
delete mirrorPayload.supportAction;
|
|
272
|
-
if (pendingAction) mirrorPayload.supportAction = pendingAction;
|
|
273
|
-
settle.mirrorAttempted = true;
|
|
274
|
-
const mirror = await recordClusterRecommendationsMirror({ code, ...mirrorPayload });
|
|
275
|
-
settle.mirrorOk = mirror.ok;
|
|
276
|
-
settle.mirrorRecordId = mirror.recordId;
|
|
277
|
-
if (mirror.ok && support.ok && mirror.recordId) settle.supportMirrorRecordIds.push(mirror.recordId);
|
|
278
|
-
if (mirror.ok && pendingAction) {
|
|
279
|
-
mirroredActions.push(...pendingAction.actions.map(({ candidateId, type }) => ({ candidateId, type })));
|
|
280
|
-
settle.supportPendingCandidateIds = remainingSupportCandidates(candidates, mirroredActions).map((candidate) => candidate.candidateId);
|
|
281
|
-
}
|
|
282
|
-
if (!mirror.ok) {
|
|
283
|
-
settle.mirrorError = 'write_failed';
|
|
284
|
-
settle.mirrorPayload = mirrorPayload;
|
|
285
|
-
if (pendingAction) {
|
|
286
|
-
settle.supportActionMirrorUnknown = mirror.confirmedAbsent !== true;
|
|
287
|
-
const requests = pendingAction.actions.filter((entry) => entry.type === 'group_registration').map((item) => ({
|
|
288
|
-
candidateId: item.candidateId,
|
|
289
|
-
idempotencyKey: item.idempotencyKey,
|
|
290
|
-
status: mirror.confirmedAbsent ? 'failed' : 'unknown',
|
|
291
|
-
error: mirror.confirmedAbsent ? 'support_mirror_failed' : 'support_mirror_outcome_unknown',
|
|
292
|
-
}));
|
|
293
|
-
Object.assign(settle, await settleSupportClaims(requests));
|
|
294
|
-
}
|
|
295
|
-
if (clinicalMirror || result.status !== 'failed') result = { status: 'failed', stage: 'mirror', reason: 'mirror_failed' };
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
if (support.ok) settle.supportActionMirrored = mirroredActions.length > 0 && settle.supportPendingCandidateIds.length === 0;
|
|
299
|
-
return { ...settle, ...result };
|
|
300
|
-
};
|
|
301
|
-
|
|
199
|
+
let graded = [];
|
|
302
200
|
try {
|
|
303
|
-
const
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
if (await recommendationPlanExists({ runId: rid })) {
|
|
310
|
-
const pending = await pendingMirrorPayload(rid);
|
|
311
|
-
if (supportRouting.enabled === true) {
|
|
312
|
-
const previous = await getTriageRecommendationEventModel()
|
|
313
|
-
.findOne({ runId: rid }).sort({ createdAt: -1 }).lean();
|
|
314
|
-
settle.supportSafetyCleared = previous?.supportSafetyCleared === true;
|
|
315
|
-
const previousMirror = await getTriageRecommendationEventModel()
|
|
316
|
-
.findOne({ runId: rid, mirrorAttempted: true }).sort({ createdAt: -1 }).lean();
|
|
317
|
-
if (previousMirror?.mirrorOk) existingClinicalMirrorId = previousMirror.mirrorRecordId;
|
|
318
|
-
}
|
|
319
|
-
if (!pending) return finish({ status: 'skipped_duplicate', reason: 'already_generated' });
|
|
320
|
-
return finish({ status: 'success', reason: 'mirror_repaired' }, pending);
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
let graded = [];
|
|
201
|
+
const storedTriage = await storeTriage(triageResponse);
|
|
202
|
+
graded = storedTriage.graded;
|
|
203
|
+
settle.triageStored = true;
|
|
204
|
+
} catch (err) {
|
|
205
|
+
logger.warn('[triageRecommendation] storeTriage failed; grading in-memory', { code, triageRecordId: payload.triageRecordId, error: err?.message });
|
|
206
|
+
settle.triageStored = false;
|
|
324
207
|
try {
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
logger.warn('[triageRecommendation] storeTriage failed; grading in-memory', { code, triageRecordId: payload.triageRecordId, error: err?.message });
|
|
330
|
-
settle.triageStored = false;
|
|
331
|
-
try {
|
|
332
|
-
graded = gradeComposites(catalog, new TriageResponse(triageResponse));
|
|
333
|
-
} catch (gradeErr) {
|
|
334
|
-
logger.warn('[triageRecommendation] grading failed', { code, error: gradeErr?.message });
|
|
335
|
-
return finish({ status: 'failed', stage: 'assemble', reason: 'grading_failed' });
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
const answeredTermList = askedTermsOf(catalog, triageResponse.answers);
|
|
339
|
-
const sentinels = sentinelTermsOf(catalog, triageResponse.answers);
|
|
340
|
-
const gradedTerms = new Set(graded.map((symptom) => symptom.term));
|
|
341
|
-
settle.droppedComboCount = answeredTermList.filter((term) => !gradedTerms.has(term)).length;
|
|
342
|
-
const sentinelTerms = new Set([...sentinels.notApplicable, ...sentinels.declined]);
|
|
343
|
-
const ungradedTerms = answeredTermList.filter((term) => !gradedTerms.has(term) && !sentinelTerms.has(term));
|
|
344
|
-
// Pain is answered in its own block, so it never appears in answeredTermList.
|
|
345
|
-
if (affirmative(triageResponse.pain?.hasPain) && !gradedTerms.has(PAIN_TERM)) ungradedTerms.push(PAIN_TERM);
|
|
346
|
-
|
|
347
|
-
const adherenceEntries = payload.adherence.filter(Boolean);
|
|
348
|
-
const priorResolutions = await readPriorResolutions(adherenceEntries, payload.patientRecordId);
|
|
349
|
-
const adherenceCounts = await recordTriageAdherence({
|
|
350
|
-
code, entries: adherenceEntries, patientRecordId: payload.patientRecordId, priorResolutions, eventKey: payload.triageRecordId,
|
|
351
|
-
});
|
|
352
|
-
settle.adherenceRecorded = adherenceCounts.recorded;
|
|
353
|
-
settle.adherenceSkipped = adherenceCounts.skipped;
|
|
354
|
-
settle.adherenceNoTask = adherenceCounts.noTask;
|
|
355
|
-
settle.adherenceUnresolved = adherenceCounts.unresolved;
|
|
356
|
-
settle.adherenceUnverified = adherenceCounts.unverified;
|
|
357
|
-
settle.adherenceFailed = adherenceCounts.failed;
|
|
358
|
-
settle.adherenceDuplicate = adherenceCounts.duplicate;
|
|
359
|
-
settle.adherenceMalformed = payload.adherence.length - adherenceEntries.length;
|
|
360
|
-
|
|
361
|
-
const painMostImportant = triageResponse.pain?.mostImportant || null;
|
|
362
|
-
// Patient words only: buildSafetySignals scans these for red-flag patterns.
|
|
363
|
-
const freeTextBits = [
|
|
364
|
-
triageResponse.otherSymptomsText,
|
|
365
|
-
...triageResponse.otherSymptomsNotProctcae,
|
|
366
|
-
triageResponse.pain?.otherText,
|
|
367
|
-
painMostImportant,
|
|
368
|
-
].filter(Boolean);
|
|
369
|
-
// The flow asks for the worst symptom's intensity, not its interference.
|
|
370
|
-
const freeTextLabelled = [
|
|
371
|
-
triageResponse.otherSymptomsText,
|
|
372
|
-
...triageResponse.otherSymptomsNotProctcae,
|
|
373
|
-
triageResponse.otherSymptomsInterference
|
|
374
|
-
? `Intensidad de otros síntomas: ${triageResponse.otherSymptomsInterference}` : null,
|
|
375
|
-
triageResponse.pain?.otherText ? `Otros dolores: ${triageResponse.pain.otherText}` : null,
|
|
376
|
-
painMostImportant ? `Dolor más importante: ${painMostImportant}` : null,
|
|
377
|
-
].filter(Boolean);
|
|
378
|
-
|
|
379
|
-
if (!hasActionableFindings({
|
|
380
|
-
graded,
|
|
381
|
-
additionalSymptoms: triageResponse.additionalSymptoms,
|
|
382
|
-
freeTextDerivedSymptoms,
|
|
383
|
-
freeTextBits,
|
|
384
|
-
nonIdentifiedSymptoms: triageResponse.nonIdentifiedSymptoms,
|
|
385
|
-
ungradedTerms,
|
|
386
|
-
})) {
|
|
387
|
-
return finish({ status: 'skipped', reason: 'no_symptoms_reported' });
|
|
208
|
+
graded = gradeComposites(catalog, new TriageResponse(triageResponse));
|
|
209
|
+
} catch (gradeErr) {
|
|
210
|
+
logger.warn('[triageRecommendation] grading failed', { code, error: gradeErr?.message });
|
|
211
|
+
return { ...settle, status: 'failed', stage: 'assemble', reason: 'grading_failed' };
|
|
388
212
|
}
|
|
213
|
+
}
|
|
214
|
+
const answeredTermList = askedTermsOf(catalog, triageResponse.answers);
|
|
215
|
+
const sentinels = sentinelTermsOf(catalog, triageResponse.answers);
|
|
216
|
+
const gradedTerms = new Set(graded.map((symptom) => symptom.term));
|
|
217
|
+
settle.droppedComboCount = answeredTermList.filter((term) => !gradedTerms.has(term)).length;
|
|
218
|
+
const sentinelTerms = new Set([...sentinels.notApplicable, ...sentinels.declined]);
|
|
219
|
+
const ungradedTerms = answeredTermList.filter((term) => !gradedTerms.has(term) && !sentinelTerms.has(term));
|
|
220
|
+
// Pain is answered in its own block, so it never appears in answeredTermList.
|
|
221
|
+
if (affirmative(triageResponse.pain?.hasPain) && !gradedTerms.has(PAIN_TERM)) ungradedTerms.push(PAIN_TERM);
|
|
222
|
+
|
|
223
|
+
const adherenceEntries = payload.adherence.filter(Boolean);
|
|
224
|
+
const priorResolutions = await readPriorResolutions(adherenceEntries, payload.patientRecordId);
|
|
225
|
+
const adherenceCounts = await recordTriageAdherence({
|
|
226
|
+
code, entries: adherenceEntries, patientRecordId: payload.patientRecordId, priorResolutions, eventKey: payload.triageRecordId,
|
|
227
|
+
});
|
|
228
|
+
settle.adherenceRecorded = adherenceCounts.recorded;
|
|
229
|
+
settle.adherenceSkipped = adherenceCounts.skipped;
|
|
230
|
+
settle.adherenceNoTask = adherenceCounts.noTask;
|
|
231
|
+
settle.adherenceUnresolved = adherenceCounts.unresolved;
|
|
232
|
+
settle.adherenceUnverified = adherenceCounts.unverified;
|
|
233
|
+
settle.adherenceFailed = adherenceCounts.failed;
|
|
234
|
+
settle.adherenceDuplicate = adherenceCounts.duplicate;
|
|
235
|
+
settle.adherenceMalformed = payload.adherence.length - adherenceEntries.length;
|
|
236
|
+
|
|
237
|
+
const painMostImportant = triageResponse.pain?.mostImportant || null;
|
|
238
|
+
// Patient words only: buildSafetySignals scans these for red-flag patterns.
|
|
239
|
+
const freeTextBits = [
|
|
240
|
+
triageResponse.otherSymptomsText,
|
|
241
|
+
...triageResponse.otherSymptomsNotProctcae,
|
|
242
|
+
triageResponse.pain?.otherText,
|
|
243
|
+
painMostImportant,
|
|
244
|
+
].filter(Boolean);
|
|
245
|
+
// The flow asks for the worst symptom's intensity, not its interference.
|
|
246
|
+
const freeTextLabelled = [
|
|
247
|
+
triageResponse.otherSymptomsText,
|
|
248
|
+
...triageResponse.otherSymptomsNotProctcae,
|
|
249
|
+
triageResponse.otherSymptomsInterference
|
|
250
|
+
? `Intensidad de otros síntomas: ${triageResponse.otherSymptomsInterference}` : null,
|
|
251
|
+
triageResponse.pain?.otherText ? `Otros dolores: ${triageResponse.pain.otherText}` : null,
|
|
252
|
+
painMostImportant ? `Dolor más importante: ${painMostImportant}` : null,
|
|
253
|
+
].filter(Boolean);
|
|
254
|
+
|
|
255
|
+
if (!hasActionableFindings({
|
|
256
|
+
graded,
|
|
257
|
+
additionalSymptoms: triageResponse.additionalSymptoms,
|
|
258
|
+
freeTextDerivedSymptoms,
|
|
259
|
+
freeTextBits,
|
|
260
|
+
nonIdentifiedSymptoms: triageResponse.nonIdentifiedSymptoms,
|
|
261
|
+
ungradedTerms,
|
|
262
|
+
})) {
|
|
263
|
+
return { ...settle, status: 'skipped', reason: 'no_symptoms_reported' };
|
|
264
|
+
}
|
|
389
265
|
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
266
|
+
const profile = await readClinicalProfile(code);
|
|
267
|
+
if (profile === undefined) return { ...settle, status: 'failed', stage: 'assemble', reason: 'profile_read_failed' };
|
|
268
|
+
if (!profile) return { ...settle, status: 'failed', stage: 'assemble', reason: 'no_clinical_profile' };
|
|
393
269
|
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
});
|
|
400
|
-
const [riskAssessment] = riskRead.assessments;
|
|
401
|
-
// A failed read degrades the section; it must never fail the run.
|
|
402
|
-
const [openCases, escalations] = await Promise.all([
|
|
403
|
-
readSymptomCases({ patientId: code })
|
|
404
|
-
.then((cases) => cases.filter((managed) => OPEN_STATUSES.includes(managed.condition.clinicalStatus)))
|
|
405
|
-
.catch((err) => {
|
|
406
|
-
logger.warn('[triageRecommendation] open cases unavailable; section degraded', { code, error: err?.message });
|
|
407
|
-
return [];
|
|
408
|
-
}),
|
|
409
|
-
readDispatchedEscalations({ patientId: code, since: escalationLookbackSince() })
|
|
410
|
-
.catch((err) => {
|
|
411
|
-
logger.warn('[triageRecommendation] escalation recall unavailable; section degraded', { code, error: err?.message });
|
|
412
|
-
return [];
|
|
413
|
-
}),
|
|
414
|
-
]);
|
|
415
|
-
const patterns = await getSafetyFlagPatterns().catch(() => []);
|
|
416
|
-
const safetySignals = buildSafetySignals({ graded, riskAssessment, freeTextBits, patterns });
|
|
417
|
-
|
|
418
|
-
// Ungraded pain has to reach the sub-agents as unknown, not vanish with its own block.
|
|
419
|
-
const askedTerms = [...new Set([...answeredTermList, ...ungradedTerms])];
|
|
420
|
-
const additionalSymptoms = resolveAdditionalSymptoms(catalog, triageResponse.additionalSymptoms);
|
|
421
|
-
const casoBaseFor = (stage, symptomSignals) => buildCasoBase({
|
|
422
|
-
profile,
|
|
423
|
-
graded,
|
|
424
|
-
askedTerms,
|
|
425
|
-
...sentinels,
|
|
426
|
-
priorResolutions,
|
|
427
|
-
safetySignals,
|
|
428
|
-
symptomsChange: triageResponse.symptomsChange,
|
|
429
|
-
openCases,
|
|
430
|
-
escalations,
|
|
431
|
-
cadence: payload.cadence,
|
|
432
|
-
authored: payload.authored,
|
|
433
|
-
triageRecordId: payload.triageRecordId,
|
|
434
|
-
freeText: freeTextLabelled.join(' · ') || null,
|
|
435
|
-
additionalSymptoms,
|
|
436
|
-
freeTextDerivedSymptoms,
|
|
437
|
-
nonIdentifiedSymptoms: triageResponse.nonIdentifiedSymptoms,
|
|
438
|
-
stage,
|
|
439
|
-
catalog,
|
|
440
|
-
symptomSignals,
|
|
270
|
+
const riskRead = await readPatientRiskAssessments({ patientId: code, limit: 1 })
|
|
271
|
+
.then((assessments) => ({ assessments, failed: false }))
|
|
272
|
+
.catch((err) => {
|
|
273
|
+
logger.warn('[triageRecommendation] risk assessment unavailable; section degraded', { code, error: err?.message });
|
|
274
|
+
return { assessments: [], failed: true };
|
|
441
275
|
});
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
...additionalSymptoms.map((symptom) => symptom.term).filter(Boolean),
|
|
448
|
-
...freeTextDerivedSymptoms,
|
|
449
|
-
];
|
|
450
|
-
const reportedKeys = symptomKeySet(catalog, reportedTerms);
|
|
451
|
-
const floorConfig = await getRedFlagMinRoutes()
|
|
452
|
-
.then(({ rows, invalidRows }) => ({ rows, invalidRows, configError: null }))
|
|
276
|
+
const [riskAssessment] = riskRead.assessments;
|
|
277
|
+
// A failed read degrades the section; it must never fail the run.
|
|
278
|
+
const [openCases, escalations] = await Promise.all([
|
|
279
|
+
readSymptomCases({ patientId: code })
|
|
280
|
+
.then((cases) => cases.filter((managed) => OPEN_STATUSES.includes(managed.condition.clinicalStatus)))
|
|
453
281
|
.catch((err) => {
|
|
454
|
-
logger.warn('[triageRecommendation]
|
|
455
|
-
return
|
|
456
|
-
})
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
282
|
+
logger.warn('[triageRecommendation] open cases unavailable; section degraded', { code, error: err?.message });
|
|
283
|
+
return [];
|
|
284
|
+
}),
|
|
285
|
+
readDispatchedEscalations({ patientId: code, since: escalationLookbackSince() })
|
|
286
|
+
.catch((err) => {
|
|
287
|
+
logger.warn('[triageRecommendation] escalation recall unavailable; section degraded', { code, error: err?.message });
|
|
288
|
+
return [];
|
|
289
|
+
}),
|
|
290
|
+
]);
|
|
291
|
+
const patterns = await getSafetyFlagPatterns().catch(() => []);
|
|
292
|
+
const safetySignals = buildSafetySignals({ graded, riskAssessment, freeTextBits, patterns });
|
|
293
|
+
|
|
294
|
+
// Ungraded pain has to reach the sub-agents as unknown, not vanish with its own block.
|
|
295
|
+
const askedTerms = [...new Set([...answeredTermList, ...ungradedTerms])];
|
|
296
|
+
const additionalSymptoms = resolveAdditionalSymptoms(catalog, triageResponse.additionalSymptoms);
|
|
297
|
+
const casoBaseFor = (stage, symptomSignals) => buildCasoBase({
|
|
298
|
+
profile,
|
|
299
|
+
graded,
|
|
300
|
+
askedTerms,
|
|
301
|
+
...sentinels,
|
|
302
|
+
priorResolutions,
|
|
303
|
+
safetySignals,
|
|
304
|
+
symptomsChange: triageResponse.symptomsChange,
|
|
305
|
+
openCases,
|
|
306
|
+
escalations,
|
|
307
|
+
cadence: payload.cadence,
|
|
308
|
+
authored: payload.authored,
|
|
309
|
+
triageRecordId: payload.triageRecordId,
|
|
310
|
+
freeText: freeTextLabelled.join(' · ') || null,
|
|
311
|
+
additionalSymptoms,
|
|
312
|
+
freeTextDerivedSymptoms,
|
|
313
|
+
nonIdentifiedSymptoms: triageResponse.nonIdentifiedSymptoms,
|
|
314
|
+
stage,
|
|
315
|
+
catalog,
|
|
316
|
+
symptomSignals,
|
|
317
|
+
});
|
|
468
318
|
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
settle.supportSafetyCleared = !gate.urgentUnder24h
|
|
483
|
-
&& gate.redFlags.every((flag) => flag.verificationStatus === 'denied');
|
|
484
|
-
|
|
485
|
-
const planStart = Date.now();
|
|
486
|
-
const boundary = {
|
|
487
|
-
catalog,
|
|
488
|
-
gate,
|
|
489
|
-
deniedKeys,
|
|
490
|
-
reportedKeys,
|
|
491
|
-
deniedAeKeys: deniedAeKeySet(catalog, gate),
|
|
492
|
-
reported: reportedSymptoms(catalog, reportedTerms),
|
|
493
|
-
};
|
|
494
|
-
const rankContext = buildRankContext({ catalog, graded, reportedTerms, priorResolutions, openCases });
|
|
495
|
-
const symptomSignals = buildSymptomSignals({
|
|
496
|
-
catalog, graded, ungradedTerms, additionalSymptoms, freeTextDerivedSymptoms, priorResolutions, openCases,
|
|
497
|
-
});
|
|
498
|
-
const planOutcome = await runPlan({
|
|
499
|
-
provider, presetId: planPresetId, casoBase: casoBaseFor('plan', symptomSignals), gate, boundary, rankContext, rid, code, payload,
|
|
319
|
+
const { reported, denied } = splitByEpistemics({ graded, askedTerms, ...sentinels });
|
|
320
|
+
const deniedKeys = symptomKeySet(catalog, denied);
|
|
321
|
+
const reportedTerms = [
|
|
322
|
+
...reported.map((symptom) => symptom.term),
|
|
323
|
+
...additionalSymptoms.map((symptom) => symptom.term).filter(Boolean),
|
|
324
|
+
...freeTextDerivedSymptoms,
|
|
325
|
+
];
|
|
326
|
+
const reportedKeys = symptomKeySet(catalog, reportedTerms);
|
|
327
|
+
const floorConfig = await getRedFlagMinRoutes()
|
|
328
|
+
.then(({ rows, invalidRows }) => ({ rows, invalidRows, configError: null }))
|
|
329
|
+
.catch((err) => {
|
|
330
|
+
logger.warn('[triageRecommendation] red-flag minimum routes unavailable; no route floor', { code, error: err?.message });
|
|
331
|
+
return { rows: [], invalidRows: [], configError: err?.message || 'desconocido' };
|
|
500
332
|
});
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
settle.
|
|
508
|
-
|
|
509
|
-
settle.rankReordered = planOutcome.rankReordered;
|
|
510
|
-
settle.deniedCardsDropped = planOutcome.deniedCardsDropped;
|
|
511
|
-
settle.deniedTargetsStripped = planOutcome.deniedTargetsStripped;
|
|
512
|
-
|
|
513
|
-
try {
|
|
514
|
-
await storeRecommendationPlan({ patientId: code, plan });
|
|
515
|
-
} catch (err) {
|
|
516
|
-
logger.error('[triageRecommendation] plan store failed', { code, runId: rid, error: err?.message });
|
|
517
|
-
return finish({ status: 'failed', stage: 'fhir', reason: 'store_failed' });
|
|
518
|
-
}
|
|
519
|
-
const mirrorPayload = {
|
|
520
|
-
triageRecordId: payload.triageRecordId,
|
|
521
|
-
step1: buildLegacyStep1(gate),
|
|
522
|
-
step2: buildLegacyStep2(plan),
|
|
523
|
-
step3: buildLegacyStep3({ plan, gate }),
|
|
524
|
-
};
|
|
525
|
-
return finish({ status: 'success', reason: null }, mirrorPayload);
|
|
526
|
-
} catch (err) {
|
|
527
|
-
logger.error('[triageRecommendation] recommendation generation failed', { code, runId: rid, error: err?.message });
|
|
528
|
-
return finish({ status: 'failed', stage: 'error', reason: 'error' });
|
|
529
|
-
}
|
|
530
|
-
}
|
|
333
|
+
const routeFloor = {
|
|
334
|
+
catalog,
|
|
335
|
+
...floorConfig,
|
|
336
|
+
affirmedKeys: reportedKeys,
|
|
337
|
+
riskAssessment,
|
|
338
|
+
riskReadFailed: riskRead.failed,
|
|
339
|
+
freeTextPending: settle.classifierPending === true && freeTextBits.length > 0,
|
|
340
|
+
};
|
|
531
341
|
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
342
|
+
const gateStart = Date.now();
|
|
343
|
+
const gateOutcome = await runGate({
|
|
344
|
+
provider, presetId: gatePresetId, casoBase: casoBaseFor('gate'), routeFloor, rid, code, payload,
|
|
345
|
+
});
|
|
346
|
+
settle.gateLatencyMs = Date.now() - gateStart;
|
|
347
|
+
settle.gateAttempts = gateOutcome.attempts;
|
|
348
|
+
if (gateOutcome.failure) {
|
|
535
349
|
return {
|
|
536
|
-
...
|
|
537
|
-
|
|
538
|
-
|
|
350
|
+
...settle,
|
|
351
|
+
...gateOutcome.failure,
|
|
352
|
+
autoRepairs: gateOutcome.gateRepairs || [],
|
|
353
|
+
qualityWarnings: gateOutcome.gateWarnings || settle.qualityWarnings,
|
|
539
354
|
};
|
|
540
|
-
}).filter((candidate) => candidate.groupEligible || candidate.urgentIntakeEligible);
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
async function settleSupportClaims(requests) {
|
|
544
|
-
const supportPendingSettlements = [];
|
|
545
|
-
let supportActionError = null;
|
|
546
|
-
for (const request of requests) {
|
|
547
|
-
try {
|
|
548
|
-
const settled = await settleInvitation(request);
|
|
549
|
-
if (!settled) {
|
|
550
|
-
const confirmed = await getSupportCandidateModel().findOne({
|
|
551
|
-
candidateId: request.candidateId,
|
|
552
|
-
invitationAttempts: { $elemMatch: { idempotencyKey: request.idempotencyKey, status: request.status } },
|
|
553
|
-
}).lean();
|
|
554
|
-
if (!confirmed) throw new Error('claim_settlement_unconfirmed');
|
|
555
|
-
}
|
|
556
|
-
} catch (error) {
|
|
557
|
-
supportPendingSettlements.push(request);
|
|
558
|
-
supportActionError = error?.message || 'claim_settlement_failed';
|
|
559
|
-
}
|
|
560
355
|
}
|
|
561
|
-
|
|
562
|
-
|
|
356
|
+
const { gate, gateRepairs, gateWarnings } = gateOutcome;
|
|
357
|
+
settle.gateVerdict = gate.urgentUnder24h ? 'urgent' : 'clear';
|
|
358
|
+
settle.urgentUnder24h = gate.urgentUnder24h;
|
|
359
|
+
settle.escalationRoute = gate.escalationRoute;
|
|
360
|
+
settle.qualityWarnings = gateWarnings;
|
|
361
|
+
|
|
362
|
+
const planStart = Date.now();
|
|
363
|
+
const boundary = {
|
|
364
|
+
catalog,
|
|
365
|
+
gate,
|
|
366
|
+
deniedKeys,
|
|
367
|
+
reportedKeys,
|
|
368
|
+
deniedAeKeys: deniedAeKeySet(catalog, gate),
|
|
369
|
+
reported: reportedSymptoms(catalog, reportedTerms),
|
|
370
|
+
};
|
|
371
|
+
const rankContext = buildRankContext({ catalog, graded, reportedTerms, priorResolutions, openCases });
|
|
372
|
+
const symptomSignals = buildSymptomSignals({
|
|
373
|
+
catalog, graded, ungradedTerms, additionalSymptoms, freeTextDerivedSymptoms, priorResolutions, openCases,
|
|
374
|
+
});
|
|
375
|
+
const planOutcome = await runPlan({
|
|
376
|
+
provider, presetId: planPresetId, casoBase: casoBaseFor('plan', symptomSignals), gate, boundary, rankContext, rid, code, payload,
|
|
377
|
+
});
|
|
378
|
+
settle.planLatencyMs = Date.now() - planStart;
|
|
379
|
+
settle.attempts = planOutcome.attempts;
|
|
380
|
+
if (planOutcome.failure) return { ...settle, ...planOutcome.failure, autoRepairs: [...gateRepairs, ...(planOutcome.repairs || [])] };
|
|
381
|
+
const { plan, planRepairs, qualityWarnings } = planOutcome;
|
|
382
|
+
settle.elementCount = plan.elements.length;
|
|
383
|
+
settle.autoRepairs = [...gateRepairs, ...planRepairs];
|
|
384
|
+
settle.qualityWarnings = [...gateWarnings, ...qualityWarnings];
|
|
385
|
+
settle.rankReordered = planOutcome.rankReordered;
|
|
386
|
+
settle.deniedCardsDropped = planOutcome.deniedCardsDropped;
|
|
387
|
+
settle.deniedTargetsStripped = planOutcome.deniedTargetsStripped;
|
|
563
388
|
|
|
564
|
-
async function settleSupportRouting({ payload, provider, supportRouting, context, runId }) {
|
|
565
|
-
if (supportRouting.enabled !== true) return { ok: false, audit: {}, candidates: [] };
|
|
566
389
|
try {
|
|
567
|
-
|
|
568
|
-
.findOne({ runId, supportRoutingOk: true }).sort({ createdAt: -1 }).lean();
|
|
569
|
-
if (previous) {
|
|
570
|
-
const ids = previous.supportDeliveryCandidateIds || [];
|
|
571
|
-
return {
|
|
572
|
-
ok: true,
|
|
573
|
-
previous,
|
|
574
|
-
candidates: [],
|
|
575
|
-
audit: { supportRoutingOk: true, supportCandidateCount: previous.supportCandidateCount, supportDeliveryCandidateIds: ids },
|
|
576
|
-
};
|
|
577
|
-
}
|
|
578
|
-
const recommendation = await evaluateSupportRouting({
|
|
579
|
-
provider,
|
|
580
|
-
patientId: payload.patientCode,
|
|
581
|
-
origin: 'triage',
|
|
582
|
-
sourceId: payload.triageRecordId,
|
|
583
|
-
createdAt: payload.authored || new Date().toISOString(),
|
|
584
|
-
context,
|
|
585
|
-
});
|
|
586
|
-
const candidates = await recordSupportRoutingRecommendation(recommendation);
|
|
587
|
-
for (const service of ['nutrition', 'psychology']) await updateSupportOperationalReview({
|
|
588
|
-
patientId: payload.patientCode, service, sourceId: payload.triageRecordId,
|
|
589
|
-
reasonCode: 'classification_failed', resolved: true,
|
|
590
|
-
noClinicalDecision: !recommendation.decisions.some((decision) => decision.service === service),
|
|
591
|
-
});
|
|
592
|
-
for (const decision of recommendation.decisions) {
|
|
593
|
-
const incomplete = !decision.safety || decision.safety.needsHumanConfirmation !== false
|
|
594
|
-
|| ['suicidalIdeation', 'immediateRisk', 'urgentMedicalRisk'].some((flag) => typeof decision.safety[flag] !== 'boolean');
|
|
595
|
-
await updateSupportOperationalReview({
|
|
596
|
-
patientId: payload.patientCode, service: decision.service, sourceId: payload.triageRecordId,
|
|
597
|
-
reasonCode: 'classification_safety_unconfirmed', resolved: !incomplete,
|
|
598
|
-
});
|
|
599
|
-
}
|
|
600
|
-
const safetyCleared = recommendation.decisions.every((decision) => decision.safety
|
|
601
|
-
&& ['suicidalIdeation', 'immediateRisk', 'urgentMedicalRisk', 'needsHumanConfirmation']
|
|
602
|
-
.every((flag) => decision.safety[flag] === false));
|
|
603
|
-
const safeServices = safetyCleared ? recommendation.decisions.map((decision) => decision.service) : [];
|
|
604
|
-
const deliverable = candidates.filter((candidate) => safeServices.includes(candidate.service));
|
|
605
|
-
return { ok: true, candidates: deliverable, audit: {
|
|
606
|
-
supportRoutingOk: true,
|
|
607
|
-
supportCandidateCount: candidates.length,
|
|
608
|
-
supportDeliveryCandidateIds: deliverable.map((candidate) => candidate.candidateId),
|
|
609
|
-
} };
|
|
390
|
+
await storeRecommendationPlan({ patientId: code, plan });
|
|
610
391
|
} catch (err) {
|
|
611
|
-
logger.
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
392
|
+
logger.error('[triageRecommendation] plan store failed', { code, runId: rid, error: err?.message });
|
|
393
|
+
return { ...settle, status: 'failed', stage: 'fhir', reason: 'store_failed' };
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
settle.mirrorAttempted = true;
|
|
397
|
+
const mirrorPayload = {
|
|
398
|
+
triageRecordId: payload.triageRecordId,
|
|
399
|
+
step1: buildLegacyStep1(gate),
|
|
400
|
+
step2: buildLegacyStep2(plan),
|
|
401
|
+
step3: buildLegacyStep3({ plan, gate }),
|
|
402
|
+
};
|
|
403
|
+
const mirror = await recordClusterRecommendationsMirror({ code, ...mirrorPayload });
|
|
404
|
+
settle.mirrorOk = mirror.ok;
|
|
405
|
+
settle.mirrorRecordId = mirror.recordId;
|
|
406
|
+
if (!mirror.ok) {
|
|
407
|
+
settle.mirrorError = 'write_failed';
|
|
408
|
+
settle.mirrorPayload = mirrorPayload;
|
|
409
|
+
logger.error('[triageRecommendation] Airtable mirror failed; plan stored in FHIR', { code, runId: rid, triageRecordId: payload.triageRecordId });
|
|
410
|
+
return { ...settle, status: 'failed', stage: 'mirror', reason: 'mirror_failed' };
|
|
621
411
|
}
|
|
412
|
+
|
|
413
|
+
return { ...settle, status: 'success', reason: null };
|
|
622
414
|
}
|
|
623
415
|
|
|
624
416
|
async function pendingMirrorPayload(runId) {
|
|
@@ -627,9 +419,8 @@ async function pendingMirrorPayload(runId) {
|
|
|
627
419
|
.sort({ createdAt: -1 })
|
|
628
420
|
.lean();
|
|
629
421
|
if (!last || last.mirrorOk !== false || !last.mirrorPayload) return null;
|
|
630
|
-
const { triageRecordId, step1, step2, step3
|
|
631
|
-
return { triageRecordId, step1, step2, step3
|
|
632
|
-
...(excludeRecordId ? { excludeRecordId } : {}), ...(excludeRecordIds ? { excludeRecordIds } : {}) };
|
|
422
|
+
const { triageRecordId, step1, step2, step3 } = last.mirrorPayload;
|
|
423
|
+
return { triageRecordId, step1, step2, step3 };
|
|
633
424
|
}
|
|
634
425
|
|
|
635
426
|
function gateCorrectionNote(issues) {
|
|
@@ -650,7 +441,9 @@ function rejectedGateShape(rawGate, redFlags) {
|
|
|
650
441
|
};
|
|
651
442
|
}
|
|
652
443
|
|
|
653
|
-
async function runGate({
|
|
444
|
+
async function runGate({
|
|
445
|
+
provider, presetId, casoBase, routeFloor, rid, code, payload,
|
|
446
|
+
}) {
|
|
654
447
|
let attempts = 0;
|
|
655
448
|
let gateRepairs = [];
|
|
656
449
|
let accepted = null;
|
|
@@ -736,22 +529,26 @@ async function runGate({ provider, presetId, casoBase, routeFloor, rid, code, pa
|
|
|
736
529
|
});
|
|
737
530
|
} catch (err) {
|
|
738
531
|
logger.warn('[triageRecommendation] gate failed DTO validation', { code, runId: rid, error: err?.message });
|
|
739
|
-
return {
|
|
532
|
+
return {
|
|
533
|
+
attempts, gateRepairs, gateWarnings, failure: { status: 'failed', stage: 'safety_gate', reason: 'gate_malformed' },
|
|
534
|
+
};
|
|
740
535
|
}
|
|
741
536
|
try {
|
|
742
537
|
await storeSafetyGate({ patientId: code, safetyGate: gate });
|
|
743
538
|
} catch (err) {
|
|
744
539
|
logger.error('[triageRecommendation] gate store failed', { code, runId: rid, error: err?.message });
|
|
745
|
-
return {
|
|
540
|
+
return {
|
|
541
|
+
attempts, gateRepairs, gateWarnings, failure: { status: 'failed', stage: 'fhir', reason: 'gate_store_failed' },
|
|
542
|
+
};
|
|
746
543
|
}
|
|
747
|
-
return {
|
|
544
|
+
return {
|
|
545
|
+
attempts, gate, gateRepairs, gateWarnings,
|
|
546
|
+
};
|
|
748
547
|
}
|
|
749
548
|
|
|
750
549
|
async function runPlan({ provider, presetId, casoBase, gate, boundary = null, rankContext = {}, rid, code, payload }) {
|
|
751
550
|
const planInput = `${casoBase}\n\n### Gate de seguridad comprometido (PASO 1)\n${JSON.stringify(buildLegacyStep1(gate))}`;
|
|
752
551
|
let lastIssues = [];
|
|
753
|
-
let safetyUncertain = false;
|
|
754
|
-
const outcome = (result) => ({ ...result, safetyUncertain });
|
|
755
552
|
const buildPlan = (takeaways, elements) => new RecommendationPlan({
|
|
756
553
|
runId: rid,
|
|
757
554
|
patientId: code,
|
|
@@ -787,42 +584,43 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
787
584
|
} catch (err) {
|
|
788
585
|
logger.warn('[triageRecommendation] plan provider call failed', { code, runId: rid, attempt, error: err?.message });
|
|
789
586
|
lastIssues = [];
|
|
790
|
-
if (last) return
|
|
587
|
+
if (last) return { attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_provider_failed' } };
|
|
791
588
|
continue;
|
|
792
589
|
}
|
|
793
590
|
if (result?.status && result.status !== 'completed') {
|
|
794
591
|
lastIssues = [{ path: 'plan', problem: `respuesta incompleta del proveedor (status=${result.status})` }];
|
|
795
592
|
firstEvidence = firstEvidence ?? rawEvidence(result);
|
|
796
|
-
if (last) return
|
|
593
|
+
if (last) return { attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_incomplete', hardRejectIssues: lastIssues, rawExcerpt: firstEvidence } };
|
|
797
594
|
continue;
|
|
798
595
|
}
|
|
799
596
|
const parsed = safeParse(readOutputText(result), null);
|
|
800
597
|
firstEvidence = firstEvidence ?? rawEvidence(result);
|
|
801
598
|
if (!isPlainObject(parsed)) {
|
|
802
599
|
lastIssues = [{ path: 'plan', problem: 'la respuesta no es un objeto JSON válido' }];
|
|
803
|
-
if (last) return
|
|
600
|
+
if (last) return { attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_malformed', rawExcerpt: firstEvidence } };
|
|
804
601
|
continue;
|
|
805
602
|
}
|
|
806
603
|
const rawPlan = isPlainObject(parsed.input) ? parsed.input : parsed;
|
|
807
604
|
const takeaways = objectArg(rawPlan.takeaways);
|
|
808
|
-
safetyUncertain = safetyUncertain || takeaways?.safety_confirmation_needed === true || takeaways?.vital_risk_possible_now === true;
|
|
809
605
|
const rawElements = arr(arrayArg(rawPlan.elements));
|
|
810
606
|
if (!takeaways || !rawElements.length) {
|
|
811
607
|
lastIssues = [{ path: 'elements', problem: 'takeaways y elements[] no vacío son obligatorios' }];
|
|
812
608
|
if (attempt < PLAN_MAX_ATTEMPTS) continue;
|
|
813
|
-
return
|
|
609
|
+
return { attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_empty', rawExcerpt: firstEvidence } };
|
|
814
610
|
}
|
|
815
611
|
|
|
816
612
|
repairs = [];
|
|
817
613
|
const built = rawElements.map((raw) => buildElement(raw, repairs));
|
|
818
614
|
stripOtcOffers(built, repairs);
|
|
819
|
-
const {
|
|
615
|
+
const {
|
|
616
|
+
elements, dropped, stripped, urgentReframed,
|
|
617
|
+
} = applyCardSurfaceBoundary(built, boundary, repairs, { rescue: last });
|
|
820
618
|
deniedCardsDropped = dropped;
|
|
821
619
|
deniedTargetsStripped = stripped;
|
|
822
620
|
if (!elements.length) {
|
|
823
621
|
lastIssues = [{ path: 'elements', problem: 'ningún elemento nombra un síntoma reportado en este triaje; construye el plan sobre los síntomas que el paciente sí reportó hoy' }];
|
|
824
622
|
if (attempt < PLAN_MAX_ATTEMPTS) continue;
|
|
825
|
-
return
|
|
623
|
+
return { attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_all_denied', hardRejectIssues: lastIssues } };
|
|
826
624
|
}
|
|
827
625
|
rankReordered = applyRankOrder(elements, gate, repairs, rankContext);
|
|
828
626
|
const issues = validate(elements, { gate, lane: 'triage', urgentReframed });
|
|
@@ -830,7 +628,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
830
628
|
if (blocking.length) {
|
|
831
629
|
lastIssues = blocking;
|
|
832
630
|
if (attempt < PLAN_MAX_ATTEMPTS) continue;
|
|
833
|
-
return
|
|
631
|
+
return { attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_invalid', hardRejectIssues: blocking } };
|
|
834
632
|
}
|
|
835
633
|
|
|
836
634
|
let plan;
|
|
@@ -839,9 +637,9 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
839
637
|
} catch (err) {
|
|
840
638
|
lastIssues = [{ path: 'plan', problem: err?.message || 'DTO inválido' }];
|
|
841
639
|
if (attempt < PLAN_MAX_ATTEMPTS) continue;
|
|
842
|
-
return
|
|
640
|
+
return { attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_invalid', hardRejectIssues: lastIssues } };
|
|
843
641
|
}
|
|
844
|
-
return
|
|
642
|
+
return {
|
|
845
643
|
attempts: attempt,
|
|
846
644
|
plan,
|
|
847
645
|
planRepairs: repairs,
|
|
@@ -849,9 +647,9 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
|
|
|
849
647
|
rankReordered,
|
|
850
648
|
deniedCardsDropped,
|
|
851
649
|
deniedTargetsStripped,
|
|
852
|
-
}
|
|
650
|
+
};
|
|
853
651
|
}
|
|
854
|
-
return
|
|
652
|
+
return { attempts: PLAN_MAX_ATTEMPTS, failure: { status: 'failed', stage: 'plan', reason: 'plan_invalid', hardRejectIssues: lastIssues } };
|
|
855
653
|
}
|
|
856
654
|
|
|
857
655
|
function rawEvidence(result) {
|