@peopl-health/nexus 6.0.0-dev.16505 → 6.0.0-dev.16508

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.
@@ -31,6 +31,7 @@ function flagsByStatus(sections) {
31
31
  unassessed: pending.map((flag) => inlineOf(flag.flag)),
32
32
  drugSafety: pending.filter((flag) => flag.blocksDrug !== false).map((flag) => inlineOf(flag.flag)),
33
33
  urgent: pending.filter((flag) => flag.urgentIfPositive === true).map((flag) => inlineOf(flag.flag)),
34
+ urgentPresent: flags.filter((flag) => flag.present === true && flag.urgentIfPositive === true).map((flag) => inlineOf(flag.flag)),
34
35
  unobtainable: pending.filter((flag) => flag.present === UNOBTAINABLE).map((flag) => inlineOf(flag.flag)),
35
36
  };
36
37
  }
@@ -89,6 +89,17 @@ function draftProvider() {
89
89
  }
90
90
  }
91
91
 
92
+ const MAX_URGENT_FLAGS = 2;
93
+ const urgencyRank = (flag) => (flag.present === true ? 0 : flag.present === false ? 2 : 1);
94
+
95
+ // The model does not always keep to two grave flags per symptom: the confirmed ones keep the mark first, then the pending ones in its order.
96
+ function capUrgentFlags(block) {
97
+ const urgent = (Array.isArray(block?.redFlags) ? block.redFlags : []).filter((flag) => flag?.urgentIfPositive === true);
98
+ if (urgent.length <= MAX_URGENT_FLAGS) return block;
99
+ const kept = new Set([...urgent].sort((a, b) => urgencyRank(a) - urgencyRank(b)).slice(0, MAX_URGENT_FLAGS));
100
+ return { ...block, redFlags: block.redFlags.map((flag) => (urgent.includes(flag) && !kept.has(flag) ? { ...flag, urgentIfPositive: false } : flag)) };
101
+ }
102
+
92
103
  async function generateEscalationDraft({
93
104
  code, callLogs = [], alarms = [], agentCharacterization = null, provider, trace = null, reviewId = null, now = Date.now(),
94
105
  } = {}) {
@@ -131,7 +142,7 @@ async function generateEscalationDraft({
131
142
  const parsed = safeParse(readStructuredText(result), null);
132
143
  const patientMessage = trimmed(parsed?.patientMessage);
133
144
  // The schema is not strict, so the model sometimes sends the list JSON-encoded as a string.
134
- const blocks = parsed?.symptoms === undefined ? [parsed] : arrayArg(parsed.symptoms);
145
+ const blocks = (parsed?.symptoms === undefined ? [parsed] : arrayArg(parsed.symptoms)).map(capUrgentFlags);
135
146
  if (!blocks.length) {
136
147
  const shape = parsed.symptoms;
137
148
  logger.warn('[escalationDraft] generation returned a malformed symptom list', {
@@ -186,6 +197,9 @@ async function generateEscalationDraft({
186
197
  return { completed: false, attempted: true, rejected: true, reason: `the model wrote a field name or technical token into the doctor or patient text: "${leaked}"` };
187
198
  }
188
199
 
200
+ const urgentPresent = [...new Set(blocks.flatMap((block) => flagsByStatus(block).urgentPresent))];
201
+ // A grave flag the patient confirmed is enough for the doctor, whatever else is still pending.
202
+ const sufficientForDoctor = urgentPresent.length ? true : (typeof parsed?.sufficientForDoctor === 'boolean' ? parsed.sufficientForDoctor : null);
189
203
  return {
190
204
  completed: true,
191
205
  attempted: true,
@@ -196,9 +210,10 @@ async function generateEscalationDraft({
196
210
  unassessedRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).unassessed))],
197
211
  urgentUnassessedRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).urgent))],
198
212
  unobtainableRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).unobtainable))],
213
+ urgentPresentRedFlags: urgentPresent,
199
214
  missingCharacterization: textList(parsed?.missingCharacterization),
200
- sufficientForDoctor: typeof parsed?.sufficientForDoctor === 'boolean' ? parsed.sufficientForDoctor : null,
201
- blockingQuestion: parsed?.sufficientForDoctor === false ? trimmed(parsed?.blockingQuestion) || null : null,
215
+ sufficientForDoctor,
216
+ blockingQuestion: sufficientForDoctor === false ? trimmed(parsed?.blockingQuestion) || null : null,
202
217
  suggestCall: suggestCallOf(parsed?.suggestCall),
203
218
  sectionsUnavailable: context.degradedSections ?? [],
204
219
  };
@@ -133,6 +133,7 @@ const draftSchema = new mongoose.Schema({
133
133
  unassessedRedFlags: { type: [String], default: undefined },
134
134
  urgentUnassessedRedFlags: { type: [String], default: undefined },
135
135
  unobtainableRedFlags: { type: [String], default: undefined },
136
+ urgentPresentRedFlags: { type: [String], default: undefined },
136
137
  sufficientForDoctor: { type: Boolean, default: undefined },
137
138
  blockingQuestion: { type: String, default: undefined },
138
139
  missingCharacterization: { type: [String], default: undefined },
@@ -7,6 +7,7 @@ const { readGroupMessageId } = require('../clinical/services/clinicalAirtableSer
7
7
 
8
8
  const { countMessages } = require('./messageService');
9
9
  const { logPatientChange } = require('./patientService');
10
+ const { getThreadInfo } = require('./threadService');
10
11
  const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES, PRE_DECISION_STATUSES, caseTakenReason, handOffToDoctor, teamAlertIdentity } = require('./escalationReviewService');
11
12
  const { graveMissingOf, isDraftCurrent, pendingFlagsOf } = require('./gravePendingService');
12
13
  const { BUSINESS_HOURS_LEVELS, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
@@ -48,7 +49,11 @@ function outcomeOf(review, clock, now) {
48
49
  const withUpdate = (note) => (update ? noteOf([UPDATE_NOTE, note].filter(Boolean).join(' · ')) : note);
49
50
 
50
51
  const grave = graveMissingOf(review, clock, now);
51
- if (grave.length) return { grave, update, note: withUpdate(noteOf(`Falta dato grave: ${grave.map(({ flag }) => flag).join(', ')}`)) };
52
+ const present = latest.urgentPresentRedFlags ?? [];
53
+ if (grave.length || present.length) {
54
+ const note = [present.length && `Bandera grave presente: ${present.join(', ')}`, grave.length && `Falta dato grave: ${grave.map(({ flag }) => flag).join(', ')}`];
55
+ return { grave, update, note: withUpdate(noteOf(note.filter(Boolean).join(' · '))) };
56
+ }
52
57
  // A grave question still inside its wait holds the case even when the rest is enough.
53
58
  if (pendingFlagsOf(review, clock.since).flags.length) return null;
54
59
  if (latest.sufficientForDoctor === true) return { grave: [], update, note: withUpdate(null) };
@@ -218,12 +223,19 @@ async function sendDueGraveAlerts(review, clock, entries, now) {
218
223
  return delivered ? sending.length : 0;
219
224
  }
220
225
 
226
+ const unsentGraveAlerts = (review, clock) => (review.graveAlerts ?? []).filter((entry) => !entry.sentAt && timeOf(entry.since) === clock.since.getTime());
227
+
228
+ // A patient in the hospital is already under care: the doctor still gets the grave datum, the team is not called for it.
229
+ async function skipGraveAlerts(review, clock, now) {
230
+ for (const entry of unsentGraveAlerts(review, clock)) await setOn(review, entry, { sentAt: now, skippedReason: 'patient_hospitalized' }, { sentAt: null });
231
+ }
232
+
221
233
  // In urgent, a patient who left the bot's question unanswered gets one reminder, held for the team day at night.
222
234
  async function remindQuietPatient(review, clock, now) {
223
235
  if (clock.level !== 'urgent' || !PRE_DECISION_STATUSES.includes(review.status) || review.closedAt) return;
224
236
  const latest = (review.drafts ?? []).at(-1);
225
237
  if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime()) return;
226
- const pending = latest.sufficientForDoctor === false || pendingFlagsOf(review, clock.since).flags.length > 0;
238
+ const pending = !latest.urgentPresentRedFlags?.length && (latest.sufficientForDoctor === false || pendingFlagsOf(review, clock.since).flags.length > 0);
227
239
  if (!pending || (review.quietReminders ?? []).some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
228
240
  const dueAt = teamOpenAt(new Date(timeOf(latest.createdAt) + quietReminderMinutes() * 60000), responseDeadlinePolicy());
229
241
  if (now.getTime() < dueAt.getTime()) return;
@@ -266,13 +278,16 @@ async function remindQuietPatient(review, clock, now) {
266
278
  async function settleCharacterization(review, clock, now) {
267
279
  if (!clock) return;
268
280
  const outcome = outcomeOf(review, clock, now);
269
- const claimed = outcome?.grave.length ? await claimGraveAlerts(review, clock, outcome.grave, now) : [];
281
+ const graveWork = outcome?.grave.length || unsentGraveAlerts(review, clock).length;
282
+ const hospitalized = graveWork ? Boolean((await getThreadInfo(review.patientCode))?.hospitalizedAt) : false;
283
+ const claimed = outcome?.grave.length && !hospitalized ? await claimGraveAlerts(review, clock, outcome.grave, now) : [];
270
284
  const attempts = attemptsOf(review, clock);
271
285
  // Each failure doubles the wait; after the last attempt the team hands the case over by hand.
272
286
  const backingOff = attempts >= MAX_HANDOFF_ATTEMPTS
273
287
  || (attempts > 0 && now.getTime() - timeOf(review.autoHandoffFailedAt) < HANDOFF_RETRY_MS * 2 ** (attempts - 1));
274
- if (outcome && !backingOff && await handOff(review, clock, outcome, now) && !outcome.grave.length) await sendHandoffNotice(review, clock, outcome);
275
- await sendDueGraveAlerts(review, clock, [...(review.graveAlerts ?? []), ...claimed], now);
288
+ if (outcome && !backingOff && await handOff(review, clock, outcome, now) && (hospitalized || !outcome.grave.length)) await sendHandoffNotice(review, clock, outcome);
289
+ if (hospitalized) await skipGraveAlerts(review, clock, now);
290
+ else await sendDueGraveAlerts(review, clock, [...(review.graveAlerts ?? []), ...claimed], now);
276
291
  await remindQuietPatient(review, clock, now);
277
292
  }
278
293
 
@@ -1448,6 +1448,7 @@ async function generateBotDraft({ id, lease = null } = {}) {
1448
1448
  unassessedRedFlags: draft.unassessedRedFlags,
1449
1449
  urgentUnassessedRedFlags: draft.urgentUnassessedRedFlags,
1450
1450
  unobtainableRedFlags: draft.unobtainableRedFlags,
1451
+ urgentPresentRedFlags: draft.urgentPresentRedFlags,
1451
1452
  sufficientForDoctor: draft.sufficientForDoctor,
1452
1453
  blockingQuestion: draft.blockingQuestion,
1453
1454
  missingCharacterization: draft.missingCharacterization,
@@ -172,7 +172,7 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
172
172
  alarms: { $elemMatch: { raisedAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } } },
173
173
  }, { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, quietReminders: 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1,
174
174
  'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
175
- 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1,
175
+ 'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1,
176
176
  })
177
177
  .sort({ _id: -1 })
178
178
  .limit(SWEEP_LIMIT)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.0-dev.16505",
3
+ "version": "6.0.0-dev.16508",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",