@peopl-health/nexus 6.1.0-dev.18138 → 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, urgent } = 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.
@@ -99,7 +99,7 @@ function symptomParagraph(entry, fallbackSymptom) {
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
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.join(', '))}`,
102
+ !proposedDrugs(entry).length && urgent.length && `Falta descartar: ${sentence(urgent.map((flag) => (unobtainable.includes(flag) ? `${flag} (no lo puede dar)` : flag)).join(', '))}`,
103
103
  proposalLine(entry),
104
104
  ].filter(Boolean).join(' ');
105
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 });
@@ -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,9 +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
- // A grave datum still inside its wait goes in the note too, so the doctor knows it is being asked.
79
- const asking = pendingFlagsOf(review, clock.since).flags.map(({ flag }) => flag).filter((flag) => !grave.some((entry) => entry.flag === flag));
80
- const note = [present.length && `Bandera grave presente: ${present.join(', ')}`, missing, asking.length && `Preguntando: ${asking.join(', ')}`];
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(', ')}`];
81
85
  return { grave, update, notify, held, note: withUpdate(noteOf(note.filter(Boolean).join(' · '))) };
82
86
  }
83
87
  // A grave question still inside its wait holds the case even when the rest is enough.
@@ -359,8 +363,13 @@ async function askBlockingQuestion(review, clock, now) {
359
363
  const latest = (review.drafts ?? []).at(-1);
360
364
  if (latest?.writtenBy !== DRAFT_OPERATOR || timeOf(latest.createdAt) < clock.since.getTime() || !isDraftCurrent(review, latest)) return;
361
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();
362
371
  const graveFlags = blocking || latest.urgentPresentRedFlags?.length ? []
363
- : pendingFlagsOf(review, clock.since).flags.filter(({ unobtainable }) => !unobtainable).map(({ flag }) => flag);
372
+ : pendingFlagsOf(review, clock.since).flags.filter(({ flag, unobtainable }) => !unobtainable && !settled.has(flag)).map(({ flag }) => flag);
364
373
  const question = blocking || graveFlags.join('; ') || null;
365
374
  const flags = blocking ? [latest.blockingFlag].filter(Boolean).map(normalizedKeyOf) : graveFlags;
366
375
  if (!question) return;
@@ -411,9 +420,12 @@ async function askBlockingQuestion(review, clock, now) {
411
420
  async function settleCharacterization(review, clock, now) {
412
421
  if (!clock) return;
413
422
  const outcome = outcomeOf(review, clock, now);
414
- 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;
415
427
  const hospitalized = graveWork ? Boolean((await getThreadInfo(review.patientCode))?.hospitalizedAt) : false;
416
- 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) : [];
417
429
  const attempts = attemptsOf(review, clock);
418
430
  // Each failure doubles the wait; after the last attempt the team hands the case over by hand.
419
431
  const backingOff = attempts >= MAX_HANDOFF_ATTEMPTS
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.1.0-dev.18138",
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",