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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 -142
  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
@@ -6,6 +6,7 @@ const { logger } = require('../utils/logger');
6
6
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
7
7
  const {
8
8
  CALL_OUTCOMES,
9
+ CANCELLABLE_STATUSES,
9
10
  DECISION_SOURCES,
10
11
  DOCTOR_DECISIONS,
11
12
  HANDOFF_MODES,
@@ -109,9 +110,10 @@ const releaseReview = (id, from, to, claim = null) => getEscalationReview().upda
109
110
  // The record of a message that really went out is never gated on status: the operator may have
110
111
  // adjudicated the review while the send was still running. Only the status transition is gated,
111
112
  // so a closed review keeps its handoff or delivery without being resurrected.
112
- async function completeOperation(id, claim, fromStatus, recordUpdate, nextStatus) {
113
+ async function completeOperation(id, claim, fromStatus, recordUpdate, nextStatus, lateUpdate = recordUpdate) {
113
114
  const EscalationReview = getEscalationReview();
114
- const record = { ...recordUpdate, $set: { ...recordUpdate.$set, operationClaim: null } };
115
+ const claimCleared = (update) => ({ ...update, $set: { ...update.$set, operationClaim: null } });
116
+ const record = claimCleared(recordUpdate);
115
117
  const settled = await EscalationReview.findOneAndUpdate(
116
118
  { _id: id, status: fromStatus, operationClaim: claim },
117
119
  { ...record, $set: { ...record.$set, status: nextStatus } },
@@ -121,7 +123,7 @@ async function completeOperation(id, claim, fromStatus, recordUpdate, nextStatus
121
123
 
122
124
  const recorded = await EscalationReview.findOneAndUpdate(
123
125
  { _id: id, operationClaim: claim },
124
- record,
126
+ claimCleared(lateUpdate),
125
127
  { new: true },
126
128
  ).lean();
127
129
  if (recorded) {
@@ -247,6 +249,24 @@ const deliveryTransport = (message, result) => {
247
249
  return result.deferred ? 'template_recovery' : 'text';
248
250
  };
249
251
 
252
+ let indexesReady = new WeakMap();
253
+
254
+ function ensureActiveReviewIndex(EscalationReview) {
255
+ const pending = indexesReady.get(EscalationReview);
256
+ if (pending) return pending;
257
+
258
+ const building = EscalationReview.ensureIndexes().catch((error) => {
259
+ indexesReady.delete(EscalationReview);
260
+ if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
261
+ logger.error('[EscalationReview] A uniqueness index could not be built', { error: redactedError(error) });
262
+ throw httpError(409, 'Escalation reviews cannot be opened: a uniqueness index could not be built. The server log names the index and the conflict; resolve it and retry.');
263
+ });
264
+ indexesReady.set(EscalationReview, building);
265
+ return building;
266
+ }
267
+
268
+ const _resetEscalationReviewIndexes = () => { indexesReady = new WeakMap(); };
269
+
250
270
  async function openEscalationReview({ code, patientCaseRecordId = null, openedBy, requestId = null } = {}) {
251
271
  const patientCode = patientCodeOf(code);
252
272
  const operator = requiredText(openedBy, 'openedBy');
@@ -263,14 +283,14 @@ async function openEscalationReview({ code, patientCaseRecordId = null, openedBy
263
283
  }
264
284
 
265
285
  const EscalationReview = getEscalationReview();
266
- await EscalationReview.init();
286
+ await ensureActiveReviewIndex(EscalationReview);
267
287
  let review;
268
288
  try {
269
289
  review = (await EscalationReview.create(fields)).toObject();
270
290
  } catch (error) {
271
- if (error?.code !== DUPLICATE_KEY_ERROR || !fields.activeCaseKey) throw error;
272
- const existing = await EscalationReview.findOne({ activeCaseKey: fields.activeCaseKey }).lean();
273
- if (!existing) throw httpError(409, 'The patient case review changed while opening; try again');
291
+ if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
292
+ const existing = await EscalationReview.findOne({ patientCode, closedAt: null }).lean();
293
+ if (!existing) throw httpError(409, 'A closed review still holds this patient case; try again in a moment');
274
294
  return { review: existing, created: false };
275
295
  }
276
296
  await audit(review, operator, requestId, { action: 'opened', patientCaseRecordId });
@@ -373,10 +393,9 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
373
393
  let updated;
374
394
  try {
375
395
  if (approver) delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ review, draft, approver, operator })) };
376
- const recordUpdate = withCaseMirror(review, {
377
- $push: { doctorHandoffs: { mode, draftNumber, ...delivery, sentBy: operator } },
378
- }, { status: 'en revision_medica' });
379
- updated = await completeOperation(reviewId, claim, 'handing_off', recordUpdate, 'awaiting_doctor');
396
+ const handoff = { $push: { doctorHandoffs: { mode, draftNumber, ...delivery, sentBy: operator } } };
397
+ const recordUpdate = withCaseMirror(review, handoff, { status: 'en revision_medica' });
398
+ updated = await completeOperation(reviewId, claim, 'handing_off', recordUpdate, 'awaiting_doctor', handoff);
380
399
  } catch (error) {
381
400
  await releaseReview(reviewId, 'handing_off', review.status, claim);
382
401
  throw error;
@@ -524,6 +543,17 @@ async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false,
524
543
  return syncCase(review, operator, requestId);
525
544
  }
526
545
 
546
+ async function cancelEscalationReview({ id, cancelledBy, reason = null, requestId = null } = {}) {
547
+ const reviewId = reviewIdOf(id);
548
+ const operator = requiredText(cancelledBy, 'cancelledBy');
549
+ const review = await updateReview(reviewId, CANCELLABLE_STATUSES, {
550
+ $set: { status: 'cancelled', closedBy: operator, closedAt: new Date() },
551
+ $unset: { activeCaseKey: '' },
552
+ });
553
+ await audit(review, operator, requestId, { action: 'cancelled', reason: optionalText(reason) });
554
+ return review;
555
+ }
556
+
527
557
  async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {}) {
528
558
  const reviewId = reviewIdOf(id);
529
559
  const operator = requiredText(syncedBy, 'syncedBy');
@@ -531,8 +561,10 @@ async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {})
531
561
  }
532
562
 
533
563
  module.exports = {
564
+ _resetEscalationReviewIndexes,
534
565
  addCallLog,
535
566
  addDraft,
567
+ cancelEscalationReview,
536
568
  closeEscalationReview,
537
569
  getEscalationReviewById,
538
570
  handOffToDoctor,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.51.0-dev.7632",
3
+ "version": "5.51.0-dev.7633",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,90 +0,0 @@
1
- const mongoose = require('mongoose');
2
-
3
- const { clinicalConnection } = require('../config/connection');
4
-
5
- const evidenceSchema = new mongoose.Schema({
6
- key: { type: String, required: true },
7
- source: { type: String, required: true, enum: ['triage', 'chat', 'fhir', 'airtable'] },
8
- sourceId: { type: String, required: true },
9
- code: { type: String, required: true },
10
- summary: { type: String, default: null },
11
- confidence: { type: Number, default: null },
12
- }, { _id: false });
13
-
14
- const invitationAttemptSchema = new mongoose.Schema({
15
- idempotencyKey: { type: String, required: true },
16
- invitationClass: { type: String, required: true, enum: ['first', 'followup'] },
17
- invitationCycle: { type: String, required: true },
18
- templateVersion: { type: String, required: true },
19
- status: { type: String, enum: ['queued', 'sent', 'delivered', 'read', 'failed', 'unknown'], default: 'queued' },
20
- providerMessageId: { type: String, default: null },
21
- error: { type: String, default: null },
22
- createdAt: { type: Date, default: Date.now },
23
- settledAt: { type: Date, default: null },
24
- }, { _id: false });
25
-
26
- const supportCandidateSchema = new mongoose.Schema({
27
- candidateId: { type: String, required: true, unique: true },
28
- patientId: { type: String, required: true },
29
- service: { type: String, required: true, enum: ['nutrition', 'psychology'] },
30
- disposition: {
31
- type: String,
32
- required: true,
33
- enum: ['group', 'individual', 'escalated', 'reviewRequired', 'none'],
34
- },
35
- engagement: {
36
- state: { type: String, enum: ['notInvited', 'invited', 'registered', 'attended', 'declined'], default: 'notInvited' },
37
- lastInvitedAt: { type: Date, default: null },
38
- cooldownUntil: { type: Date, default: null },
39
- registrationEvidenceId: { type: String, default: null },
40
- registeredAt: { type: Date, default: null },
41
- attendanceEvidenceId: { type: String, default: null },
42
- attendedAt: { type: Date, default: null },
43
- declineEvidenceId: { type: String, default: null },
44
- declinedAt: { type: Date, default: null },
45
- declinePreference: { type: String, enum: [null, 'another_date', 'not_now', 'never'], default: null },
46
- },
47
- groupEligible: { type: Boolean, required: true },
48
- urgentIntakeEligible: { type: Boolean, default: false },
49
- priority: { type: String, enum: ['routine', 'soon', 'urgent'], default: 'routine' },
50
- confidence: { type: Number, required: true },
51
- nutritionRisk: { type: String, default: null },
52
- psychologyRisk: { type: String, default: null },
53
- reasonCodes: { type: [String], default: [] },
54
- operationalReviews: { type: [new mongoose.Schema({
55
- reasonCode: { type: String, required: true, enum: ['classification_failed', 'attendance_unavailable', 'safety_unconfirmed', 'classification_safety_unconfirmed', 'invitation_claim_failed'] },
56
- sourceId: { type: String, required: true, maxlength: 256 },
57
- detectedAt: { type: Date, required: true },
58
- }, { _id: false })], default: [] },
59
- operationalReviewOverflow: { type: Boolean, default: false },
60
- evidence: { type: [evidenceSchema], default: [] },
61
- sourceEventIds: { type: [String], default: [] },
62
- latestSourceId: { type: String, required: true },
63
- latestOrigin: { type: String, required: true },
64
- decisionVersion: { type: String, required: true },
65
- invitationAttempts: { type: [invitationAttemptSchema], default: [] },
66
- activeInvitationKey: { type: String, default: null },
67
- cooldownInvitationKey: { type: String, default: null },
68
- specialistClearedAt: { type: Date, default: null },
69
- escalation: {
70
- risk: { type: String, default: null },
71
- sourceId: { type: String, default: null },
72
- origin: { type: String, default: null },
73
- detectedAt: { type: Date, default: null },
74
- clearedAt: { type: Date, default: null },
75
- },
76
- revision: { type: Number, default: 0 },
77
- lastEvaluatedAt: { type: Date, required: true },
78
- }, { timestamps: true });
79
-
80
- supportCandidateSchema.index({ patientId: 1, service: 1 }, { unique: true, name: 'one_support_candidate_per_service' });
81
- supportCandidateSchema.index({ disposition: 1, service: 1, priority: 1, updatedAt: -1 });
82
- supportCandidateSchema.index({ 'invitationAttempts.idempotencyKey': 1 }, { sparse: true });
83
-
84
- function getSupportCandidateModel() {
85
- const conn = clinicalConnection();
86
- return conn.models.SupportCandidate
87
- || conn.model('SupportCandidate', supportCandidateSchema, 'supportCandidates');
88
- }
89
-
90
- module.exports = { getSupportCandidateModel, supportCandidateSchema };
@@ -1,39 +0,0 @@
1
- const { logger } = require('../../utils/logger');
2
-
3
- const DELIVERY_OUTCOMES = new Set(['sent', 'known_not_sent', 'unknown']);
4
-
5
- async function settleClaimedDelivery({
6
- directive,
7
- settleDelivery,
8
- outcome,
9
- providerMessageId = null,
10
- patientCode,
11
- turnId = null,
12
- traceId = null,
13
- }) {
14
- if (!directive?.claimed || directive.settled || !DELIVERY_OUTCOMES.has(outcome)
15
- || typeof settleDelivery !== 'function') return false;
16
-
17
- const accepted = await settleDelivery({
18
- operationId: directive.operationId,
19
- outcome,
20
- providerMessageId: typeof providerMessageId === 'string' && providerMessageId
21
- ? providerMessageId
22
- : null,
23
- patientCode,
24
- turnId,
25
- traceId,
26
- });
27
- if (accepted === false) {
28
- logger.warn('[deliverySettlement] repository rejected settlement', {
29
- operationId: directive.operationId,
30
- outcome,
31
- });
32
- return false;
33
- }
34
- directive.settled = true;
35
- if (outcome === 'known_not_sent') directive.claimed = false;
36
- return true;
37
- }
38
-
39
- module.exports = { settleClaimedDelivery };
@@ -1,129 +0,0 @@
1
- const { SupportAction } = require('../../shared/dtos/SupportAction');
2
- const { logger } = require('../../utils/logger');
3
- const { claimInvitation, recordEngagement, updateSupportOperationalReview } = require('./supportCandidateService');
4
-
5
- const TEMPLATE_VERSION = 'support-card-v1';
6
- const URGENT_NUTRITION_TARGET = 'nutrition.urgent_intake';
7
-
8
- function isSafeGroupCandidate(candidate) {
9
- if (!candidate.groupEligible) return false;
10
- return candidate.service === 'nutrition'
11
- ? (candidate.nutritionRisk === 'green' && candidate.disposition === 'group')
12
- || (candidate.nutritionRisk === 'yellow' && candidate.disposition === 'individual')
13
- : candidate.disposition === 'group' && candidate.psychologyRisk === 'green';
14
- }
15
-
16
- function isUrgentNutritionCandidate(candidate) {
17
- return candidate.service === 'nutrition'
18
- && candidate.nutritionRisk === 'yellow'
19
- && candidate.urgentIntakeEligible === true
20
- && candidate.disposition === 'individual';
21
- }
22
-
23
- function groupContextFor(candidate, deliveryContext) {
24
- const invitationClass = deliveryContext?.invitationClassByService?.[candidate.service];
25
- const targetKey = deliveryContext?.targetKeyByService?.[candidate.service];
26
- if (!['first', 'followup'].includes(invitationClass)) return null;
27
- if (typeof targetKey !== 'string' || !targetKey.trim()) return null;
28
- return { invitationClass, targetKey };
29
- }
30
-
31
- function urgentNutritionAction(candidate) {
32
- return {
33
- candidateId: candidate.candidateId,
34
- service: 'nutrition',
35
- type: 'urgent_nutrition_intake',
36
- invitationClass: null,
37
- targetKey: URGENT_NUTRITION_TARGET,
38
- priority: candidate.priority,
39
- };
40
- }
41
-
42
- async function updateActionReview(review, options) {
43
- try {
44
- await updateSupportOperationalReview(review, options);
45
- } catch (_error) {
46
- logger.warn('[supportAction] review persistence failed', { sourceId: review.sourceId, service: review.service, reasonCode: review.reasonCode });
47
- }
48
- }
49
-
50
- async function prepareSupportAction({ patientId, sourceId, candidates = [], resolveDeliveryContext, now = new Date() }, options = {}) {
51
- const patientCandidates = candidates.filter((candidate) => candidate.patientId === patientId);
52
- const urgentActions = patientCandidates
53
- .filter(isUrgentNutritionCandidate)
54
- .map(urgentNutritionAction);
55
- const groupCandidates = patientCandidates.filter(isSafeGroupCandidate);
56
-
57
- if (!groupCandidates.length) {
58
- return urgentActions.length
59
- ? new SupportAction({ schemaVersion: '1', patientId, sourceId, actions: urgentActions })
60
- : null;
61
- }
62
-
63
- let deliveryContext;
64
- try {
65
- deliveryContext = await resolveDeliveryContext({ patientId, candidates: groupCandidates });
66
- } catch (_error) {
67
- for (const candidate of groupCandidates) await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'attendance_unavailable' }, options);
68
- return urgentActions.length
69
- ? new SupportAction({ schemaVersion: '1', patientId, sourceId, actions: urgentActions })
70
- : null;
71
- }
72
-
73
- const claimedActions = [];
74
- const invitationCycle = new Date(now).toISOString().slice(0, 10);
75
- for (const candidate of groupCandidates) {
76
- const context = groupContextFor(candidate, deliveryContext);
77
- if (!context) {
78
- await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'attendance_unavailable' }, options);
79
- continue;
80
- }
81
- let claimed;
82
- try {
83
- const evidence = deliveryContext.attendanceEvidenceByService?.[candidate.service];
84
- if (context.invitationClass === 'followup') {
85
- if (!evidence || evidence.patientId !== patientId || evidence.service !== candidate.service
86
- || typeof evidence.evidenceId !== 'string' || !evidence.evidenceId.trim()) {
87
- await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'attendance_unavailable' }, options);
88
- continue;
89
- }
90
- const recorded = await recordEngagement({
91
- patientId, service: candidate.service, state: 'attended',
92
- evidenceId: evidence.evidenceId, occurredAt: null,
93
- }, { ...options, historicalAttendance: true });
94
- if (!recorded) {
95
- await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'attendance_unavailable' }, options);
96
- continue;
97
- }
98
- }
99
- claimed = await claimInvitation({
100
- candidateId: candidate.candidateId,
101
- invitationClass: context.invitationClass,
102
- invitationCycle,
103
- templateVersion: TEMPLATE_VERSION,
104
- now,
105
- }, options);
106
- if (!claimed) continue;
107
- await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'attendance_unavailable', resolved: true }, options);
108
- await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'invitation_claim_failed', resolved: true }, options);
109
- } catch (error) {
110
- logger.warn('[supportAction] invitation claim failed', { candidateId: candidate.candidateId, error: error?.message });
111
- await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'invitation_claim_failed' }, options);
112
- continue;
113
- }
114
- claimedActions.push({
115
- candidateId: candidate.candidateId,
116
- service: candidate.service,
117
- type: 'group_registration',
118
- invitationClass: context.invitationClass,
119
- idempotencyKey: claimed.activeInvitationKey,
120
- targetKey: context.targetKey,
121
- priority: candidate.priority,
122
- });
123
- }
124
-
125
- const actions = [...urgentActions, ...claimedActions];
126
- return actions.length ? new SupportAction({ schemaVersion: '1', patientId, sourceId, actions }) : null;
127
- }
128
-
129
- module.exports = { prepareSupportAction };