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

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.
@@ -67,7 +67,6 @@ const triageRecommendationEventSchema = new mongoose.Schema({
67
67
  default: [],
68
68
  },
69
69
  supportPendingCandidateIds: { type: [String], default: [] },
70
- supportActionMirrorRecordId: { type: String, default: null },
71
70
  supportMirrorRecordIds: { type: [String], default: [] },
72
71
  supportActionError: { type: String, default: null },
73
72
  supportPendingSettlements: {
@@ -16,9 +16,9 @@ const { logger } = require('../../utils/logger');
16
16
  const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
17
17
  const { isJsonBlob } = require('../../utils/formatUtils');
18
18
  const { isPlainObject } = require('../../utils/jsonUtils');
19
+ const { MAX_ADDITIONAL_TOOL_IDS } = require('../../core/runtimeToolPolicy');
19
20
 
20
21
  const CONSUMER_SIGNALS_KEY = 'consumer';
21
- const MAX_ADDITIONAL_TOOL_IDS = 8;
22
22
 
23
23
  const { getToolSchemas: getRegistrySchemas } = require('../../services/toolRegistryService');
24
24
  const { getMessages } = require('../../services/messageService');
@@ -103,6 +103,7 @@ async function prepareSupportAction({ patientId, sourceId, candidates = [], reso
103
103
  templateVersion: TEMPLATE_VERSION,
104
104
  now,
105
105
  }, options);
106
+ if (!claimed) continue;
106
107
  await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'attendance_unavailable', resolved: true }, options);
107
108
  await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'invitation_claim_failed', resolved: true }, options);
108
109
  } catch (error) {
@@ -110,7 +111,6 @@ async function prepareSupportAction({ patientId, sourceId, candidates = [], reso
110
111
  await updateActionReview({ patientId, service: candidate.service, sourceId, reasonCode: 'invitation_claim_failed' }, options);
111
112
  continue;
112
113
  }
113
- if (!claimed) continue;
114
114
  claimedActions.push({
115
115
  candidateId: candidate.candidateId,
116
116
  service: candidate.service,
@@ -53,11 +53,24 @@ function candidatePatch(existing, recommendation, decision) {
53
53
  };
54
54
  }
55
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
+
56
68
  async function upsertDecision(recommendation, decision, options = {}) {
57
69
  const Model = options.Model || getSupportCandidateModel();
58
70
  const query = { patientId: recommendation.patientId, service: decision.service };
59
71
  for (let attempt = 0; attempt < 5; attempt += 1) {
60
72
  const existing = await Model.findOne(query).lean();
73
+ const stale = isStaleRecommendation(existing, recommendation);
61
74
  const compareAndSet = existing
62
75
  ? {
63
76
  ...query,
@@ -68,7 +81,9 @@ async function upsertDecision(recommendation, decision, options = {}) {
68
81
  : { ...query, candidateId: { $exists: false } };
69
82
  try {
70
83
  const updated = await Model.findOneAndUpdate(compareAndSet, {
71
- $set: candidatePatch(existing, recommendation, decision),
84
+ $set: stale
85
+ ? historicalEvidencePatch(existing, recommendation, decision)
86
+ : candidatePatch(existing, recommendation, decision),
72
87
  $setOnInsert: {
73
88
  candidateId: uuidv4(),
74
89
  patientId: recommendation.patientId,
@@ -76,7 +91,7 @@ async function upsertDecision(recommendation, decision, options = {}) {
76
91
  },
77
92
  $inc: { revision: 1 },
78
93
  }, { new: true, upsert: !existing, setDefaultsOnInsert: true });
79
- if (updated) return updated;
94
+ if (updated) return stale ? null : updated;
80
95
  } catch (error) {
81
96
  if (error?.code !== 11000) throw error;
82
97
  }
@@ -90,7 +105,8 @@ async function recordSupportRoutingRecommendation(rawRecommendation, options = {
90
105
  : new SupportRoutingRecommendation(rawRecommendation);
91
106
  const candidates = [];
92
107
  for (const decision of recommendation.decisions) {
93
- candidates.push(await upsertDecision(recommendation, decision, options));
108
+ const candidate = await upsertDecision(recommendation, decision, options);
109
+ if (candidate) candidates.push(candidate);
94
110
  }
95
111
  return candidates;
96
112
  }
@@ -125,6 +141,7 @@ async function updateSupportOperationalReview({ patientId, service, reasonCode,
125
141
  $set: patch,
126
142
  ...(!existing ? { $setOnInsert: {
127
143
  candidateId: uuidv4(), patientId, service, disposition: 'reviewRequired',
144
+ // Review placeholders must remain ineligible even if the schema default changes.
128
145
  groupEligible: false, urgentIntakeEligible: false, confidence: 0,
129
146
  decisionVersion: OPERATIONAL_PLACEHOLDER_VERSION, latestSourceId: sourceId,
130
147
  latestOrigin: 'triage', lastEvaluatedAt: new Date(now),
@@ -139,12 +156,35 @@ async function updateSupportOperationalReview({ patientId, service, reasonCode,
139
156
  throw new Error('support operational review changed repeatedly');
140
157
  }
141
158
 
142
- async function approveCandidate(candidateId, { Model = getSupportCandidateModel() } = {}) {
143
- return Model.findOneAndUpdate(
144
- { candidateId, disposition: 'reviewRequired' },
145
- { $set: { disposition: 'group', groupEligible: true }, $inc: { revision: 1 } },
146
- { new: true },
147
- );
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;
148
188
  }
149
189
 
150
190
  function invitationKey({ candidateId, invitationClass, invitationCycle, templateVersion }) {
@@ -415,16 +455,38 @@ async function rescheduleDeclinedCandidate(candidateId, { Model = getSupportCand
415
455
  );
416
456
  }
417
457
 
418
- async function clearCandidateEscalation(candidateId, { reviewedRevision, approvedForGroup = false, Model = getSupportCandidateModel() } = {}) {
458
+ async function clearCandidateEscalation(candidateId, {
459
+ reviewedRevision, approvedForGroup = false, reviewedRisk, Model = getSupportCandidateModel(),
460
+ } = {}) {
419
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
+ }
420
482
  return Model.findOneAndUpdate(
421
483
  { candidateId, disposition: 'escalated', revision: reviewedRevision },
422
484
  {
423
485
  $set: {
424
- disposition: approvedForGroup ? 'group' : 'reviewRequired',
425
- groupEligible: approvedForGroup,
426
- specialistClearedAt: new Date(),
427
- 'escalation.clearedAt': new Date(),
486
+ disposition: 'reviewRequired',
487
+ groupEligible: false,
488
+ specialistClearedAt: reviewedAt,
489
+ 'escalation.clearedAt': reviewedAt,
428
490
  },
429
491
  $inc: { revision: 1 },
430
492
  },
@@ -202,12 +202,10 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
202
202
  settle.supportMirroredActions = mirroredActions;
203
203
  settle.supportPendingCandidateIds = priorSupport?.supportPendingCandidateIds
204
204
  || support.audit.supportDeliveryCandidateIds.filter((id) => !mirroredGroupIds.includes(id));
205
- settle.supportMirrorRecordIds = [...(priorSupport?.supportMirrorRecordIds
206
- || (priorSupport?.supportActionMirrorRecordId ? [priorSupport.supportActionMirrorRecordId] : []))];
205
+ settle.supportMirrorRecordIds = [...(priorSupport?.supportMirrorRecordIds || [])];
207
206
  }
208
207
  if (priorSupport?.supportAction) settle.supportAction = priorSupport.supportAction;
209
208
  if (priorSupport?.supportActionMirrored) settle.supportActionMirrored = true;
210
- if (priorSupport?.supportActionMirrorRecordId) settle.supportActionMirrorRecordId = priorSupport.supportActionMirrorRecordId;
211
209
  if (priorSupport?.supportActionMirrorUnknown) settle.supportActionMirrorUnknown = true;
212
210
  if (priorSupport?.supportPendingSettlements?.length) {
213
211
  const recovery = await settleSupportClaims(priorSupport.supportPendingSettlements);
@@ -280,7 +278,6 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
280
278
  if (mirror.ok && pendingAction) {
281
279
  mirroredActions.push(...pendingAction.actions.map(({ candidateId, type }) => ({ candidateId, type })));
282
280
  settle.supportPendingCandidateIds = remainingSupportCandidates(candidates, mirroredActions).map((candidate) => candidate.candidateId);
283
- settle.supportActionMirrorRecordId = mirror.recordId;
284
281
  }
285
282
  if (!mirror.ok) {
286
283
  settle.mirrorError = 'write_failed';
@@ -81,19 +81,39 @@ function normalizedDecision(raw, turnId) {
81
81
  : { ...common, psychologyRisk: raw.psychologyRisk || 'unknown' };
82
82
  }
83
83
 
84
+ function inactiveTurn() {
85
+ return JSON.stringify({ success: false, error: 'support_routing_turn_inactive', data: {} });
86
+ }
87
+
88
+ function isRuntimeLive(runtime) {
89
+ if (typeof runtime?.isLive !== 'function') return false;
90
+ try {
91
+ return runtime.isLive() === true;
92
+ } catch {
93
+ return false;
94
+ }
95
+ }
96
+
84
97
  async function handler(args = {}, context = {}) {
85
98
  const runtime = context?.toolRuntimeContext;
86
- if (!runtime?.turnId || !runtime?.patientCode) {
87
- return JSON.stringify({ success: false, error: 'submitSupportRoutingRecommendation requires an active turn context.', data: {} });
99
+ if (!runtime?.turnId || !runtime?.patientCode || runtime.turnKind !== 'patient') {
100
+ return inactiveTurn();
101
+ }
102
+ if (!isRuntimeLive(runtime)) {
103
+ return inactiveTurn();
88
104
  }
89
105
  try {
106
+ const observedAt = runtime.patientInput?.observedAt;
90
107
  const recommendation = new SupportRoutingRecommendation({
91
108
  patientId: runtime.patientCode,
92
109
  origin: 'chat',
93
110
  sourceId: runtime.turnId,
94
- createdAt: new Date().toISOString(),
111
+ createdAt: typeof observedAt === 'string' && !Number.isNaN(new Date(observedAt).getTime())
112
+ ? new Date(observedAt).toISOString()
113
+ : new Date().toISOString(),
95
114
  decisions: (args.decisions || []).map((decision) => normalizedDecision(decision, runtime.turnId)),
96
115
  });
116
+ if (!isRuntimeLive(runtime)) return inactiveTurn();
97
117
  const candidates = await recordSupportRoutingRecommendation(recommendation);
98
118
  runtime.trace?.setSignals?.({
99
119
  supportRouting: { candidateIds: candidates.map((candidate) => candidate.candidateId), services: recommendation.decisions.map((d) => d.service) },
@@ -1,9 +1,9 @@
1
1
  const { isPlainObject } = require('../utils/jsonUtils');
2
2
  const { describeThrown } = require('../utils/errorUtils');
3
3
  const { logger } = require('../utils/logger');
4
+ const { MAX_ADDITIONAL_TOOL_IDS } = require('./runtimeToolPolicy');
4
5
 
5
6
  const VALID_HOOKS = ['preProcess', 'postProcess'];
6
- const MAX_ADDITIONAL_TOOL_IDS = 8;
7
7
 
8
8
  class ProcessingPipeline {
9
9
  constructor(hooks = {}) {
@@ -0,0 +1,3 @@
1
+ const MAX_ADDITIONAL_TOOL_IDS = 8;
2
+
3
+ module.exports = { MAX_ADDITIONAL_TOOL_IDS };
package/lib/index.d.ts CHANGED
@@ -802,7 +802,11 @@ declare module '@peopl-health/nexus' {
802
802
  now?: Date;
803
803
  }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
804
804
  readSupportDashboardCandidates(): Promise<SupportDashboardCandidateRecord[]>;
805
- approveCandidate(candidateId: string, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
805
+ approveCandidate(candidateId: string, options: {
806
+ reviewedRevision: number;
807
+ reviewedRisk: 'green' | 'yellow';
808
+ Model?: unknown;
809
+ }): Promise<SupportCandidateRecord | null>;
806
810
  candidatePatch(existing: SupportCandidateRecord | null | undefined, recommendation: SupportRoutingRecommendationInput, decision: SupportRoutingDecisionInput): Partial<SupportCandidateRecord>;
807
811
  claimInvitation(request: {
808
812
  candidateId: string;
@@ -811,7 +815,12 @@ declare module '@peopl-health/nexus' {
811
815
  templateVersion: string;
812
816
  now?: Date;
813
817
  }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
814
- clearCandidateEscalation(candidateId: string, options: { reviewedRevision: number; approvedForGroup?: boolean; Model?: unknown }): Promise<SupportCandidateRecord | null>;
818
+ clearCandidateEscalation(candidateId: string, options: {
819
+ reviewedRevision: number;
820
+ approvedForGroup?: boolean;
821
+ reviewedRisk?: 'green' | 'yellow';
822
+ Model?: unknown;
823
+ }): Promise<SupportCandidateRecord | null>;
815
824
  evidenceKey(item: Pick<SupportEvidence, 'source' | 'sourceId' | 'code'>): string;
816
825
  initialState(decision: SupportRoutingDecisionInput): SupportDisposition;
817
826
  markCandidateAccepted(request: { patientId: string; service: SupportService; sessionId?: string | null }, options?: { Model?: unknown }): Promise<SupportCandidateRecord | null>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.51.0-dev.7627",
3
+ "version": "5.51.0-dev.7631",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",