@peopl-health/nexus 5.61.0-dev.11181 → 5.61.0-dev.11184

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.
@@ -26,7 +26,6 @@ class TwilioMessageAdapter extends MessageAdapter {
26
26
  processed: false,
27
27
  pushName: rawMessage.ProfileName || null,
28
28
  body,
29
- normalizedContent: contactBody ? { type: 'extracted_contact', text: contactBody } : null,
30
29
  media,
31
30
  interactive,
32
31
  quotedMessageId: rawMessage.OriginalRepliedMessageSid || null,
@@ -15,6 +15,7 @@ const { isContingencyCancelOnReplyLive } = require('./flags/contingencyFlags');
15
15
  const { maybeWarmPatientRisk } = require('./services/riskAssessmentService');
16
16
  const { settleClaimedDelivery } = require('./services/deliverySettlementService');
17
17
  const { ToolRuntimeContext } = require('./context/ToolRuntimeContext');
18
+ const { reviewUpdateOf } = require('./helpers/reviewUpdateHelper');
18
19
  const { resolveTurnContext, TURN_KIND } = require('./context/turnContext');
19
20
 
20
21
  const traceContingency = (net) => ({
@@ -256,6 +257,21 @@ class AssistantProcessor {
256
257
  });
257
258
  }
258
259
 
260
+ if (traceStored && !runOptions.shadow) {
261
+ const update = reviewUpdateOf({
262
+ turnId: ctx.turnId,
263
+ toolHistory: ctx.toolHistory,
264
+ signals: ctx.trace?.signals,
265
+ patientText: ctx.patientInput?.text,
266
+ });
267
+ if (update) {
268
+ // Required here: escalationReviewService reaches this module through NexusMessaging.
269
+ const { recordReviewUpdate } = require('../services/escalationReviewService');
270
+ // Awaited so it lands before the turn returns; it never throws and never fails the reply.
271
+ await recordReviewUpdate({ code: thread.code, update });
272
+ }
273
+ }
274
+
259
275
  const run = runResult?.run;
260
276
 
261
277
  return {
@@ -0,0 +1,54 @@
1
+ const { objectArg } = require('../../utils/jsonUtils');
2
+ const { isToolFailure } = require('./toolResultHelper');
3
+
4
+ const IMPRESSION_TOOLS = ['openCondition', 'recordClinicalImpression'];
5
+ const CHARACTERIZATION_TOOLS = ['extractClinicalInfo', ...IMPRESSION_TOOLS, 'reportMedicalEscalation'];
6
+ const MAX_PATIENT_TEXT = 500;
7
+
8
+ const textOf = (value) => {
9
+ const text = typeof value === 'string' ? value.trim() : '';
10
+ return text && text.toLowerCase() !== 'none' ? text : null;
11
+ };
12
+
13
+ const gradeOf = (gradeEstimate) => {
14
+ const grade = objectArg(gradeEstimate)?.best_estimate;
15
+ return Number.isInteger(grade) ? grade : null;
16
+ };
17
+
18
+ const impressionOf = (call) => {
19
+ const args = objectArg(call.tool_arguments) || {};
20
+ const result = objectArg(call.tool_output)?.data;
21
+ return {
22
+ caseId: textOf(args.case_id) || textOf(result?.case_id),
23
+ ctcaeTerm: textOf(args.ctcae_term),
24
+ event: call.tool_name === 'openCondition' ? 'opened' : textOf(args.event),
25
+ // A carried-forward grade is resolved by the tool, so its result holds the grade the call omitted.
26
+ grade: gradeOf(args.grade_estimate) ?? gradeOf(result?.grade_estimate),
27
+ trajectory: textOf(args.trajectory_direction),
28
+ missingForHigherGrade: textOf(args.missing_for_higher_grade),
29
+ checkInQuestion: textOf(args.check_in_question),
30
+ };
31
+ };
32
+
33
+ const flagNameOf = (flag) => textOf(typeof flag === 'string' ? flag : flag?.flag);
34
+
35
+ // What the agent characterized this turn, or null when it did not characterize anything:
36
+ // a courtesy reply runs the extractor too, but leaves no mention, impression or escalation behind.
37
+ function reviewUpdateOf({ turnId, toolHistory = [], signals = {}, patientText = null, at = new Date() } = {}) {
38
+ const calls = toolHistory.filter((call) => CHARACTERIZATION_TOOLS.includes(call?.tool_name) && !isToolFailure(call.tool_output));
39
+ const mentionCount = Array.isArray(signals?.clinicalMentions) ? signals.clinicalMentions.length : 0;
40
+ const safetyFlags = (Array.isArray(signals?.safetyFlags) ? signals.safetyFlags : []).map(flagNameOf).filter(Boolean);
41
+ const assessed = calls.some((call) => call.tool_name !== 'extractClinicalInfo');
42
+ if (!turnId || (!assessed && mentionCount === 0 && !safetyFlags.length)) return null;
43
+
44
+ return {
45
+ turnId,
46
+ tools: [...new Set(calls.map((call) => call.tool_name))],
47
+ patientText: textOf(patientText)?.slice(0, MAX_PATIENT_TEXT) || null,
48
+ impressions: calls.filter((call) => IMPRESSION_TOOLS.includes(call.tool_name)).map(impressionOf),
49
+ safetyFlags,
50
+ at,
51
+ };
52
+ }
53
+
54
+ module.exports = { reviewUpdateOf };
@@ -241,6 +241,9 @@ async function handler(args, context = {}) {
241
241
  suspectedCondition: details.suspected_condition || null,
242
242
  recommendedAction: details.recommended_action || null,
243
243
  justification: args?.urgency_justification || null,
244
+ indicators: (Array.isArray(details.indicators) ? details.indicators : [])
245
+ .filter((indicator) => typeof indicator === 'string' && indicator.trim()),
246
+ turnId: runtime.turnId || null,
244
247
  },
245
248
  });
246
249
  queued = await recordEmergency({
package/lib/index.d.ts CHANGED
@@ -11,8 +11,6 @@ declare module '@peopl-health/nexus' {
11
11
  contactName?: string | null;
12
12
  contactLabel?: string | null;
13
13
  body?: string;
14
- /** Derived first-capture contact evidence; never canonical patient identity. */
15
- normalizedContent?: { type: 'extracted_contact'; text: string } | null;
16
14
  message?: string;
17
15
  timestamp?: string | Date;
18
16
  createdAt?: string | Date;
@@ -88,8 +86,6 @@ declare module '@peopl-health/nexus' {
88
86
  }
89
87
 
90
88
  export interface StorageConfig {
91
- /** Explicit prospective journal configuration. Enabled capture requires tenantId and a Clinical mapping set before Nexus.initialize(). */
92
- clinicalEventCapture?: { enabled?: boolean | 'true' | 'false'; tenantId?: string };
93
89
  mongoUri: string;
94
90
  dbName: string;
95
91
  collections?: {
@@ -411,7 +407,6 @@ declare module '@peopl-health/nexus' {
411
407
  export function requestIdMiddleware(req: any, res: any, next: () => void): void;
412
408
  export function getRequestId(): string | null;
413
409
 
414
- /** Set the Clinical mapping before initializing MongoStorage with enabled clinicalEventCapture. */
415
410
  export function setModelDatabases(mapping: Record<string, string>): void;
416
411
  export function setModelDatabase(modelName: string, dbName: string): void;
417
412
  export function getModelDatabase(modelName: string): string | null;
package/lib/index.js CHANGED
@@ -119,7 +119,6 @@ class Nexus {
119
119
  }
120
120
  this.messaging.setMessageStorage(this.storage);
121
121
  } catch (e) {
122
- if (e?.code === 'CLINICAL_SOURCE_CONFIG') throw e;
123
122
  logger.warn('Warning: storage initialization failed:', e?.message || e);
124
123
  }
125
124
  }
@@ -21,9 +21,30 @@ const alarmSchema = new mongoose.Schema({
21
21
  suspectedCondition: { type: String, default: null },
22
22
  recommendedAction: { type: String, default: null },
23
23
  justification: { type: String, default: null },
24
+ indicators: { type: [String], default: undefined },
25
+ turnId: { type: String, default: null },
24
26
  raisedAt: { type: Date, required: true },
25
27
  }, { _id: false });
26
28
 
29
+ const impressionUpdateSchema = new mongoose.Schema({
30
+ caseId: { type: String, default: null },
31
+ ctcaeTerm: { type: String, default: null },
32
+ event: { type: String, default: null },
33
+ grade: { type: Number, default: null },
34
+ trajectory: { type: String, default: null },
35
+ missingForHigherGrade: { type: String, default: null },
36
+ checkInQuestion: { type: String, default: null },
37
+ }, { _id: false });
38
+
39
+ const reviewUpdateSchema = new mongoose.Schema({
40
+ turnId: { type: String, required: true },
41
+ tools: { type: [String], default: [] },
42
+ patientText: { type: String, default: null },
43
+ impressions: { type: [impressionUpdateSchema], default: [] },
44
+ safetyFlags: { type: [String], default: [] },
45
+ at: { type: Date, required: true },
46
+ }, { _id: false });
47
+
27
48
  const noteFactSchema = new mongoose.Schema({
28
49
  variableId: { type: String, required: true },
29
50
  concept: { type: String, default: null },
@@ -126,6 +147,9 @@ const escalationReviewSchema = new mongoose.Schema({
126
147
  openedBy: { type: String, required: true },
127
148
  assistantPausedByReview: { type: Boolean, default: false },
128
149
  alarms: { type: [alarmSchema], default: [] },
150
+ updates: { type: [reviewUpdateSchema], default: [] },
151
+ updatedSinceSeen: { type: Boolean, default: false },
152
+ previousReviewId: { type: String, default: null },
129
153
  callLogs: { type: [callLogSchema], default: [] },
130
154
  noteFacts: { type: [noteFactSchema], default: [] },
131
155
  drafts: { type: [draftSchema], default: [] },
@@ -33,6 +33,8 @@ const { switchThreadStoppedStatus } = require('./threadService');
33
33
 
34
34
  const AUDIT_SOURCE = 'escalation_review';
35
35
  const RECENT_REVIEW_LIMIT = 20;
36
+ const MAX_REVIEW_UPDATES = 50;
37
+ const PREVIOUS_REVIEW_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
36
38
  const DUPLICATE_KEY_ERROR = 11000;
37
39
  const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
38
40
  const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
@@ -412,6 +414,59 @@ async function requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseR
412
414
  }
413
415
 
414
416
  const BOT_OPERATOR = 'bot:reportMedicalEscalation';
417
+ const AGENT_OPERATOR = 'bot:clinicalAgent';
418
+
419
+ async function previousReviewIdOf(EscalationReview, patientCode, now) {
420
+ try {
421
+ const previous = await EscalationReview
422
+ .findOne({ patientCode, closedAt: { $gte: new Date(now.getTime() - PREVIOUS_REVIEW_WINDOW_MS) } }, { _id: 1 })
423
+ .sort({ closedAt: -1 })
424
+ .lean();
425
+ return previous ? String(previous._id) : null;
426
+ } catch (error) {
427
+ logger.warn('[EscalationReview] The previous review lookup failed; opening the review unlinked', { error: redactedError(error) });
428
+ return null;
429
+ }
430
+ }
431
+
432
+ // Files what the agent characterized after the escalation on the patient's open review, and sends a
433
+ // returned review back to the queue. Never opens a review: only an escalation does.
434
+ async function recordReviewUpdate({ code, update } = {}) {
435
+ if (!update) return null;
436
+ try {
437
+ const patientCode = patientCodeOf(code);
438
+ const EscalationReview = getEscalationReview();
439
+ const pushed = await EscalationReview.findOneAndUpdate(
440
+ { patientCode, closedAt: null },
441
+ { $push: { updates: { $each: [update], $slice: -MAX_REVIEW_UPDATES } } },
442
+ { new: true },
443
+ ).lean();
444
+ if (!pushed) return null;
445
+
446
+ // The turn that opened the review seeds its draft, but it is not news to whoever opens it.
447
+ const openingTurn = pushed.alarms?.[0]?.turnId === update.turnId;
448
+ const updated = openingTurn ? pushed : (await EscalationReview
449
+ .findOneAndUpdate({ _id: pushed._id }, { $set: { updatedSinceSeen: true } }, { new: true })
450
+ .lean()) ?? pushed;
451
+ const requeued = updated.status === 'returned'
452
+ ? await EscalationReview
453
+ .findOneAndUpdate({ _id: updated._id, status: 'returned' }, { $set: { status: 'documenting' } }, { new: true })
454
+ .lean()
455
+ : null;
456
+ await audit(updated, AGENT_OPERATOR, null, {
457
+ action: 'case_updated',
458
+ turnId: update.turnId,
459
+ tools: update.tools,
460
+ ...(requeued && { statusFrom: 'returned', statusTo: 'documenting' }),
461
+ });
462
+ return requeued || updated;
463
+ } catch (error) {
464
+ logger.error('[EscalationReview] The agent update was not recorded against the review', {
465
+ error: redactedError(error), stack: redactedStack(error),
466
+ });
467
+ return null;
468
+ }
469
+ }
415
470
 
416
471
  async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
417
472
  try {
@@ -434,7 +489,11 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
434
489
  }
435
490
  try {
436
491
  return (await EscalationReview.create({
437
- patientCode, openedBy: BOT_OPERATOR, alarms: [entry], assistantPausedByReview: false,
492
+ patientCode,
493
+ openedBy: BOT_OPERATOR,
494
+ alarms: [entry],
495
+ assistantPausedByReview: false,
496
+ previousReviewId: await previousReviewIdOf(EscalationReview, patientCode, now),
438
497
  })).toObject();
439
498
  } catch (error) {
440
499
  if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
@@ -513,6 +572,15 @@ async function getEscalationReviewById({ id, requestedBy } = {}) {
513
572
  const reviewId = reviewIdOf(id);
514
573
  const operator = requiredText(requestedBy, 'requestedBy');
515
574
  const review = await loadReview(reviewId);
575
+ if (review.updatedSinceSeen) {
576
+ // Only clears what this read returned: an update that lands meanwhile changes updatedAt and stays unread.
577
+ await getEscalationReview()
578
+ // A read is not a change: leaving updatedAt alone keeps handoff claims and grace periods intact.
579
+ .updateOne({ _id: review._id, updatedAt: review.updatedAt }, { $set: { updatedSinceSeen: false } }, { timestamps: false })
580
+ .catch((error) => logger.warn('[EscalationReview] The updated mark was not cleared', {
581
+ escalationReviewId: String(review._id), error: redactedError(error),
582
+ }));
583
+ }
516
584
  return { review, isApprover: await isEscalationApprover(operator) };
517
585
  }
518
586
 
@@ -857,6 +925,9 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
857
925
  if (draftedAt && (review.alarms ?? []).some((alarm) => new Date(alarm.raisedAt).getTime() > draftedAt)) {
858
926
  throw httpError(409, 'A new alarm arrived after this draft was written; review it and save a new draft before sending it to the doctor');
859
927
  }
928
+ if (draftedAt && (review.updates ?? []).some((entry) => new Date(entry.at).getTime() > draftedAt)) {
929
+ throw httpError(409, 'The agent characterized the case after this draft was written; review it and save a new draft before sending it to the doctor');
930
+ }
860
931
  const identity = await readDoctorIdentity(review);
861
932
  if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
862
933
  const link = doctorLink(review);
@@ -872,7 +943,8 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
872
943
  reviewId,
873
944
  [review.status],
874
945
  { $set: { status: 'handing_off', operationClaim: claim } },
875
- { drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length } },
946
+ // updatedAt moves with every write, so an agent update filed since the read fails the claim.
947
+ { drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length }, updatedAt: review.updatedAt },
876
948
  );
877
949
  let delivery = {};
878
950
  let updated;
@@ -975,6 +1047,17 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
975
1047
  throw httpError(409, 'This decision carries no approved text to send to the patient');
976
1048
  }
977
1049
 
1050
+ const decidedAt = claimed.decisions[decisionNumber - 1].createdAt;
1051
+ if (decidedAt && (claimed.updates ?? []).some((entry) => new Date(entry.at) > new Date(decidedAt))) {
1052
+ // Back to documenting: the decision is spent, and a new draft and decision have to follow.
1053
+ await releaseReview(reviewId, 'sending', 'documenting', claim).catch((releaseError) => {
1054
+ logger.error('[EscalationReview] The claim was not released after a decision new information overtook', {
1055
+ escalationReviewId: String(claimed._id), error: releaseError.message,
1056
+ });
1057
+ });
1058
+ throw httpError(409, 'The agent characterized the case after this decision; it went back to documenting for a new draft and decision');
1059
+ }
1060
+
978
1061
  // Built outside the try: composing reads Mongo and Airtable, and failing there never sent.
979
1062
  let message;
980
1063
  try {
@@ -1161,13 +1244,15 @@ async function cancelEscalationReview({ id, cancelledBy, reason = null, requestI
1161
1244
 
1162
1245
  let review;
1163
1246
  try {
1247
+ // Once the doctor has seen or decided the review, cancelling it needs a reason whatever its status.
1164
1248
  review = await updateReview(reviewId, allowed, {
1165
1249
  $set: { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: notes },
1166
- });
1250
+ }, notes ? {} : { 'doctorHandoffs.0': { $exists: false }, 'decisions.0': { $exists: false } });
1167
1251
  } catch (error) {
1168
1252
  if (error?.statusCode !== 409 || notes) throw error;
1169
1253
  const current = await loadReview(reviewId);
1170
- if (CANCELLABLE_AFTER_HANDOFF_STATUSES.includes(current.status)) throw httpError(409, CANCEL_NEEDS_REASON);
1254
+ const doctorInvolved = Boolean(current.doctorHandoffs?.length || current.decisions?.length);
1255
+ if (doctorInvolved || CANCELLABLE_AFTER_HANDOFF_STATUSES.includes(current.status)) throw httpError(409, CANCEL_NEEDS_REASON);
1171
1256
  throw error;
1172
1257
  }
1173
1258
 
@@ -1193,6 +1278,7 @@ module.exports = {
1193
1278
  openEscalationReview,
1194
1279
  recordEscalationAlarm,
1195
1280
  recordDoctorDecision,
1281
+ recordReviewUpdate,
1196
1282
  sendApprovedIndications,
1197
1283
  setReviewCases,
1198
1284
  suggestDraft,
@@ -9,8 +9,6 @@ const { getClinicalContext } = require('../helpers/patientInformationHelper');
9
9
 
10
10
  const { updateRecordByFilter } = require('../services/airtableService');
11
11
 
12
- const { captureClinicalMessage } = require('../clinical/services/clinicalMessageCaptureService');
13
-
14
12
  const INTERNAL_ORIGINS = new Set(['system', 'instruction']);
15
13
 
16
14
  async function getMessages(query, options = {}) {
@@ -30,9 +28,8 @@ async function aggregateMessages(pipeline, options = {}) {
30
28
  return Message.aggregate(pipeline, options);
31
29
  }
32
30
 
33
- async function insertMessage(values, options = {}) {
31
+ async function insertMessage(values) {
34
32
  try {
35
- await captureClinicalMessage(values, options?.clinicalEventCapture);
36
33
  if (!values.clinical_context) {
37
34
  const { clinicalContext } = await getClinicalContext(values.numero);
38
35
  values.clinical_context = clinicalContext;
@@ -12,12 +12,10 @@ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
12
12
  const { getMessages, insertMessage } = require('../services/messageService');
13
13
 
14
14
  const { getEventBus: getStatusEventBus } = require('../core/NexusMessaging');
15
- const { assertClinicalCaptureConfigured } = require('../clinical/services/clinicalCaptureConfigService');
16
15
 
17
16
  class MongoStorage {
18
17
  constructor(config) {
19
18
  this.mongoUri = config.mongoUri;
20
- this.clinicalEventCapture = config.clinicalEventCapture;
21
19
  this.dbName = config.dbName;
22
20
  this.collections = config.collections || {
23
21
  messages: 'messages',
@@ -34,7 +32,6 @@ class MongoStorage {
34
32
  }
35
33
 
36
34
  async connect() {
37
- assertClinicalCaptureConfigured(this.clinicalEventCapture);
38
35
  await mongoConnect(this.mongoUri);
39
36
  if (this.dbName) this.db = getDb(this.dbName);
40
37
  }
@@ -42,7 +39,7 @@ class MongoStorage {
42
39
  async saveMessage(messageData) {
43
40
  try {
44
41
  const values = this.buildMessageValues(messageData);
45
- const { doc } = await insertMessage(values, { clinicalEventCapture: this.clinicalEventCapture });
42
+ const { doc } = await insertMessage(values);
46
43
  logger.info('[MongoStorage] Message stored');
47
44
  if (!messageData.silent) this._emitMessageNew(doc, messageData.from, messageData.frontendId);
48
45
  return doc;
@@ -57,7 +54,7 @@ class MongoStorage {
57
54
  ...messageData,
58
55
  statusInfo: { status: 'queued', updatedAt: new Date() }
59
56
  });
60
- const { doc } = await insertMessage(values, { clinicalEventCapture: this.clinicalEventCapture });
57
+ const { doc } = await insertMessage(values);
61
58
  if (!messageData.silent) this._emitMessageNew(doc, messageData.from, messageData.frontendId, 'queued');
62
59
  return doc;
63
60
  }
@@ -115,15 +112,6 @@ class MongoStorage {
115
112
  plainBody: messageData.plainBody || '',
116
113
  processed: messageData.processed || false,
117
114
  message_id: messageId,
118
- sourceText: messageData.plainBody ?? messageData.body,
119
- normalizedContent: messageData.normalizedContent,
120
- sourceSystem: messageData.sourceSystem,
121
- sourceProvider: messageData.provider,
122
- sourceRecordId: messageData.sourceRecordId,
123
- sourceRevision: messageData.sourceRevision,
124
- sourceTimestamp: messageData.sourceTimestamp,
125
- sourceActorId: messageData.from,
126
- quotedMessageId: messageData.quotedMessageId,
127
115
  interactive_type: messageData.interactive?.type || null,
128
116
  interactive_data: messageData.interactive || null,
129
117
  from_me: messageData.fromMe !== undefined ? messageData.fromMe : true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.61.0-dev.11181",
3
+ "version": "5.61.0-dev.11184",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,32 +0,0 @@
1
- const mongoose = require('mongoose');
2
-
3
- const { clinicalConnection } = require('../config/connection');
4
-
5
- const clinicalSourceEventSchema = new mongoose.Schema({
6
- _id: { type: String, required: true },
7
- tenantId: { type: String, required: true, immutable: true },
8
- sourceSystem: { type: String, required: true, immutable: true },
9
- sourceRecordId: { type: String, required: true, immutable: true },
10
- sourceRevision: { type: String, required: true, immutable: true },
11
- sourceMessageId: { type: String, default: null, immutable: true },
12
- patientId: { type: String, default: null, immutable: true },
13
- identity: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
14
- actor: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
15
- experiencer: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
16
- validTime: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
17
- recordTime: { type: Date, required: true, immutable: true },
18
- evidenceRefs: { type: [mongoose.Schema.Types.Mixed], default: [], immutable: true },
19
- artifactRefs: { type: [mongoose.Schema.Types.Mixed], default: [], immutable: true },
20
- normalizedContent: { type: mongoose.Schema.Types.Mixed, default: null, immutable: true },
21
- payload: { type: mongoose.Schema.Types.Mixed, required: true, immutable: true },
22
- schemaVersion: { type: String, required: true, immutable: true },
23
- policyVersion: { type: String, default: null, immutable: true },
24
- }, { versionKey: false, autoCreate: false, autoIndex: false });
25
-
26
- function getClinicalSourceEventModel() {
27
- const connection = clinicalConnection();
28
- return connection.models.ClinicalSourceEvent
29
- || connection.model('ClinicalSourceEvent', clinicalSourceEventSchema, 'clinicalSourceEvent');
30
- }
31
-
32
- module.exports = { getClinicalSourceEventModel, clinicalSourceEventSchema };
@@ -1,22 +0,0 @@
1
- const { getModelDatabase } = require('../../config/mongoConfig');
2
-
3
- class ClinicalCaptureConfigError extends Error {
4
- constructor() {
5
- super('Clinical source capture configuration invalid');
6
- this.name = 'ClinicalCaptureConfigError';
7
- this.code = 'CLINICAL_SOURCE_CONFIG';
8
- }
9
- }
10
-
11
- function assertClinicalCaptureConfigured(settings) {
12
- if (settings?.enabled !== true && settings?.enabled !== 'true') return;
13
-
14
- const tenantId = settings.tenantId;
15
- const clinicalDb = getModelDatabase('Clinical');
16
- if (typeof tenantId !== 'string' || !tenantId || tenantId.trim() !== tenantId
17
- || typeof clinicalDb !== 'string' || !clinicalDb.trim()) {
18
- throw new ClinicalCaptureConfigError();
19
- }
20
- }
21
-
22
- module.exports = { assertClinicalCaptureConfigured, ClinicalCaptureConfigError };
@@ -1,132 +0,0 @@
1
- const { createHash } = require('crypto');
2
-
3
- class ClinicalSourceError extends Error {
4
- constructor(code, message) {
5
- super(message);
6
- this.name = 'ClinicalSourceError';
7
- this.code = code;
8
- }
9
- }
10
-
11
- function invalidSource() {
12
- return new ClinicalSourceError('CLINICAL_SOURCE_INVALID', 'Invalid clinical source event');
13
- }
14
-
15
- function isStableId(value) {
16
- return typeof value === 'string' && value.length > 0 && value.trim() === value;
17
- }
18
-
19
- // JSON only: reject values that would silently disappear or change during persistence.
20
- function canonical(value, ancestors = new Set()) {
21
- if (value === null || typeof value === 'string' || typeof value === 'boolean') return JSON.stringify(value);
22
- if (typeof value === 'number' && Number.isFinite(value)) return JSON.stringify(value);
23
- if (typeof value !== 'object' || ancestors.has(value)) throw invalidSource();
24
- if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw invalidSource();
25
- ancestors.add(value);
26
- const result = Array.isArray(value)
27
- ? '[' + Array.from(value, item => canonical(item, ancestors)).join(',') + ']'
28
- : '{' + Object.keys(value).sort().map(key => JSON.stringify(key) + ':' + canonical(value[key], ancestors)).join(',') + '}';
29
- ancestors.delete(value);
30
- return result;
31
- }
32
-
33
- function validateClinicalSourceEvent(envelope) {
34
- if (!envelope || typeof envelope !== 'object') throw invalidSource();
35
- for (const field of ['tenantId', 'sourceSystem', 'sourceRecordId', 'sourceRevision', 'schemaVersion']) {
36
- if (!isStableId(envelope[field])) throw invalidSource();
37
- }
38
- if (envelope.sourceMessageId != null && !isStableId(envelope.sourceMessageId)) throw invalidSource();
39
- if (envelope.patientId !== null && !isStableId(envelope.patientId)) throw invalidSource();
40
- if (!['unknown', 'ambiguous', 'resolved'].includes(envelope.identity?.status) || !Array.isArray(envelope.identity.sourceRefs)) throw invalidSource();
41
- if ((envelope.patientId !== null) !== (envelope.identity.status === 'resolved')) throw invalidSource();
42
- for (const field of ['actor', 'experiencer', 'payload']) {
43
- if (!envelope[field] || typeof envelope[field] !== 'object' || Array.isArray(envelope[field])) throw invalidSource();
44
- }
45
- if (!Array.isArray(envelope.evidenceRefs)) throw invalidSource();
46
- const artifactRefs = envelope.artifactRefs === undefined ? [] : envelope.artifactRefs;
47
- if (!Array.isArray(artifactRefs)) throw invalidSource();
48
- const attachmentIndexes = new Set();
49
- for (const ref of artifactRefs) {
50
- if (!ref || typeof ref !== 'object' || Array.isArray(ref)
51
- || Object.keys(ref).some(key => !['attachmentIndex', 'bucket', 'key'].includes(key))
52
- || !Number.isSafeInteger(ref.attachmentIndex) || ref.attachmentIndex < 0
53
- || attachmentIndexes.has(ref.attachmentIndex) || !isStableId(ref.bucket) || !isStableId(ref.key)) throw invalidSource();
54
- attachmentIndexes.add(ref.attachmentIndex);
55
- }
56
- const normalizedContent = envelope.normalizedContent ?? null;
57
- if (normalizedContent !== null && (typeof normalizedContent !== 'object' || Array.isArray(normalizedContent)
58
- || Object.keys(normalizedContent).some(key => !['type', 'text'].includes(key))
59
- || normalizedContent.type !== 'extracted_contact' || typeof normalizedContent.text !== 'string'
60
- || !normalizedContent.text.trim())) throw invalidSource();
61
- if (!['known', 'unknown'].includes(envelope.validTime?.status)) throw invalidSource();
62
- if (envelope.validTime.status === 'known' && (typeof envelope.validTime.at !== 'string' || !Number.isFinite(Date.parse(envelope.validTime.at)))) throw invalidSource();
63
- if (envelope.validTime.status === 'unknown' && envelope.validTime.at != null) throw invalidSource();
64
- if (envelope.policyVersion !== null && !isStableId(envelope.policyVersion)) throw invalidSource();
65
- const document = {};
66
- for (const field of ['tenantId', 'sourceSystem', 'sourceRecordId', 'sourceRevision', 'patientId', 'identity', 'actor', 'experiencer', 'validTime', 'evidenceRefs', 'payload', 'schemaVersion', 'policyVersion']) document[field] = envelope[field];
67
- document.sourceMessageId = envelope.sourceMessageId ?? null;
68
- document.artifactRefs = artifactRefs;
69
- document.normalizedContent = normalizedContent;
70
- return JSON.parse(canonical(document));
71
- }
72
-
73
- function sourceFingerprint(document) {
74
- // Identity adjudication, policy selection, capture artifacts and observation time are not source revisions.
75
- const omitted = new Set(['artifactRefs', 'normalizedContent', 'patientId', 'identity', 'policyVersion', 'recordTime', '_id']);
76
- const source = Object.fromEntries(Object.entries(document).filter(([key]) => !omitted.has(key)));
77
- return canonical({ ...source, identitySourceRefs: document.identity.sourceRefs });
78
- }
79
-
80
- function persistenceClassification(stage, error) {
81
- if (stage === 'unacknowledged') return 'unacknowledged';
82
- if (stage === 'missing_duplicate') return 'not_found';
83
- if ([50, 64].includes(error?.code) || error?.name === 'MongoNetworkTimeoutError') return 'timeout';
84
- if ([13, 18].includes(error?.code)) return 'authorization';
85
- if ([6, 7, 89, 91].includes(error?.code)
86
- || ['MongoNetworkError', 'MongoServerSelectionError'].includes(error?.name)) return 'unavailable';
87
- return 'unknown';
88
- }
89
-
90
- async function ingestClinicalSourceEvent(envelope) {
91
- const document = validateClinicalSourceEvent(envelope);
92
- const eventId = createHash('sha256').update(JSON.stringify([
93
- document.tenantId, document.sourceSystem, document.sourceRecordId, document.sourceRevision,
94
- ])).digest('hex');
95
- const fingerprint = sourceFingerprint(document);
96
- let stage = 'model';
97
- try {
98
- const { getClinicalSourceEventModel } = require('../models/clinicalSourceEventModel');
99
- const { collection } = getClinicalSourceEventModel();
100
- try {
101
- stage = 'write';
102
- const result = await collection.insertOne({ ...document, _id: eventId, recordTime: new Date() }, { writeConcern: { w: 'majority', j: true, wtimeoutMS: 10000 } });
103
- if (!result?.acknowledged) {
104
- stage = 'unacknowledged';
105
- throw new Error();
106
- }
107
- return { eventId, state: document.patientId === null ? 'identity_pending' : 'recorded' };
108
- } catch (error) {
109
- if (error.code !== 11000) throw error;
110
- stage = 'duplicate_read';
111
- const existing = await collection.findOne({ _id: eventId }, { readPreference: 'primary', readConcern: { level: 'majority' } });
112
- if (!existing) {
113
- stage = 'missing_duplicate';
114
- throw new Error();
115
- }
116
- stage = 'duplicate_verify';
117
- if (sourceFingerprint(existing) !== fingerprint) throw new ClinicalSourceError('CLINICAL_SOURCE_CONFLICT', 'Clinical source revision conflict');
118
- return { eventId, state: 'duplicate' };
119
- }
120
- } catch (error) {
121
- if (error instanceof ClinicalSourceError && error.code === 'CLINICAL_SOURCE_CONFLICT') throw error;
122
- try {
123
- const { logger } = require('../../utils/logger');
124
- logger.error('[clinicalEventService] Source persistence failed', { stage, classification: persistenceClassification(stage, error) });
125
- } catch {
126
- // Diagnostic availability must not change the safe public failure contract.
127
- }
128
- throw new ClinicalSourceError('CLINICAL_SOURCE_PERSISTENCE', 'Clinical source persistence failed');
129
- }
130
- }
131
-
132
- module.exports = { ingestClinicalSourceEvent, validateClinicalSourceEvent, ClinicalSourceError };
@@ -1,72 +0,0 @@
1
- const { isBenchMode } = require('../../utils/benchModeHelper');
2
- const { isShadowRun } = require('../../utils/shadowScope');
3
- const { ingestClinicalSourceEvent, validateClinicalSourceEvent, ClinicalSourceError } = require('./clinicalEventService');
4
-
5
- function pick(source, fields) {
6
- if (!source || typeof source !== 'object') return null;
7
- return Object.fromEntries(fields.filter(field => source[field] !== undefined).map(field => [field, source[field]]));
8
- }
9
-
10
- function mediaEvidence(media) {
11
- const fields = ['key', 'bucket', 'bucketName', 'mimeType', 'mediaType', 'contentType', 'filename', 'fileName', 'fileSize', 'caption', 'url', 'size', 'sha256'];
12
- const evidence = pick(media, fields);
13
- if (evidence && Array.isArray(media.metadata?.attachments)) {
14
- evidence.attachments = media.metadata.attachments.map(item => pick(item, fields));
15
- }
16
- return evidence;
17
- }
18
-
19
- function privateArtifactRefs(media) {
20
- const attachments = Array.isArray(media?.metadata?.attachments) ? media.metadata.attachments : [];
21
- return [media, ...attachments].flatMap((item, attachmentIndex) => {
22
- const bucket = item?.bucketName ?? item?.bucket;
23
- if (bucket == null || item?.key == null) return [];
24
- return [{ attachmentIndex, bucket, key: item.key }];
25
- });
26
- }
27
-
28
- function buildClinicalMessageEnvelope(values, tenantId) {
29
- const raw = values.raw ?? {};
30
- if (typeof raw !== 'object' || Array.isArray(raw)) throw new ClinicalSourceError('CLINICAL_SOURCE_INVALID', 'Invalid clinical source event');
31
- const sourceSystem = values.sourceSystem || values.sourceProvider || (raw.MessageSid ? 'twilio' : raw.key?.id ? 'baileys' : 'whatsapp_platform');
32
- const sourceId = values.sourceRecordId ?? values.message_id;
33
- const actorId = raw.From || raw.key?.remoteJid || values.contact_code || values.sourceActorId || values.numero || null;
34
- const providerEvidence = pick(raw, ['MessageSid', 'SmsSid', 'OriginalRepliedMessageSid', 'Body', 'ButtonPayload', 'ButtonText', 'ListId', 'ListTitle', 'ListDescription', 'FlowData', 'InteractiveData', 'NumMedia', 'MediaUrl0', 'MediaContentType0']);
35
- const mediaFields = Object.keys(raw).filter(key => /^Media(?:Url|ContentType)\d+$/.test(key));
36
- Object.assign(providerEvidence, pick(raw, mediaFields));
37
- const hasProviderMedia = mediaFields.some(key => /^MediaUrl\d+$/.test(key));
38
- const event = {
39
- tenantId, sourceSystem, sourceRecordId: sourceId, sourceRevision: values.sourceRevision ?? '1',
40
- sourceMessageId: values.message_id ?? null, patientId: null,
41
- identity: {
42
- status: 'unknown', sourceRefs: actorId ? [{ system: 'message_transport', id: actorId }] : [],
43
- routingEnrichment: { contactRole: values.contact_role || null, patientReference: values.numero || null },
44
- },
45
- actor: { type: 'transport_contact', sourceId: actorId, reportedRole: null, authenticatedRole: null },
46
- experiencer: { patientId: null, status: 'unknown' },
47
- validTime: { status: 'unknown' },
48
- evidenceRefs: [],
49
- artifactRefs: privateArtifactRefs(values.media),
50
- normalizedContent: values.normalizedContent ?? null,
51
- payload: {
52
- sourceTimestamp: values.sourceTimestamp ?? null,
53
- text: typeof raw.Body === 'string' ? raw.Body : values.sourceText ?? values.plainBody ?? values.body ?? '',
54
- interactive: pick(values.interactive_data, ['type', 'payload', 'title', 'id', 'description', 'replyId', 'flowData', 'interactiveData']) || (values.interactive_type ? { type: values.interactive_type } : null),
55
- media: hasProviderMedia ? null : mediaEvidence(values.media),
56
- providerEvidence,
57
- quotedMessageId: values.quotedMessageId ?? raw.OriginalRepliedMessageSid ?? null,
58
- },
59
- schemaVersion: '1', policyVersion: null,
60
- };
61
- return validateClinicalSourceEvent(event);
62
- }
63
-
64
- async function captureClinicalMessage(values, settings = {}) {
65
- const enabled = settings?.enabled;
66
- if (enabled !== true && enabled !== 'true') return { state: 'skipped', reason: 'disabled' };
67
- if (isShadowRun() || isBenchMode(values?.numero) || isBenchMode(values?.contact_code)) return { state: 'skipped', reason: 'isolated_run' };
68
- if (values?.from_me !== false || !['patient', 'whatsapp_platform'].includes(values?.origin)) return { state: 'skipped', reason: 'excluded_message' };
69
- return ingestClinicalSourceEvent(buildClinicalMessageEnvelope(values, settings.tenantId));
70
- }
71
-
72
- module.exports = { buildClinicalMessageEnvelope, captureClinicalMessage };