@peopl-health/nexus 6.1.0-dev.18137 → 6.1.0-dev.18186

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.
@@ -90,7 +90,7 @@ function symptomParagraph(entry, fallbackSymptom) {
90
90
  const label = inlineOf(sections.symptom) || fallbackSymptom || 'Síntoma no especificado';
91
91
  const graded = [1, 2, 3, 4, 5].includes(sections.grade);
92
92
  const grade = graded ? `G${sections.grade}` : 'grado no establecido';
93
- const { present, absent, unassessed } = flagsByStatus(sections);
93
+ const { present, absent, unassessed, urgent, unobtainable } = flagsByStatus(sections);
94
94
  const summary = inlineOf(sections.characterizationSummary);
95
95
  return [
96
96
  // An ungraded symptom whose label already names a grade is not called ungraded.
@@ -98,6 +98,8 @@ function symptomParagraph(entry, fallbackSymptom) {
98
98
  summary && sentence(summary),
99
99
  present.length && `${present.length > 1 ? 'Banderas rojas presentes' : 'Bandera roja presente'}: ${sentence(present.join(', '))}`,
100
100
  !present.length && !unassessed.length && absent.length && 'Sin banderas rojas.',
101
+ // A proposal names its own pending grave flags; without one they would go unsaid.
102
+ !proposedDrugs(entry).length && urgent.length && `Falta descartar: ${sentence(urgent.map((flag) => (unobtainable.includes(flag) ? `${flag} (no lo puede dar)` : flag)).join(', '))}`,
101
103
  proposalLine(entry),
102
104
  ].filter(Boolean).join(' ');
103
105
  }
@@ -19,6 +19,7 @@ const MIN_AGE_MS = 15 * 60 * 1000;
19
19
  const RETRY_MAX_AGE_MS = 60 * 60 * 1000;
20
20
  const MAX_CANDIDATES = 20;
21
21
  const MAX_RETRIES_PER_PASS = 3;
22
+ const TRANSIENT_DISPATCH_FAILURES = new Set(['triage_read_failed', 'patient_read_failed', 'item_read_failed']);
22
23
  const CLAIM_TTL_MS = 60 * 60 * 1000;
23
24
  const DEFAULT_SWEEP_INTERVAL_MS = 10 * 60 * 1000;
24
25
  const RETRY_SETTLE_MS = 5 * 60 * 1000;
@@ -222,7 +223,7 @@ async function sweepInterruptedTriages({
222
223
  } = {}) {
223
224
  const result = { found: 0, retried: 0, skipped: 0 };
224
225
  if (!retryLive()) return result;
225
- const active = await leases.listActive();
226
+ const active = await leases.listActive({ interrupted: true, source: programSource() });
226
227
  if (!active) return result;
227
228
 
228
229
  const due = active.filter(({ value }) => value.source === programSource()
@@ -246,7 +247,7 @@ async function sweepInterruptedTriages({
246
247
  await retrigger(run);
247
248
  result.retried += 1;
248
249
  } catch (error) {
249
- await claims.release(`${triageRecordId}:${value.startedAt}`);
250
+ if (TRANSIENT_DISPATCH_FAILURES.has(error.message)) await claims.release(`${triageRecordId}:${value.startedAt}`);
250
251
  logger.error('[recommendationRecovery] retry of an interrupted run could not be dispatched', { ...run, error: error.message });
251
252
  }
252
253
  }
@@ -153,7 +153,7 @@ function handleTriageCompleted(rawPayload, { trigger = 'auna', runId = null, sup
153
153
  inflightRuns.set(payload.triageRecordId, inflight);
154
154
  inflight.leaseWritten = inflightLeases.set(payload.triageRecordId, lease);
155
155
  if (shuttingDown) inflight.interrupted = inflight.leaseWritten;
156
- inflight.leaseWritten
156
+ Promise.resolve()
157
157
  .then(() => generateTriageRecommendations({ payload, provider: requireGatewayProvider(), runId, supportRouting }))
158
158
  .then((settle) => {
159
159
  logger.info('[triageRecommendation] settled', { code: payload.patientCode, triageRecordId: payload.triageRecordId, status: settle.status, reason: settle.reason });
@@ -181,6 +181,7 @@ function handleTriageCompleted(rawPayload, { trigger = 'auna', runId = null, sup
181
181
  .finally(async () => {
182
182
  if (inflightRuns.get(payload.triageRecordId) !== inflight) return;
183
183
  inflightRuns.delete(payload.triageRecordId);
184
+ await inflight.leaseWritten;
184
185
  await inflight.interrupted;
185
186
  await inflightLeases.release(payload.triageRecordId);
186
187
  });
@@ -108,11 +108,12 @@ class WriteClaimStore {
108
108
  }
109
109
  }
110
110
 
111
- async listActive() {
111
+ async listActive(valueMatch = {}) {
112
112
  if (!this._durable()) return null;
113
+ const query = { key: new RegExp(`^${this.namespace}:`), expiresAt: { $gt: new Date() } };
114
+ for (const [field, expected] of Object.entries(valueMatch)) query[`value.${field}`] = expected;
113
115
  try {
114
- const claims = await WriteClaim.find({ key: new RegExp(`^${this.namespace}:`), expiresAt: { $gt: new Date() } })
115
- .limit(100).lean();
116
+ const claims = await WriteClaim.find(query).sort({ createdAt: -1 }).limit(100).lean();
116
117
  return claims.map((claim) => ({ key: claim.key.slice(this.namespace.length + 1), value: claim.value }));
117
118
  } catch (error) {
118
119
  logger.warn('[writeClaimStore] Claims could not be listed', { namespace: this.namespace, error: error.message });
@@ -10,7 +10,7 @@ const { countMessages, getMessages } = require('./messageService');
10
10
  const { logPatientChange } = require('./patientService');
11
11
  const { getThreadInfo } = require('./threadService');
12
12
  const { AUTO_HANDOFF_OPERATOR, BOOKKEEPING, DRAFT_OPERATOR, MAX_DOCTOR_UPDATES, PRE_DECISION_STATUSES, caseTakenReason, handOffToDoctor, teamAlertIdentity } = require('./escalationReviewService');
13
- const { graveMissingOf, isDraftCurrent, pendingFlagsOf } = require('./gravePendingService');
13
+ const { graveMissingOf, isDraftCurrent, pendingFlagsOf, stillDocumented } = require('./gravePendingService');
14
14
  const { BUSINESS_HOURS_LEVELS, pendingWaitMinutes, quietReminderMinutes, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
15
15
  const { sendGroupNotice, sendTeamAlert } = require('./teamAlertService');
16
16
  const { digestRecipient, digestTimeOf, urgentDigestLive } = require('./doctorDigestService');
@@ -38,7 +38,11 @@ const ASK_RULES = 'No agregues otras preguntas, no repitas lo que ya le dijiste
38
38
  const blockingAskText = (question) => `La revisión de esta escalación necesita un dato que todavía falta. Pregúntale a la paciente, en un solo mensaje breve y con tus palabras: «${question}». ${ASK_RULES}`;
39
39
  const graveAskText = (flags) => `La revisión de esta escalación necesita saber si la paciente tiene: ${flags.join('; ')}. Pregúntale, en un solo mensaje breve y con palabras sencillas, por lo que ella pueda notar o medir, sin nombrar diagnósticos. ${ASK_RULES}`;
40
40
 
41
- const noteOf = (text) => oneLineOf(text).slice(0, MAX_NOTE_LENGTH);
41
+ // A note too long for the template ends on a whole word with «…», so the cut shows.
42
+ const noteOf = (text) => {
43
+ const line = oneLineOf(text);
44
+ return line.length <= MAX_NOTE_LENGTH ? line : `${line.slice(0, MAX_NOTE_LENGTH - 1).replace(/\s+\S*$/, '')}…`;
45
+ };
42
46
  const flagKey = (flag) => String(flag ?? '').trim().toLowerCase();
43
47
  const timeOf = (value) => new Date(value).getTime();
44
48
  const minutesSince = (from, now) => (now.getTime() - timeOf(from)) / 60000;
@@ -75,7 +79,9 @@ function outcomeOf(review, clock, now) {
75
79
  const held = teamFirst && grave.some(({ flag }) => now.getTime() < graveDueAt(review, clock, flag) + wait * 60000);
76
80
  if (grave.length || present.length) {
77
81
  const missing = grave.length && `Falta dato grave: ${grave.map(({ flag }) => flag).join(', ')}${teamFirst && !held ? ' (no se consiguió)' : ''}`;
78
- const note = [present.length && `Bandera grave presente: ${present.join(', ')}`, missing];
82
+ // A grave datum still inside its wait goes in the note too, so the doctor knows it is still open.
83
+ const pending = pendingFlagsOf(review, clock.since).flags.map(({ flag }) => flag).filter((flag) => !grave.some((entry) => entry.flag === flag));
84
+ const note = [present.length && `Bandera grave presente: ${present.join(', ')}`, missing, pending.length && `Pendiente: ${pending.join(', ')}`];
79
85
  return { grave, update, notify, held, note: withUpdate(noteOf(note.filter(Boolean).join(' · '))) };
80
86
  }
81
87
  // A grave question still inside its wait holds the case even when the rest is enough.
@@ -351,13 +357,21 @@ async function remindQuietPatient(review, clock, now) {
351
357
 
352
358
  // Once per draft the bot asks its blocking question or the pending grave data, unless a question is open; after a patient message, once the bot replied.
353
359
  async function askBlockingQuestion(review, clock, now) {
354
- if (!OUTCOME_LEVELS.includes(clock.level) || review.status !== 'draft_ready' || review.closedAt) return;
360
+ // With the doctor, only a case the bot handed over is still asked, and only its grave data.
361
+ const withDoctor = review.status === 'awaiting_doctor';
362
+ if (!OUTCOME_LEVELS.includes(clock.level) || !(review.status === 'draft_ready' || (withDoctor && stillDocumented(review))) || review.closedAt) return;
355
363
  const latest = (review.drafts ?? []).at(-1);
356
364
  if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return;
357
- const graveFlags = latest.blockingQuestion || latest.urgentPresentRedFlags?.length ? []
358
- : pendingFlagsOf(review, clock.since).flags.filter(({ unobtainable }) => !unobtainable).map(({ flag }) => flag);
359
- const question = latest.blockingQuestion || graveFlags.join('; ') || null;
360
- const flags = latest.blockingQuestion ? [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf) : graveFlags;
365
+ const blocking = withDoctor ? null : latest.blockingQuestion;
366
+ // With the doctor, a datum already asked or already sent to the team is not asked again on every redraft.
367
+ const settled = withDoctor ? new Set([
368
+ ...(review.graveAlerts ?? []).filter((entry) => timeOf(entry.since) === clock.since.getTime()).map((entry) => entry.flag),
369
+ ...(review.blockingAsks ?? []).filter((entry) => ASKED_OUTCOMES.includes(entry.outcome) && timeOf(entry.draftAt) >= clock.since.getTime()).flatMap((entry) => entry.flags ?? []),
370
+ ].map(normalizedKeyOf)) : new Set();
371
+ const graveFlags = blocking || latest.urgentPresentRedFlags?.length ? []
372
+ : pendingFlagsOf(review, clock.since).flags.filter(({ flag, unobtainable }) => !unobtainable && !settled.has(flag)).map(({ flag }) => flag);
373
+ const question = blocking || graveFlags.join('; ') || null;
374
+ const flags = blocking ? [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf) : graveFlags;
361
375
  if (!question) return;
362
376
  const asks = review.blockingAsks ?? [];
363
377
  if (asks.some((entry) => timeOf(entry.draftAt) === timeOf(latest.createdAt))) return;
@@ -377,11 +391,11 @@ async function askBlockingQuestion(review, clock, now) {
377
391
  // The turn runs in the background so the sweep does not wait on it; while it waits for the chat lock the case can be handed over, redrafted or taken.
378
392
  const beforeRun = async () => {
379
393
  const fresh = await getEscalationReview().findById(review._id).lean();
380
- if (!fresh || fresh.closedAt || fresh.status !== 'draft_ready') return 'moved';
394
+ if (!fresh || fresh.closedAt || fresh.status !== review.status || (withDoctor && !stillDocumented(fresh))) return 'moved';
381
395
  if (!isDraftCurrent(fresh, latest) || timeOf(fresh.drafts?.at(-1)?.createdAt) !== timeOf(latest.createdAt)) return 'superseded';
382
396
  return takenOf(fresh, clock);
383
397
  };
384
- const instruction = latest.blockingQuestion ? blockingAskText(latest.blockingQuestion) : graveAskText(graveFlags);
398
+ const instruction = blocking ? blockingAskText(blocking) : graveAskText(graveFlags);
385
399
  getMessaging().processInstruction(review.patientCode, instruction, 'developer', { triggeredBy: OPERATOR, beforeRun })
386
400
  .then((result) => result?.outcome ?? null, (error) => {
387
401
  logger.error('[CharacterizationOutcome] The blocking question was not asked', {
@@ -406,9 +420,12 @@ async function askBlockingQuestion(review, clock, now) {
406
420
  async function settleCharacterization(review, clock, now) {
407
421
  if (!clock) return;
408
422
  const outcome = outcomeOf(review, clock, now);
409
- const graveWork = outcome?.grave.length || unsentGraveAlerts(review, clock).length;
423
+ // With the doctor after the bot's handoff, a grave datum falls due even when the patient writes nothing more.
424
+ const grave = outcome?.grave
425
+ ?? (OUTCOME_LEVELS.includes(clock.level) && review.status === 'awaiting_doctor' && stillDocumented(review) ? graveMissingOf(review, clock, now) : []);
426
+ const graveWork = grave.length || unsentGraveAlerts(review, clock).length;
410
427
  const hospitalized = graveWork ? Boolean((await getThreadInfo(review.patientCode))?.hospitalizedAt) : false;
411
- const claimed = outcome?.grave.length && !hospitalized ? await claimGraveAlerts(review, clock, outcome.grave, now) : [];
428
+ const claimed = grave.length && !hospitalized ? await claimGraveAlerts(review, clock, grave, now) : [];
412
429
  const attempts = attemptsOf(review, clock);
413
430
  // Each failure doubles the wait; after the last attempt the team hands the case over by hand.
414
431
  const backingOff = attempts >= MAX_HANDOFF_ATTEMPTS
@@ -1,6 +1,6 @@
1
1
  const { normalizedKeyOf } = require('../utils/coercionUtils');
2
2
 
3
- const { DOCUMENTING_STATUSES } = require('./escalationReviewService');
3
+ const { AUTO_HANDOFF_OPERATOR, DOCUMENTING_STATUSES } = require('./escalationReviewService');
4
4
  const { pendingWaitMinutes } = require('./reviewDeadlineService');
5
5
 
6
6
  const keysOf = (flags) => [...new Set((flags ?? []).map(normalizedKeyOf).filter(Boolean))];
@@ -20,6 +20,10 @@ function pendingFlagsOf(review, since) {
20
20
  return { latest: drafts.at(-1) ?? null, flags: [...firstSeen].map(([flag, firstSeenAt]) => ({ flag, firstSeenAt, unobtainable: unobtainable.includes(flag) })) };
21
21
  }
22
22
 
23
+ // The bot keeps documenting a case it handed to the doctor itself, so its grave questions still wait for the patient there.
24
+ const stillDocumented = (review) => DOCUMENTING_STATUSES.includes(review.status)
25
+ || (review.status === 'awaiting_doctor' && review.doctorHandoffs?.at(-1)?.sentBy === AUTO_HANDOFF_OPERATOR);
26
+
23
27
  // The latest draft speaks for the case only while no newer patient turn or redraft is waiting to replace it.
24
28
  const isDraftCurrent = (review, latest) => !review.draftDueAt
25
29
  && !(review.updates ?? []).some((update) => new Date(update.at).getTime() > new Date(latest.createdAt).getTime());
@@ -30,8 +34,8 @@ function graveMissingOf(review, clock, now) {
30
34
  if (!limit) return [];
31
35
  const { latest, flags } = pendingFlagsOf(review, clock.since);
32
36
  if (!latest || !isDraftCurrent(review, latest)) return [];
33
- // Once the case left documenting (with the doctor) no new draft comes, so the wait no longer means unanswered.
34
- const waiting = DOCUMENTING_STATUSES.includes(review.status);
37
+ // Once a person handed the case over no new draft comes, so the wait no longer means unanswered.
38
+ const waiting = stillDocumented(review);
35
39
  const isDue = ({ firstSeenAt, unobtainable }) => unobtainable || (waiting && now.getTime() - firstSeenAt.getTime() >= limit * 60 * 1000);
36
40
  if (!flags.some(isDue)) return [];
37
41
  // Only the first alert gathers the data still waiting; one that appears after it waits its own time.
@@ -40,4 +44,4 @@ function graveMissingOf(review, clock, now) {
40
44
  .map(({ flag, firstSeenAt, unobtainable }) => ({ flag, firstSeenAt, reason: unobtainable ? 'unobtainable' : 'unanswered' }));
41
45
  }
42
46
 
43
- module.exports = { graveMissingOf, isDraftCurrent, pendingFlagsOf };
47
+ module.exports = { graveMissingOf, isDraftCurrent, pendingFlagsOf, stillDocumented };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.1.0-dev.18137",
3
+ "version": "6.1.0-dev.18186",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",