@peopl-health/nexus 5.51.0-dev.7633 → 5.51.0-dev.7635

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.
Files changed (36) hide show
  1. package/README.md +21 -0
  2. package/lib/clinical/AssistantProcessor.js +156 -12
  3. package/lib/clinical/context/ToolRuntimeContext.js +39 -1
  4. package/lib/clinical/context/turnContext.js +10 -0
  5. package/lib/clinical/models/supportCandidateModel.js +90 -0
  6. package/lib/clinical/models/triageRecommendationEventModel.js +28 -0
  7. package/lib/clinical/providers/BaseLLMProvider.js +45 -5
  8. package/lib/clinical/services/clinicalAirtableService.js +8 -5
  9. package/lib/clinical/services/deliverySettlementService.js +39 -0
  10. package/lib/clinical/services/divergenceService.js +9 -2
  11. package/lib/clinical/services/supportActionService.js +129 -0
  12. package/lib/clinical/services/supportCandidateService.js +532 -0
  13. package/lib/clinical/services/supportRoutingAgentService.js +118 -0
  14. package/lib/clinical/services/triageRecommendationService.js +453 -251
  15. package/lib/clinical/tools/deliverPatientMessageTool.js +82 -23
  16. package/lib/clinical/tools/registerClinicalTools.js +2 -0
  17. package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
  18. package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +142 -0
  19. package/lib/controllers/dashboardController.js +5 -2
  20. package/lib/controllers/escalationReviewController.js +0 -12
  21. package/lib/core/BatchingManager.js +20 -9
  22. package/lib/core/NexusMessaging.js +25 -6
  23. package/lib/core/ProcessingPipeline.js +32 -3
  24. package/lib/core/runtimeToolPolicy.js +3 -0
  25. package/lib/index.d.ts +334 -6
  26. package/lib/index.js +22 -0
  27. package/lib/models/escalationReviewModel.js +0 -4
  28. package/lib/routes/index.js +0 -2
  29. package/lib/services/airtableService.js +8 -1
  30. package/lib/services/dashboard-provider-registry.js +38 -0
  31. package/lib/services/dashboardService.js +30 -3
  32. package/lib/services/escalationReviewService.js +4 -36
  33. package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
  34. package/lib/shared/dtos/SupportAction.js +28 -0
  35. package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
  36. package/package.json +1 -1
@@ -2,6 +2,7 @@ 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');
5
6
  const { isShadowRun } = require('../helpers/shadowHelper');
6
7
  const { readOutputText } = require('../helpers/clinicalMentionHelper');
7
8
  const {
@@ -59,6 +60,9 @@ const { validate, blockingIssues, urgentGateIssues } = require('./recommendation
59
60
  const { escalationLookbackSince } = require('./turnRiskBriefService');
60
61
  const { applyRankOrder, buildRankContext, buildSymptomSignals } = require('./recommendationRankService');
61
62
  const { recordClusterRecommendationsMirror } = require('./clinicalAirtableService');
63
+ const { evaluateSupportRouting } = require('./supportRoutingAgentService');
64
+ const { recordSupportRoutingRecommendation, settleInvitation, updateSupportOperationalReview } = require('./supportCandidateService');
65
+ const { prepareSupportAction } = require('./supportActionService');
62
66
 
63
67
  const GENERATION_BACKOFF_MS = 10 * 60 * 1000;
64
68
  const GATE_MAX_ATTEMPTS = 2;
@@ -70,7 +74,7 @@ const PATIENT_LOOKUP_FIELD = 'patient_id (from triaje_symptoms) (from cluster_re
70
74
  const generationState = new MapCache({ maxSize: 2000, ttl: GENERATION_BACKOFF_MS });
71
75
  const FREE_TEXT_SYMPTOM_FIELDS = ['freetext_derived', 'corresponding_CTCAE', 'grade_num'];
72
76
 
73
- function handleTriageCompleted(rawPayload, { trigger = 'auna', runId = null } = {}) {
77
+ function handleTriageCompleted(rawPayload, { trigger = 'auna', runId = null, supportRouting = {} } = {}) {
74
78
  let payload;
75
79
  try {
76
80
  payload = new TriageCompletion(rawPayload);
@@ -113,12 +117,15 @@ function handleTriageCompleted(rawPayload, { trigger = 'auna', runId = null } =
113
117
  generationState.set(payload.triageRecordId, true);
114
118
  const startedAt = Date.now();
115
119
  Promise.resolve()
116
- .then(() => generateTriageRecommendations({ payload, provider: requireGatewayProvider(), runId }))
120
+ .then(() => generateTriageRecommendations({ payload, provider: requireGatewayProvider(), runId, supportRouting }))
117
121
  .then((settle) => {
118
122
  logger.info('[triageRecommendation] settled', { code: payload.patientCode, triageRecordId: payload.triageRecordId, status: settle.status, reason: settle.reason });
119
123
  // A failed run releases the claim so a deliberate redelivery can retry
120
124
  // immediately; success keeps it for the dedupe window.
121
- if (settle.status === 'failed') generationState.delete(payload.triageRecordId);
125
+ if (settle.status === 'failed' || settle.supportRoutingOk === false || settle.supportActionError
126
+ || settle.supportPendingCandidateIds?.length) {
127
+ generationState.delete(payload.triageRecordId);
128
+ }
122
129
  return recordSettleEvent({ payload, trigger, totalLatencyMs: Date.now() - startedAt, ...settle });
123
130
  })
124
131
  .catch((err) => {
@@ -159,258 +166,459 @@ async function recordSettleEvent({ payload, trigger, totalLatencyMs, ...settle }
159
166
  }
160
167
  }
161
168
 
162
- async function generateTriageRecommendations({ payload, provider, runId = null }) {
169
+ async function generateTriageRecommendations({ payload, provider, runId = null, supportRouting = {} }) {
163
170
  const rid = runId || defaultRunId(payload);
164
171
  const code = payload.patientCode;
165
172
  const settle = { runId: rid };
166
173
 
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
-
188
174
  const classifier = await readFreeTextDerivedSymptoms(payload.triageRecordId, code);
189
175
  if (classifier === null) {
190
176
  return { ...settle, status: 'failed', stage: 'assemble', reason: 'triage_patient_mismatch' };
191
177
  }
192
178
  const freeTextDerivedSymptoms = classifier.terms;
193
179
  settle.classifierPending = classifier.pending;
194
-
195
180
  const catalog = getCatalog();
196
181
  const { triageResponse, unmappedQuestionIds } = buildTriageResponse(catalog, payload);
197
182
  settle.unmappedAnswerCount = unmappedQuestionIds.length;
198
183
 
199
- let graded = [];
184
+ let supportContext = { triage: triageResponse, freeTextDerivedSymptoms };
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
+
200
302
  try {
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;
303
+ const [{ presetId: gatePresetId }, { presetId: planPresetId }] = await Promise.all([getTriageGate(), getTriagePlan()]);
304
+ if (!gatePresetId || !planPresetId || typeof provider?.runStructured !== 'function') {
305
+ return finish({ status: 'failed', stage: 'assemble', reason: 'preset_unavailable' });
306
+ }
307
+ settle.methodVersion = `${gatePresetId}+${planPresetId}`;
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 = [];
207
324
  try {
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' };
325
+ const storedTriage = await storeTriage(triageResponse);
326
+ graded = storedTriage.graded;
327
+ settle.triageStored = true;
328
+ } catch (err) {
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' });
212
388
  }
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
- }
265
389
 
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' };
390
+ const profile = await readClinicalProfile(code);
391
+ if (profile === undefined) return finish({ status: 'failed', stage: 'assemble', reason: 'profile_read_failed' });
392
+ if (!profile) return finish({ status: 'failed', stage: 'assemble', reason: 'no_clinical_profile' });
269
393
 
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 };
275
- });
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)))
394
+ const riskRead = await readPatientRiskAssessments({ patientId: code, limit: 1 })
395
+ .then((assessments) => ({ assessments, failed: false }))
281
396
  .catch((err) => {
282
- logger.warn('[triageRecommendation] open cases unavailable; section degraded', { code, error: err?.message });
283
- return [];
284
- }),
285
- readDispatchedEscalations({ patientId: code, since: escalationLookbackSince() })
397
+ logger.warn('[triageRecommendation] risk assessment unavailable; section degraded', { code, error: err?.message });
398
+ return { assessments: [], failed: true };
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,
441
+ });
442
+
443
+ const { reported, denied } = splitByEpistemics({ graded, askedTerms, ...sentinels });
444
+ const deniedKeys = symptomKeySet(catalog, denied);
445
+ const reportedTerms = [
446
+ ...reported.map((symptom) => symptom.term),
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 }))
286
453
  .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
- });
454
+ logger.warn('[triageRecommendation] red-flag minimum routes unavailable; no route floor', { code, error: err?.message });
455
+ return { rows: [], invalidRows: [], configError: err?.message || 'desconocido' };
456
+ });
457
+ const routeFloor = {
458
+ catalog,
459
+ ...floorConfig,
460
+ affirmedKeys: reportedKeys,
461
+ riskAssessment,
462
+ riskReadFailed: riskRead.failed,
463
+ freeTextPending: settle.classifierPending === true && freeTextBits.length > 0,
464
+ };
318
465
 
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' };
466
+ supportContext = { ...supportContext, case: casoBaseFor('support-routing') };
467
+ startSupport();
468
+
469
+ const gateStart = Date.now();
470
+ const gateOutcome = await runGate({
471
+ provider, presetId: gatePresetId, casoBase: casoBaseFor('gate'), routeFloor, rid, code, payload,
332
472
  });
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
- };
473
+ settle.gateLatencyMs = Date.now() - gateStart;
474
+ settle.gateAttempts = gateOutcome.attempts;
475
+ if (gateOutcome.failure) return finish({ ...gateOutcome.failure, autoRepairs: gateOutcome.gateRepairs || [],
476
+ qualityWarnings: gateOutcome.gateWarnings || settle.qualityWarnings });
477
+ const { gate, gateRepairs, gateWarnings } = gateOutcome;
478
+ settle.gateVerdict = gate.urgentUnder24h ? 'urgent' : 'clear';
479
+ settle.urgentUnder24h = gate.urgentUnder24h;
480
+ settle.escalationRoute = gate.escalationRoute;
481
+ settle.qualityWarnings = gateWarnings;
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,
500
+ });
501
+ settle.planLatencyMs = Date.now() - planStart;
502
+ settle.attempts = planOutcome.attempts;
503
+ if (planOutcome.safetyUncertain) settle.supportSafetyCleared = false;
504
+ if (planOutcome.failure) return finish({ ...planOutcome.failure, autoRepairs: [...gateRepairs, ...(planOutcome.repairs || [])] });
505
+ const { plan, planRepairs, qualityWarnings } = planOutcome;
506
+ settle.elementCount = plan.elements.length;
507
+ settle.autoRepairs = [...gateRepairs, ...planRepairs];
508
+ settle.qualityWarnings = [...gateWarnings, ...qualityWarnings];
509
+ settle.rankReordered = planOutcome.rankReordered;
510
+ settle.deniedCardsDropped = planOutcome.deniedCardsDropped;
511
+ settle.deniedTargetsStripped = planOutcome.deniedTargetsStripped;
341
512
 
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) {
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
+ }
531
+
532
+ function remainingSupportCandidates(candidates, mirroredActions) {
533
+ return candidates.map((candidate) => {
534
+ const completed = mirroredActions.filter((item) => item.candidateId === candidate.candidateId).map((item) => item.type);
349
535
  return {
350
- ...settle,
351
- ...gateOutcome.failure,
352
- autoRepairs: gateOutcome.gateRepairs || [],
353
- qualityWarnings: gateOutcome.gateWarnings || settle.qualityWarnings,
536
+ ...(typeof candidate.toObject === 'function' ? candidate.toObject() : candidate),
537
+ groupEligible: candidate.groupEligible && !completed.includes('group_registration'),
538
+ urgentIntakeEligible: candidate.urgentIntakeEligible && !completed.includes('urgent_nutrition_intake'),
354
539
  };
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
+ }
355
560
  }
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;
561
+ return { supportPendingSettlements, supportActionError };
562
+ }
388
563
 
564
+ async function settleSupportRouting({ payload, provider, supportRouting, context, runId }) {
565
+ if (supportRouting.enabled !== true) return { ok: false, audit: {}, candidates: [] };
389
566
  try {
390
- await storeRecommendationPlan({ patientId: code, plan });
567
+ const previous = await getTriageRecommendationEventModel()
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
+ } };
391
610
  } catch (err) {
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' };
611
+ logger.warn('[triageRecommendation] support routing failed', { code: payload.patientCode, runId, error: err?.message });
612
+ let supportReviewError;
613
+ try {
614
+ for (const service of ['nutrition', 'psychology']) await updateSupportOperationalReview({
615
+ patientId: payload.patientCode, service, sourceId: payload.triageRecordId, reasonCode: 'classification_failed',
616
+ });
617
+ } catch (error) {
618
+ supportReviewError = error?.message || 'support review persistence failed';
619
+ }
620
+ return { ok: false, candidates: [], audit: { supportRoutingOk: false, supportRoutingError: err?.message || 'unknown', ...(supportReviewError ? { supportReviewError } : {}) } };
411
621
  }
412
-
413
- return { ...settle, status: 'success', reason: null };
414
622
  }
415
623
 
416
624
  async function pendingMirrorPayload(runId) {
@@ -419,8 +627,9 @@ async function pendingMirrorPayload(runId) {
419
627
  .sort({ createdAt: -1 })
420
628
  .lean();
421
629
  if (!last || last.mirrorOk !== false || !last.mirrorPayload) return null;
422
- const { triageRecordId, step1, step2, step3 } = last.mirrorPayload;
423
- return { triageRecordId, step1, step2, step3 };
630
+ const { triageRecordId, step1, step2, step3, supportAction, excludeRecordId, excludeRecordIds } = last.mirrorPayload;
631
+ return { triageRecordId, step1, step2, step3, ...(supportAction ? { supportAction } : {}),
632
+ ...(excludeRecordId ? { excludeRecordId } : {}), ...(excludeRecordIds ? { excludeRecordIds } : {}) };
424
633
  }
425
634
 
426
635
  function gateCorrectionNote(issues) {
@@ -441,9 +650,7 @@ function rejectedGateShape(rawGate, redFlags) {
441
650
  };
442
651
  }
443
652
 
444
- async function runGate({
445
- provider, presetId, casoBase, routeFloor, rid, code, payload,
446
- }) {
653
+ async function runGate({ provider, presetId, casoBase, routeFloor, rid, code, payload }) {
447
654
  let attempts = 0;
448
655
  let gateRepairs = [];
449
656
  let accepted = null;
@@ -529,26 +736,22 @@ async function runGate({
529
736
  });
530
737
  } catch (err) {
531
738
  logger.warn('[triageRecommendation] gate failed DTO validation', { code, runId: rid, error: err?.message });
532
- return {
533
- attempts, gateRepairs, gateWarnings, failure: { status: 'failed', stage: 'safety_gate', reason: 'gate_malformed' },
534
- };
739
+ return { attempts, gateRepairs, gateWarnings, failure: { status: 'failed', stage: 'safety_gate', reason: 'gate_malformed' } };
535
740
  }
536
741
  try {
537
742
  await storeSafetyGate({ patientId: code, safetyGate: gate });
538
743
  } catch (err) {
539
744
  logger.error('[triageRecommendation] gate store failed', { code, runId: rid, error: err?.message });
540
- return {
541
- attempts, gateRepairs, gateWarnings, failure: { status: 'failed', stage: 'fhir', reason: 'gate_store_failed' },
542
- };
745
+ return { attempts, gateRepairs, gateWarnings, failure: { status: 'failed', stage: 'fhir', reason: 'gate_store_failed' } };
543
746
  }
544
- return {
545
- attempts, gate, gateRepairs, gateWarnings,
546
- };
747
+ return { attempts, gate, gateRepairs, gateWarnings };
547
748
  }
548
749
 
549
750
  async function runPlan({ provider, presetId, casoBase, gate, boundary = null, rankContext = {}, rid, code, payload }) {
550
751
  const planInput = `${casoBase}\n\n### Gate de seguridad comprometido (PASO 1)\n${JSON.stringify(buildLegacyStep1(gate))}`;
551
752
  let lastIssues = [];
753
+ let safetyUncertain = false;
754
+ const outcome = (result) => ({ ...result, safetyUncertain });
552
755
  const buildPlan = (takeaways, elements) => new RecommendationPlan({
553
756
  runId: rid,
554
757
  patientId: code,
@@ -584,43 +787,42 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
584
787
  } catch (err) {
585
788
  logger.warn('[triageRecommendation] plan provider call failed', { code, runId: rid, attempt, error: err?.message });
586
789
  lastIssues = [];
587
- if (last) return { attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_provider_failed' } };
790
+ if (last) return outcome({ attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_provider_failed' } });
588
791
  continue;
589
792
  }
590
793
  if (result?.status && result.status !== 'completed') {
591
794
  lastIssues = [{ path: 'plan', problem: `respuesta incompleta del proveedor (status=${result.status})` }];
592
795
  firstEvidence = firstEvidence ?? rawEvidence(result);
593
- if (last) return { attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_incomplete', hardRejectIssues: lastIssues, rawExcerpt: firstEvidence } };
796
+ if (last) return outcome({ attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_incomplete', hardRejectIssues: lastIssues, rawExcerpt: firstEvidence } });
594
797
  continue;
595
798
  }
596
799
  const parsed = safeParse(readOutputText(result), null);
597
800
  firstEvidence = firstEvidence ?? rawEvidence(result);
598
801
  if (!isPlainObject(parsed)) {
599
802
  lastIssues = [{ path: 'plan', problem: 'la respuesta no es un objeto JSON válido' }];
600
- if (last) return { attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_malformed', rawExcerpt: firstEvidence } };
803
+ if (last) return outcome({ attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_malformed', rawExcerpt: firstEvidence } });
601
804
  continue;
602
805
  }
603
806
  const rawPlan = isPlainObject(parsed.input) ? parsed.input : parsed;
604
807
  const takeaways = objectArg(rawPlan.takeaways);
808
+ safetyUncertain = safetyUncertain || takeaways?.safety_confirmation_needed === true || takeaways?.vital_risk_possible_now === true;
605
809
  const rawElements = arr(arrayArg(rawPlan.elements));
606
810
  if (!takeaways || !rawElements.length) {
607
811
  lastIssues = [{ path: 'elements', problem: 'takeaways y elements[] no vacío son obligatorios' }];
608
812
  if (attempt < PLAN_MAX_ATTEMPTS) continue;
609
- return { attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_empty', rawExcerpt: firstEvidence } };
813
+ return outcome({ attempts: attempt, failure: { status: 'failed', stage: 'plan', reason: 'plan_empty', rawExcerpt: firstEvidence } });
610
814
  }
611
815
 
612
816
  repairs = [];
613
817
  const built = rawElements.map((raw) => buildElement(raw, repairs));
614
818
  stripOtcOffers(built, repairs);
615
- const {
616
- elements, dropped, stripped, urgentReframed,
617
- } = applyCardSurfaceBoundary(built, boundary, repairs, { rescue: last });
819
+ const { elements, dropped, stripped, urgentReframed } = applyCardSurfaceBoundary(built, boundary, repairs, { rescue: last });
618
820
  deniedCardsDropped = dropped;
619
821
  deniedTargetsStripped = stripped;
620
822
  if (!elements.length) {
621
823
  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' }];
622
824
  if (attempt < PLAN_MAX_ATTEMPTS) continue;
623
- return { attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_all_denied', hardRejectIssues: lastIssues } };
825
+ return outcome({ attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_all_denied', hardRejectIssues: lastIssues } });
624
826
  }
625
827
  rankReordered = applyRankOrder(elements, gate, repairs, rankContext);
626
828
  const issues = validate(elements, { gate, lane: 'triage', urgentReframed });
@@ -628,7 +830,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
628
830
  if (blocking.length) {
629
831
  lastIssues = blocking;
630
832
  if (attempt < PLAN_MAX_ATTEMPTS) continue;
631
- return { attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_invalid', hardRejectIssues: blocking } };
833
+ return outcome({ attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_invalid', hardRejectIssues: blocking } });
632
834
  }
633
835
 
634
836
  let plan;
@@ -637,9 +839,9 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
637
839
  } catch (err) {
638
840
  lastIssues = [{ path: 'plan', problem: err?.message || 'DTO inválido' }];
639
841
  if (attempt < PLAN_MAX_ATTEMPTS) continue;
640
- return { attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_invalid', hardRejectIssues: lastIssues } };
842
+ return outcome({ attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_invalid', hardRejectIssues: lastIssues } });
641
843
  }
642
- return {
844
+ return outcome({
643
845
  attempts: attempt,
644
846
  plan,
645
847
  planRepairs: repairs,
@@ -647,9 +849,9 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ra
647
849
  rankReordered,
648
850
  deniedCardsDropped,
649
851
  deniedTargetsStripped,
650
- };
852
+ });
651
853
  }
652
- return { attempts: PLAN_MAX_ATTEMPTS, failure: { status: 'failed', stage: 'plan', reason: 'plan_invalid', hardRejectIssues: lastIssues } };
854
+ return outcome({ attempts: PLAN_MAX_ATTEMPTS, failure: { status: 'failed', stage: 'plan', reason: 'plan_invalid', hardRejectIssues: lastIssues } });
653
855
  }
654
856
 
655
857
  function rawEvidence(result) {