@peopl-health/nexus 5.51.0-dev.7608 → 5.51.0-dev.7630

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