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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +0 -21
  2. package/lib/clinical/AssistantProcessor.js +12 -156
  3. package/lib/clinical/context/ToolRuntimeContext.js +1 -39
  4. package/lib/clinical/context/turnContext.js +0 -10
  5. package/lib/clinical/models/triageRecommendationEventModel.js +0 -28
  6. package/lib/clinical/providers/BaseLLMProvider.js +5 -45
  7. package/lib/clinical/services/clinicalAirtableService.js +5 -8
  8. package/lib/clinical/services/divergenceService.js +2 -9
  9. package/lib/clinical/services/triageRecommendationService.js +251 -453
  10. package/lib/clinical/tools/deliverPatientMessageTool.js +23 -82
  11. package/lib/clinical/tools/registerClinicalTools.js +0 -2
  12. package/lib/controllers/dashboardController.js +2 -5
  13. package/lib/controllers/escalationReviewController.js +12 -0
  14. package/lib/core/BatchingManager.js +9 -20
  15. package/lib/core/NexusMessaging.js +6 -25
  16. package/lib/core/ProcessingPipeline.js +3 -32
  17. package/lib/index.d.ts +6 -334
  18. package/lib/index.js +0 -22
  19. package/lib/models/escalationReviewModel.js +4 -0
  20. package/lib/routes/index.js +2 -0
  21. package/lib/services/airtableService.js +1 -8
  22. package/lib/services/dashboardService.js +3 -30
  23. package/lib/services/escalationReviewService.js +43 -11
  24. package/package.json +1 -1
  25. package/lib/clinical/models/supportCandidateModel.js +0 -90
  26. package/lib/clinical/services/deliverySettlementService.js +0 -39
  27. package/lib/clinical/services/supportActionService.js +0 -129
  28. package/lib/clinical/services/supportCandidateService.js +0 -532
  29. package/lib/clinical/services/supportRoutingAgentService.js +0 -118
  30. package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +0 -200
  31. package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +0 -141
  32. package/lib/core/runtimeToolPolicy.js +0 -3
  33. package/lib/services/dashboard-provider-registry.js +0 -38
  34. package/lib/shared/dtos/NutritionSafetyDecision.js +0 -128
  35. package/lib/shared/dtos/SupportAction.js +0 -28
  36. package/lib/shared/dtos/SupportRoutingRecommendation.js +0 -124
@@ -1,532 +0,0 @@
1
- const { v4: uuidv4 } = require('uuid');
2
-
3
- const { getSupportCandidateModel } = require('../models/supportCandidateModel');
4
- const { SupportRoutingRecommendation } = require('../../shared/dtos/SupportRoutingRecommendation');
5
-
6
- const COOLDOWN_MS = 14 * 24 * 60 * 60 * 1000;
7
- const DELIVERY_STATUSES = ['sent', 'delivered', 'read', 'failed', 'unknown'];
8
- const INVITATION_CLASSES = ['first', 'followup'];
9
- const ENGAGEMENT_STATES = ['notInvited', 'invited', 'registered', 'attended', 'declined'];
10
- const OPERATIONAL_REASONS = ['classification_failed', 'attendance_unavailable', 'safety_unconfirmed', 'classification_safety_unconfirmed', 'invitation_claim_failed'];
11
- const OPERATIONAL_PLACEHOLDER_VERSION = 'operational-review-v1';
12
-
13
- function evidenceKey(item) {
14
- return `${item.source}:${item.sourceId}:${item.code}`;
15
- }
16
-
17
- function normalizeEvidence(items = []) {
18
- const byKey = new Map();
19
- for (const item of items) byKey.set(evidenceKey(item), { key: evidenceKey(item), ...item });
20
- return [...byKey.values()];
21
- }
22
-
23
- function initialState(decision) {
24
- return decision.disposition;
25
- }
26
-
27
- function nextState(existing, decision) {
28
- if (decision.disposition === 'escalated' || existing?.disposition === 'escalated') return 'escalated';
29
- return initialState(decision);
30
- }
31
-
32
- function candidatePatch(existing, recommendation, decision) {
33
- const priorEvidence = normalizeEvidence(existing?.evidence || []);
34
- const mergedEvidence = normalizeEvidence([...priorEvidence, ...decision.evidence]);
35
- return {
36
- disposition: nextState(existing, decision),
37
- ...(decision.disposition === 'escalated' && existing?.disposition !== 'escalated' ? {
38
- escalation: { risk: decision.psychologyRisk || decision.nutritionRisk, sourceId: recommendation.sourceId, origin: recommendation.origin, detectedAt: new Date(recommendation.createdAt), clearedAt: null },
39
- } : {}),
40
- groupEligible: decision.groupEligible,
41
- urgentIntakeEligible: decision.service === 'nutrition' ? decision.urgentIntakeEligible : false,
42
- priority: decision.priority,
43
- confidence: decision.confidence,
44
- nutritionRisk: decision.service === 'nutrition' ? decision.nutritionRisk : null,
45
- psychologyRisk: decision.service === 'psychology' ? decision.psychologyRisk : null,
46
- reasonCodes: [...new Set([...(existing?.reasonCodes || []), ...decision.reasonCodes])],
47
- evidence: mergedEvidence,
48
- sourceEventIds: [...new Set([...(existing?.sourceEventIds || []), recommendation.sourceId])],
49
- latestSourceId: recommendation.sourceId,
50
- latestOrigin: recommendation.origin,
51
- decisionVersion: recommendation.decisionVersion,
52
- lastEvaluatedAt: new Date(recommendation.createdAt),
53
- };
54
- }
55
-
56
- function isStaleRecommendation(existing, recommendation) {
57
- if (!existing?.lastEvaluatedAt || existing.decisionVersion === OPERATIONAL_PLACEHOLDER_VERSION) return false;
58
- return new Date(recommendation.createdAt).getTime() < new Date(existing.lastEvaluatedAt).getTime();
59
- }
60
-
61
- function historicalEvidencePatch(existing, recommendation, decision) {
62
- return {
63
- evidence: normalizeEvidence([...(existing?.evidence || []), ...decision.evidence]),
64
- sourceEventIds: [...new Set([...(existing?.sourceEventIds || []), recommendation.sourceId])],
65
- };
66
- }
67
-
68
- async function upsertDecision(recommendation, decision, options = {}) {
69
- const Model = options.Model || getSupportCandidateModel();
70
- const query = { patientId: recommendation.patientId, service: decision.service };
71
- for (let attempt = 0; attempt < 5; attempt += 1) {
72
- const existing = await Model.findOne(query).lean();
73
- const stale = isStaleRecommendation(existing, recommendation);
74
- const compareAndSet = existing
75
- ? {
76
- ...query,
77
- ...(existing.revision == null
78
- ? { $or: [{ revision: 0 }, { revision: { $exists: false } }] }
79
- : { revision: existing.revision }),
80
- }
81
- : { ...query, candidateId: { $exists: false } };
82
- try {
83
- const updated = await Model.findOneAndUpdate(compareAndSet, {
84
- $set: stale
85
- ? historicalEvidencePatch(existing, recommendation, decision)
86
- : candidatePatch(existing, recommendation, decision),
87
- $setOnInsert: {
88
- candidateId: uuidv4(),
89
- patientId: recommendation.patientId,
90
- service: decision.service,
91
- },
92
- $inc: { revision: 1 },
93
- }, { new: true, upsert: !existing, setDefaultsOnInsert: true });
94
- if (updated) return stale ? null : updated;
95
- } catch (error) {
96
- if (error?.code !== 11000) throw error;
97
- }
98
- }
99
- throw new Error('support candidate changed repeatedly during routing update');
100
- }
101
-
102
- async function recordSupportRoutingRecommendation(rawRecommendation, options = {}) {
103
- const recommendation = rawRecommendation instanceof SupportRoutingRecommendation
104
- ? rawRecommendation
105
- : new SupportRoutingRecommendation(rawRecommendation);
106
- const candidates = [];
107
- for (const decision of recommendation.decisions) {
108
- const candidate = await upsertDecision(recommendation, decision, options);
109
- if (candidate) candidates.push(candidate);
110
- }
111
- return candidates;
112
- }
113
-
114
- async function updateSupportOperationalReview({ patientId, service, reasonCode, sourceId, resolved = false, noClinicalDecision = false, now = new Date() }, { Model = getSupportCandidateModel() } = {}) {
115
- if (typeof patientId !== 'string' || !patientId.trim() || !['nutrition', 'psychology'].includes(service)
116
- || !OPERATIONAL_REASONS.includes(reasonCode) || typeof sourceId !== 'string' || !sourceId.trim() || sourceId.length > 256) {
117
- throw new Error('Valid support operational review identity is required');
118
- }
119
- const query = { patientId, service };
120
- for (let attempt = 0; attempt < 5; attempt += 1) {
121
- const existing = await Model.findOne(query).lean();
122
- const reviews = existing?.operationalReviews || [];
123
- const matches = (review) => review.reasonCode === reasonCode && review.sourceId === sourceId;
124
- if (resolved && !reviews.some(matches)) return existing;
125
- const updatedReviews = resolved ? reviews.filter((review) => !matches(review))
126
- : reviews.some(matches) ? reviews : [...reviews, { reasonCode, sourceId, detectedAt: new Date(now) }];
127
- const patch = { operationalReviews: updatedReviews.slice(0, 20) };
128
- if (!resolved) Object.assign(patch, {
129
- operationalReviewOverflow: existing?.operationalReviewOverflow === true || updatedReviews.length > 20,
130
- evidence: normalizeEvidence([...(existing?.evidence || []), { source: 'triage', sourceId, code: `support_operational_${reasonCode}`, summary: null, confidence: null }]),
131
- sourceEventIds: [...new Set([...(existing?.sourceEventIds || []), sourceId])],
132
- });
133
- if (resolved && noClinicalDecision && reasonCode === 'classification_failed'
134
- && existing.decisionVersion === OPERATIONAL_PLACEHOLDER_VERSION && !updatedReviews.length && !existing.operationalReviewOverflow) {
135
- patch.disposition = 'none';
136
- }
137
- const owner = existing ? { ...query, revision: existing.revision == null ? { $in: [0, null] } : existing.revision }
138
- : { ...query, candidateId: { $exists: false } };
139
- try {
140
- const updated = await Model.findOneAndUpdate(owner, {
141
- $set: patch,
142
- ...(!existing ? { $setOnInsert: {
143
- candidateId: uuidv4(), patientId, service, disposition: 'reviewRequired',
144
- // Review placeholders must remain ineligible even if the schema default changes.
145
- groupEligible: false, urgentIntakeEligible: false, confidence: 0,
146
- decisionVersion: OPERATIONAL_PLACEHOLDER_VERSION, latestSourceId: sourceId,
147
- latestOrigin: 'triage', lastEvaluatedAt: new Date(now),
148
- } } : {}),
149
- $inc: { revision: 1 },
150
- }, { new: true, upsert: !existing, setDefaultsOnInsert: true });
151
- if (updated) return updated;
152
- } catch (error) {
153
- if (error?.code !== 11000) throw error;
154
- }
155
- }
156
- throw new Error('support operational review changed repeatedly');
157
- }
158
-
159
- function requireGroupReview(reviewedRevision, reviewedRisk) {
160
- if (!Number.isInteger(reviewedRevision) || reviewedRevision < 0) throw new Error('reviewedRevision is required');
161
- if (!['green', 'yellow'].includes(reviewedRisk)) throw new Error('reviewedRisk must be safe for group approval');
162
- }
163
-
164
- function reviewedGroupPatch(service, reviewedRisk, reviewedAt) {
165
- return {
166
- disposition: service === 'nutrition' && reviewedRisk === 'yellow' ? 'individual' : 'group',
167
- groupEligible: true,
168
- specialistClearedAt: reviewedAt,
169
- [service === 'nutrition' ? 'nutritionRisk' : 'psychologyRisk']: reviewedRisk,
170
- };
171
- }
172
-
173
- async function approveCandidate(candidateId, {
174
- reviewedRevision, reviewedRisk, Model = getSupportCandidateModel(),
175
- } = {}) {
176
- requireGroupReview(reviewedRevision, reviewedRisk);
177
- const reviewedAt = new Date();
178
- const services = reviewedRisk === 'yellow' ? ['nutrition'] : ['nutrition', 'psychology'];
179
- for (const service of services) {
180
- const approved = await Model.findOneAndUpdate(
181
- { candidateId, service, disposition: 'reviewRequired', revision: reviewedRevision },
182
- { $set: reviewedGroupPatch(service, reviewedRisk, reviewedAt), $inc: { revision: 1 } },
183
- { new: true },
184
- );
185
- if (approved) return approved;
186
- }
187
- return null;
188
- }
189
-
190
- function invitationKey({ candidateId, invitationClass, invitationCycle, templateVersion }) {
191
- return `${candidateId}:${invitationClass}:${invitationCycle}:${templateVersion}`;
192
- }
193
-
194
- function claimEligibility({ candidateId, invitationClass, now }) {
195
- return {
196
- candidateId,
197
- groupEligible: true,
198
- $and: [{ $or: [
199
- { service: 'nutrition', disposition: { $in: ['group', 'individual'] } },
200
- { service: 'psychology', disposition: 'group', psychologyRisk: 'green' },
201
- ] }],
202
- activeInvitationKey: null,
203
- 'engagement.state': { $in: ['notInvited', 'invited', 'registered', 'attended'] },
204
- 'engagement.attendanceEvidenceId': invitationClass === 'followup' ? { $ne: null } : null,
205
- $or: [
206
- { 'engagement.cooldownUntil': null },
207
- { 'engagement.cooldownUntil': { $lte: now } },
208
- ],
209
- };
210
- }
211
-
212
- async function claimInvitation({ candidateId, invitationClass, invitationCycle, templateVersion, now = new Date() }, { Model = getSupportCandidateModel() } = {}) {
213
- if (!INVITATION_CLASSES.includes(invitationClass)) throw new Error(`invalid invitation class: ${invitationClass}`);
214
- if (!invitationCycle) throw new Error('invitationCycle is required');
215
- if (!templateVersion) throw new Error('templateVersion is required');
216
- const claimedAt = new Date(now);
217
- const idempotencyKey = invitationKey({ candidateId, invitationClass, invitationCycle, templateVersion });
218
- const eligibility = claimEligibility({ candidateId, invitationClass, now: claimedAt });
219
- const claimed = await Model.findOneAndUpdate({
220
- ...eligibility,
221
- 'invitationAttempts.idempotencyKey': { $ne: idempotencyKey },
222
- }, {
223
- $set: { activeInvitationKey: idempotencyKey },
224
- $push: {
225
- invitationAttempts: {
226
- idempotencyKey,
227
- invitationClass,
228
- invitationCycle,
229
- templateVersion,
230
- status: 'queued',
231
- createdAt: claimedAt,
232
- },
233
- },
234
- $inc: { revision: 1 },
235
- }, { new: true });
236
- if (claimed) return claimed;
237
- return Model.findOneAndUpdate({
238
- ...eligibility,
239
- invitationAttempts: { $elemMatch: { idempotencyKey, status: 'failed' } },
240
- }, {
241
- $set: {
242
- activeInvitationKey: idempotencyKey,
243
- 'invitationAttempts.$[attempt].status': 'queued',
244
- 'invitationAttempts.$[attempt].providerMessageId': null,
245
- 'invitationAttempts.$[attempt].error': null,
246
- 'invitationAttempts.$[attempt].createdAt': claimedAt,
247
- 'invitationAttempts.$[attempt].settledAt': null,
248
- },
249
- $inc: { revision: 1 },
250
- }, {
251
- new: true,
252
- arrayFilters: [{ 'attempt.idempotencyKey': idempotencyKey, 'attempt.status': 'failed' }],
253
- });
254
- }
255
-
256
- function attemptSettlement({ status, providerMessageId, error, now }) {
257
- return {
258
- 'invitationAttempts.$[attempt].status': status,
259
- 'invitationAttempts.$[attempt].settledAt': now,
260
- 'invitationAttempts.$[attempt].error': error,
261
- ...(providerMessageId ? { 'invitationAttempts.$[attempt].providerMessageId': providerMessageId } : {}),
262
- };
263
- }
264
-
265
- async function settleActiveAttempt({ candidateId, idempotencyKey, status, providerMessageId, error, now }, engagementStates, engagementPatch, Model) {
266
- const priorStatuses = ['queued', 'unknown'];
267
- return Model.findOneAndUpdate({
268
- candidateId,
269
- activeInvitationKey: idempotencyKey,
270
- 'engagement.state': { $in: engagementStates },
271
- invitationAttempts: { $elemMatch: { idempotencyKey, status: { $in: priorStatuses } } },
272
- }, {
273
- $set: {
274
- ...attemptSettlement({ idempotencyKey, status, providerMessageId, error, now }),
275
- ...engagementPatch,
276
- },
277
- $inc: { revision: 1 },
278
- }, {
279
- new: true,
280
- arrayFilters: [{ 'attempt.idempotencyKey': idempotencyKey, 'attempt.status': { $in: priorStatuses } }],
281
- });
282
- }
283
-
284
- async function settleFirstSuccess(args, Model) {
285
- const cooldownUntil = new Date(args.now.getTime() + COOLDOWN_MS);
286
- const deliveryPatch = {
287
- activeInvitationKey: null,
288
- cooldownInvitationKey: args.idempotencyKey,
289
- 'engagement.lastInvitedAt': args.now,
290
- 'engagement.cooldownUntil': cooldownUntil,
291
- };
292
- const invited = await settleActiveAttempt(
293
- args,
294
- ['notInvited', 'invited'],
295
- { ...deliveryPatch, 'engagement.state': 'invited' },
296
- Model,
297
- );
298
- if (invited) return invited;
299
- return settleActiveAttempt(args, ['registered', 'attended', 'declined'], deliveryPatch, Model);
300
- }
301
-
302
- async function advanceSuccessfulAttempt(args, Model) {
303
- const priorStatuses = args.status === 'delivered' ? ['sent'] : ['sent', 'delivered'];
304
- if (!['delivered', 'read'].includes(args.status)) return null;
305
- return Model.findOneAndUpdate({
306
- candidateId: args.candidateId,
307
- invitationAttempts: { $elemMatch: { idempotencyKey: args.idempotencyKey, status: { $in: priorStatuses } } },
308
- }, {
309
- $set: attemptSettlement(args),
310
- $inc: { revision: 1 },
311
- }, {
312
- new: true,
313
- arrayFilters: [{ 'attempt.idempotencyKey': args.idempotencyKey, 'attempt.status': { $in: priorStatuses } }],
314
- });
315
- }
316
-
317
- async function settleSentFailure(args, Model) {
318
- const query = {
319
- candidateId: args.candidateId,
320
- invitationAttempts: { $elemMatch: { idempotencyKey: args.idempotencyKey, status: 'sent' } },
321
- };
322
- const options = {
323
- new: true,
324
- arrayFilters: [{ 'attempt.idempotencyKey': args.idempotencyKey, 'attempt.status': 'sent' }],
325
- };
326
- const ownedCooldown = await Model.findOneAndUpdate({
327
- ...query,
328
- cooldownInvitationKey: args.idempotencyKey,
329
- }, {
330
- $set: {
331
- ...attemptSettlement(args),
332
- cooldownInvitationKey: null,
333
- 'engagement.cooldownUntil': null,
334
- },
335
- $inc: { revision: 1 },
336
- }, options);
337
- if (ownedCooldown) return ownedCooldown;
338
- return Model.findOneAndUpdate({
339
- ...query,
340
- cooldownInvitationKey: { $ne: args.idempotencyKey },
341
- }, {
342
- $set: attemptSettlement(args),
343
- $inc: { revision: 1 },
344
- }, options);
345
- }
346
-
347
- async function settleInvitation({ candidateId, idempotencyKey, status, providerMessageId = null, error = null, now = new Date() }, { Model = getSupportCandidateModel() } = {}) {
348
- if (!DELIVERY_STATUSES.includes(status)) throw new Error(`invalid invitation outcome: ${status}`);
349
- const args = { candidateId, idempotencyKey, status, providerMessageId, error, now: new Date(now) };
350
- if (status === 'unknown') {
351
- return settleActiveAttempt(args, ENGAGEMENT_STATES, {}, Model);
352
- }
353
- if (status === 'failed') {
354
- const activeFailure = await settleActiveAttempt(args, ENGAGEMENT_STATES, {
355
- activeInvitationKey: null,
356
- cooldownInvitationKey: null,
357
- 'engagement.cooldownUntil': null,
358
- }, Model);
359
- return activeFailure || settleSentFailure(args, Model);
360
- }
361
- const firstSuccess = await settleFirstSuccess(args, Model);
362
- return firstSuccess || advanceSuccessfulAttempt(args, Model);
363
- }
364
-
365
- function engagementPatch(state, evidenceId, occurredAt, preference) {
366
- const patch = { 'engagement.state': state };
367
- if (state === 'registered') {
368
- patch['engagement.registrationEvidenceId'] = evidenceId;
369
- patch['engagement.registeredAt'] = occurredAt;
370
- } else if (state === 'attended') {
371
- patch['engagement.attendanceEvidenceId'] = evidenceId;
372
- if (occurredAt != null) patch['engagement.attendedAt'] = occurredAt;
373
- } else if (state === 'declined') {
374
- patch['engagement.declineEvidenceId'] = evidenceId;
375
- patch['engagement.declinedAt'] = occurredAt;
376
- patch['engagement.declinePreference'] = preference;
377
- }
378
- return patch;
379
- }
380
-
381
- async function recordEngagement({ patientId, service, state, evidenceId = null, occurredAt = new Date(), preference = null }, { Model = getSupportCandidateModel(), historicalAttendance = false } = {}) {
382
- if (!ENGAGEMENT_STATES.includes(state)) throw new Error(`invalid engagement state: ${state}`);
383
- if (state === 'attended' && (typeof evidenceId !== 'string' || !evidenceId.trim())) {
384
- throw new Error('attendance evidenceId is required');
385
- }
386
- const allowedPriorStates = state === 'invited'
387
- ? ['notInvited', 'invited']
388
- : state === 'registered'
389
- ? ['notInvited', 'invited', 'registered']
390
- : historicalAttendance ? ENGAGEMENT_STATES.filter((prior) => prior !== 'declined') : ENGAGEMENT_STATES;
391
- return Model.findOneAndUpdate({
392
- patientId,
393
- service,
394
- 'engagement.state': { $in: allowedPriorStates },
395
- }, {
396
- $set: engagementPatch(state, evidenceId, occurredAt == null ? null : new Date(occurredAt), preference),
397
- $inc: { revision: 1 },
398
- }, { new: true });
399
- }
400
-
401
- async function markInvitedCandidateAccepted({ patientId, service, sessionId = null }, { Model = getSupportCandidateModel() } = {}) {
402
- return Model.findOneAndUpdate({
403
- patientId,
404
- service,
405
- activeInvitationKey: null,
406
- cooldownInvitationKey: null,
407
- $or: [{ invitationAttempts: { $exists: false } }, { invitationAttempts: { $size: 0 } }],
408
- 'engagement.state': { $in: ['notInvited', 'invited', 'registered'] },
409
- }, {
410
- $set: engagementPatch('registered', sessionId, new Date(), null),
411
- $inc: { revision: 1 },
412
- }, { new: true });
413
- }
414
-
415
- async function markInvitedCandidateDeclined({ patientId, service, preference = 'not_now' }, { Model = getSupportCandidateModel() } = {}) {
416
- if (!['another_date', 'not_now', 'never'].includes(preference)) throw new Error(`invalid decline preference: ${preference}`);
417
- return Model.findOneAndUpdate({
418
- patientId,
419
- service,
420
- activeInvitationKey: null,
421
- cooldownInvitationKey: null,
422
- $or: [{ invitationAttempts: { $exists: false } }, { invitationAttempts: { $size: 0 } }],
423
- 'engagement.state': { $in: ENGAGEMENT_STATES },
424
- }, {
425
- $set: engagementPatch('declined', null, new Date(), preference),
426
- $inc: { revision: 1 },
427
- }, { new: true });
428
- }
429
-
430
- async function recordLegacyInvitationResponse({ patientId, service, outcome, sessionId = null, preference = 'not_now' }, options = {}) {
431
- if (outcome === 'accepted') {
432
- if (!sessionId) throw new Error('sessionId is required for a legacy acceptance');
433
- return markInvitedCandidateAccepted({ patientId, service, sessionId }, options);
434
- }
435
- if (outcome === 'declined') return markInvitedCandidateDeclined({ patientId, service, preference }, options);
436
- throw new Error(`invalid legacy invitation outcome: ${outcome}`);
437
- }
438
-
439
- async function markCandidateAccepted(args, options = {}) {
440
- return markInvitedCandidateAccepted(args, options);
441
- }
442
-
443
- async function markCandidateDeclined(args, options = {}) {
444
- return markInvitedCandidateDeclined(args, options);
445
- }
446
-
447
- async function rescheduleDeclinedCandidate(candidateId, { Model = getSupportCandidateModel() } = {}) {
448
- return Model.findOneAndUpdate(
449
- { candidateId, 'engagement.state': 'declined', 'engagement.declinePreference': 'another_date' },
450
- {
451
- $set: { 'engagement.state': 'notInvited', 'engagement.declinePreference': null },
452
- $inc: { revision: 1 },
453
- },
454
- { new: true },
455
- );
456
- }
457
-
458
- async function clearCandidateEscalation(candidateId, {
459
- reviewedRevision, approvedForGroup = false, reviewedRisk, Model = getSupportCandidateModel(),
460
- } = {}) {
461
- if (!Number.isInteger(reviewedRevision) || reviewedRevision < 0) throw new Error('reviewedRevision is required');
462
- if (approvedForGroup) requireGroupReview(reviewedRevision, reviewedRisk);
463
- const reviewedAt = new Date();
464
- if (approvedForGroup) {
465
- const services = reviewedRisk === 'yellow' ? ['nutrition'] : ['nutrition', 'psychology'];
466
- for (const service of services) {
467
- const cleared = await Model.findOneAndUpdate(
468
- { candidateId, service, disposition: 'escalated', revision: reviewedRevision },
469
- {
470
- $set: {
471
- ...reviewedGroupPatch(service, reviewedRisk, reviewedAt),
472
- 'escalation.clearedAt': reviewedAt,
473
- },
474
- $inc: { revision: 1 },
475
- },
476
- { new: true },
477
- );
478
- if (cleared) return cleared;
479
- }
480
- return null;
481
- }
482
- return Model.findOneAndUpdate(
483
- { candidateId, disposition: 'escalated', revision: reviewedRevision },
484
- {
485
- $set: {
486
- disposition: 'reviewRequired',
487
- groupEligible: false,
488
- specialistClearedAt: reviewedAt,
489
- 'escalation.clearedAt': reviewedAt,
490
- },
491
- $inc: { revision: 1 },
492
- },
493
- { new: true },
494
- );
495
- }
496
-
497
- async function readSupportDashboardCandidates() {
498
- const rows = await getSupportCandidateModel().find({
499
- service: { $in: ['nutrition', 'psychology'] },
500
- $or: [
501
- { disposition: { $in: ['reviewRequired', 'escalated'] } },
502
- { service: 'psychology', disposition: 'individual', psychologyRisk: 'orange' },
503
- { 'operationalReviews.0': { $exists: true } },
504
- { operationalReviewOverflow: true },
505
- { invitationAttempts: { $elemMatch: { status: { $in: ['failed', 'unknown'] } } } },
506
- ],
507
- })
508
- .select('-_id candidateId patientId service disposition psychologyRisk escalation operationalReviews operationalReviewOverflow reasonCodes createdAt lastEvaluatedAt invitationAttempts.invitationCycle invitationAttempts.status invitationAttempts.createdAt')
509
- .limit(1001).maxTimeMS(10000).lean();
510
- if (rows.length > 1000) throw new Error('Support dashboard candidates incomplete');
511
- return rows;
512
- }
513
-
514
- module.exports = {
515
- updateSupportOperationalReview,
516
- readSupportDashboardCandidates,
517
- approveCandidate,
518
- candidatePatch,
519
- claimInvitation,
520
- clearCandidateEscalation,
521
- evidenceKey,
522
- initialState,
523
- markCandidateAccepted,
524
- markCandidateDeclined,
525
- nextState,
526
- normalizeEvidence,
527
- recordEngagement,
528
- recordLegacyInvitationResponse,
529
- recordSupportRoutingRecommendation,
530
- rescheduleDeclinedCandidate,
531
- settleInvitation,
532
- };
@@ -1,118 +0,0 @@
1
- const { readOutputText } = require('../helpers/clinicalMentionHelper');
2
- const { SupportRoutingRecommendation } = require('../../shared/dtos/SupportRoutingRecommendation');
3
- const { safeParse } = require('../../utils/jsonUtils');
4
-
5
- const SUPPORT_ROUTING_SCHEMA = {
6
- type: 'object',
7
- additionalProperties: false,
8
- properties: {
9
- decisions: {
10
- type: 'array',
11
- maxItems: 2,
12
- items: {
13
- type: 'object',
14
- additionalProperties: false,
15
- properties: {
16
- service: { type: 'string', enum: ['nutrition', 'psychology'] },
17
- nutritionRisk: { type: ['string', 'null'], enum: ['green', 'yellow', 'red', 'unknown', null] },
18
- psychologyRisk: { type: ['string', 'null'], enum: ['green', 'orange', 'red', 'unknown', null] },
19
- disposition: { type: 'string', enum: ['group', 'individual', 'escalated', 'reviewRequired', 'none'] },
20
- groupEligible: { type: 'boolean' },
21
- urgentIntakeEligible: { type: ['boolean', 'null'] },
22
- priority: { type: 'string', enum: ['routine', 'soon', 'urgent'] },
23
- confidence: { type: 'number', minimum: 0, maximum: 1 },
24
- reasonCodes: { type: 'array', maxItems: 20, items: { type: 'string' } },
25
- evidence: {
26
- type: 'array',
27
- minItems: 1,
28
- maxItems: 20,
29
- items: {
30
- type: 'object',
31
- additionalProperties: false,
32
- properties: {
33
- source: { type: 'string', enum: ['triage', 'chat', 'fhir', 'airtable'] },
34
- sourceId: { type: 'string' },
35
- code: { type: 'string' },
36
- summary: { type: ['string', 'null'] },
37
- confidence: { type: ['number', 'null'], minimum: 0, maximum: 1 },
38
- },
39
- required: ['source', 'sourceId', 'code', 'summary', 'confidence'],
40
- },
41
- },
42
- safety: {
43
- type: 'object',
44
- additionalProperties: false,
45
- properties: {
46
- suicidalIdeation: { type: 'boolean' },
47
- immediateRisk: { type: 'boolean' },
48
- urgentMedicalRisk: { type: 'boolean' },
49
- needsHumanConfirmation: { type: 'boolean' },
50
- },
51
- required: ['suicidalIdeation', 'immediateRisk', 'urgentMedicalRisk', 'needsHumanConfirmation'],
52
- },
53
- },
54
- required: ['service', 'nutritionRisk', 'psychologyRisk', 'disposition', 'groupEligible', 'urgentIntakeEligible', 'priority', 'confidence', 'reasonCodes', 'evidence', 'safety'],
55
- },
56
- },
57
- },
58
- required: ['decisions'],
59
- };
60
-
61
- const INSTRUCTIONS = `Eres un clasificador clínico de derivación de soporte oncológico. Evalúa únicamente evidencia explícita del caso. Devuelve como máximo una decisión por servicio y omite servicios sin señal relevante.
62
-
63
- PSICOLOGÍA — política obligatoria:
64
- - green: aceptación inicial, expresión emocional con autorregulación, expectativas realistas, participación en decisiones, red de apoyo favorecida o comunicación de necesidades. disposition=group y groupEligible=true.
65
- - orange: ansiedad/miedo a progresión, llanto intermitente, evitación parcial, alteración de autoimagen/identidad/rol, irritabilidad/hipervigilancia, dificultad para hablar del futuro, deficiencia parcial en red de apoyo o cansancio de “ser fuerte”. disposition=individual y groupEligible=false.
66
- - red: llanto descontrolado, desesperanza/discurso catastrófico, pérdida de interés en continuar tratamiento, enojo/culpa intensa o ideación/plan suicida. disposition=escalated y groupEligible=false.
67
- - unknown: información insuficiente o contradictoria. disposition=reviewRequired y groupEligible=false. Nunca infieras bienestar por ausencia de datos.
68
- Clasifica según la señal de mayor riesgo observada: red prevalece sobre orange y green; orange prevalece sobre green.
69
- Ideación suicida o riesgo inmediato siempre implica psychologyRisk=red, priority=urgent y disposition=escalated.
70
-
71
- NUTRICIÓN:
72
- - Señales pertinentes incluyen baja ingesta/apetito, pérdida de peso, disfagia, lesiones orales, alteración del gusto, náusea/vómito, diarrea, estreñimiento, reflujo o dolor abdominal.
73
- - green: señal actual, manejable y educativa; disposition=group, groupEligible=true y urgentIntakeEligible=false.
74
- - yellow: requiere resolución individual, pero sin riesgo médico urgente; disposition=individual y urgentIntakeEligible=true. groupEligible es independiente y puede ser true cuando también corresponde una indicación grupal.
75
- - red con riesgo médico urgente: disposition=escalated, groupEligible=false y urgentIntakeEligible=false.
76
- - unknown: evidencia insuficiente; disposition=reviewRequired, groupEligible=false y urgentIntakeEligible=false.
77
- Clasifica según la señal de mayor riesgo observada. Los factores clínicos de base elevan prioridad, pero solos no crean necesidad actual.
78
-
79
- Cada evidencia debe apuntar al sourceId recibido. No diagnostiques. No copies texto sensible innecesario: usa un resumen breve y reasonCodes estables en snake_case.`;
80
-
81
- function normalizeDecision(decision, origin, sourceId) {
82
- const normalized = {
83
- ...decision,
84
- evidence: decision.evidence.map((item) => ({ ...item, source: origin, sourceId })),
85
- };
86
- if (decision.service === 'nutrition') {
87
- delete normalized.psychologyRisk;
88
- } else {
89
- delete normalized.nutritionRisk;
90
- delete normalized.urgentIntakeEligible;
91
- }
92
- return normalized;
93
- }
94
-
95
- async function evaluateSupportRouting({ provider, patientId, origin, sourceId, context, createdAt = new Date().toISOString() }) {
96
- if (!provider?.runStructured) throw new Error('support routing provider unavailable');
97
- const result = await provider.runStructured({
98
- instructions: INSTRUCTIONS,
99
- input: [{ role: 'user', content: JSON.stringify({ origin, sourceId, context }) }],
100
- text: { format: { type: 'json_schema', name: 'support_routing', strict: true, schema: SUPPORT_ROUTING_SCHEMA } },
101
- metadata: { subAgent: 'support-routing', sourceId },
102
- });
103
- const parsed = safeParse(readOutputText(result), null);
104
- if (!parsed || !Array.isArray(parsed.decisions)) throw new Error('support routing response malformed');
105
- return new SupportRoutingRecommendation({
106
- patientId,
107
- origin,
108
- sourceId,
109
- createdAt,
110
- decisions: parsed.decisions.map((decision) => normalizeDecision(decision, origin, sourceId)),
111
- });
112
- }
113
-
114
- module.exports = {
115
- INSTRUCTIONS,
116
- SUPPORT_ROUTING_SCHEMA,
117
- evaluateSupportRouting,
118
- };