@peopl-health/nexus 5.56.13 → 5.56.15

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.
@@ -4,6 +4,14 @@ function inboundRecoveryLive() {
4
4
  return String(runtimeConfig.get('INBOUND_RECOVERY_LIVE', 'true')).trim().toLowerCase() === 'true';
5
5
  }
6
6
 
7
+ const COLD_MODES = ['off', 'report', 'file'];
8
+
9
+ function coldInboundMode() {
10
+ const raw = String(runtimeConfig.get('COLD_INBOUND_MODE', 'off')).trim().toLowerCase();
11
+ return COLD_MODES.includes(raw) ? raw : 'off';
12
+ }
13
+
7
14
  module.exports = {
8
15
  inboundRecoveryLive,
16
+ coldInboundMode,
9
17
  };
@@ -21,6 +21,7 @@ const noteFactSchema = new mongoose.Schema({
21
21
  quote: { type: String, default: null },
22
22
  callLogNumber: { type: Number, required: true },
23
23
  state: { type: String, enum: ['proposed', 'settling', 'confirmed', 'declined'], default: 'proposed' },
24
+ settlingAt: { type: Date, default: null },
24
25
  settledBy: { type: String, default: null },
25
26
  }, { timestamps: { createdAt: true, updatedAt: false } });
26
27
 
@@ -103,6 +103,11 @@ messageSchema.index({ createdAt: -1 }, { name: 'global_sort_idx' });
103
103
 
104
104
  messageSchema.index({ message_id: 1 }, { name: 'message_id_idx', sparse: true });
105
105
 
106
+ messageSchema.index(
107
+ { createdAt: -1 },
108
+ { name: 'failed_send_idx', partialFilterExpression: { 'statusInfo.status': 'failed' } },
109
+ );
110
+
106
111
  messageSchema.index({ turnId: 1 }, { name: 'turn_id_idx', sparse: true });
107
112
 
108
113
  messageSchema.index({ traceId: 1 }, { name: 'trace_id_idx', sparse: true });
@@ -40,9 +40,6 @@ const MAX_TEMPLATE_TEXT_LENGTH = 800;
40
40
  const STATUS_CONFLICT = 'The escalation review does not allow this action in its current status';
41
41
  const CANCEL_NEEDS_REASON = 'The doctor is already waiting on this review; cancelling it requires a reason';
42
42
  const INTERRUPTION_CONFLICT = 'The escalation review was interrupted; closing it requires interruptionNotes stating what was verified';
43
- // A send still in flight also sits in handing_off or sending, and the patient-send path reaches
44
- // Airtable, whose shared client waits up to 300s. Adjudicating before then can close the review
45
- // under a worker that is about to record a message it really sent.
46
43
  const INTERRUPTION_GRACE_MS = 10 * 60 * 1000;
47
44
  const INTERRUPTION_TOO_SOON = 'The escalation review may still be sending; wait for it to settle before adjudicating it';
48
45
 
@@ -162,9 +159,6 @@ const releaseReview = (id, from, to, claim = null) => getEscalationReview().upda
162
159
  { $set: { status: to, operationClaim: null } },
163
160
  );
164
161
 
165
- // The record of a message that really went out is never gated on status: the operator may have
166
- // adjudicated the review while the send was still running. Only the status transition is gated,
167
- // so a closed review keeps its handoff or delivery without being resurrected.
168
162
  async function completeOperation(id, claim, fromStatus, recordUpdate, nextStatus, lateUpdate = recordUpdate) {
169
163
  const EscalationReview = getEscalationReview();
170
164
  const claimCleared = (update) => ({ ...update, $set: { ...update.$set, operationClaim: null } });
@@ -630,6 +624,18 @@ async function proposeNoteFacts(review, operator, requestId) {
630
624
  }
631
625
  }
632
626
 
627
+ // A process that dies between the claim and the settlement leaves its facts in 'settling' with
628
+ // nothing left to move them. After this long they are offered again: re-storing an assertion the
629
+ // record already holds merges onto the same claim rather than adding a second one.
630
+ const SETTLING_TTL_MS = 10 * 60 * 1000;
631
+
632
+ function settleable(fact, now) {
633
+ if (fact.state === 'proposed') return true;
634
+ if (fact.state !== 'settling') return false;
635
+ const since = Date.parse(fact.settlingAt ?? '');
636
+ return !Number.isFinite(since) || now.getTime() - since >= SETTLING_TTL_MS;
637
+ }
638
+
633
639
  function factIndexes(values, field) {
634
640
  if (!Array.isArray(values)) throw httpError(400, `${field} must be an array`);
635
641
  const indexes = new Set();
@@ -652,18 +658,20 @@ async function confirmNoteFacts({ id, accepted = [], declined = [], confirmedBy,
652
658
  const review = await loadReview(reviewId);
653
659
  if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
654
660
  const proposed = (review.noteFacts ?? []).map((fact, index) => ({ fact, index }))
655
- .filter(({ fact }) => fact.state === 'proposed');
661
+ .filter(({ fact }) => settleable(fact, now));
656
662
  const unknown = [...wanted, ...refused].find((index) => !proposed.some((entry) => entry.index === index));
657
663
  if (unknown !== undefined) throw httpError(409, 'That fact is not waiting to be confirmed');
658
664
  if (!wanted.size && !refused.size) return review;
659
665
 
660
666
  // Nothing is final until the record has taken it, declines included: a request that fails
661
- // halfway has to leave the whole selection offerable again.
667
+ // halfway has to leave the whole selection offerable again. The filter names the state each
668
+ // fact was in when it was read, so a claim that raced another request finds nothing and loses.
662
669
  const claim = { _id: reviewId, status: { $in: DOCUMENTING_STATUSES } };
663
670
  const claimed = {};
664
- for (const index of [...wanted, ...refused]) {
665
- claim[`noteFacts.${index}.state`] = 'proposed';
671
+ for (const { fact, index } of proposed.filter((entry) => wanted.has(entry.index) || refused.has(entry.index))) {
672
+ claim[`noteFacts.${index}.state`] = fact.state;
666
673
  claimed[`noteFacts.${index}.state`] = 'settling';
674
+ claimed[`noteFacts.${index}.settlingAt`] = now;
667
675
  claimed[`noteFacts.${index}.settledBy`] = operator;
668
676
  }
669
677
  const held = await getEscalationReview().findOneAndUpdate(claim, { $set: claimed }, { new: true }).lean();
@@ -686,9 +694,18 @@ async function confirmNoteFacts({ id, accepted = [], declined = [], confirmedBy,
686
694
  }
687
695
  }
688
696
 
697
+ const settledAs = (index) => {
698
+ if (wanted.has(index)) return stored.has(index) ? 'confirmed' : 'proposed';
699
+ return failure ? 'proposed' : 'declined';
700
+ };
689
701
  const settle = {};
690
- for (const index of wanted) settle[`noteFacts.${index}.state`] = stored.has(index) ? 'confirmed' : 'proposed';
691
- for (const index of refused) settle[`noteFacts.${index}.state`] = failure ? 'proposed' : 'declined';
702
+ for (const index of [...wanted, ...refused]) {
703
+ const state = settledAs(index);
704
+ settle[`noteFacts.${index}.state`] = state;
705
+ settle[`noteFacts.${index}.settlingAt`] = null;
706
+ // A fact handed back never got settled, so it must stop naming the operator who tried.
707
+ if (state === 'proposed') settle[`noteFacts.${index}.settledBy`] = null;
708
+ }
692
709
  const updated = await getEscalationReview()
693
710
  .findOneAndUpdate({ _id: reviewId }, { $set: settle }, { new: true }).lean()
694
711
  .catch((error) => {
@@ -5,7 +5,7 @@ const { createIntervalSweeper } = require('../utils/intervalSweeper');
5
5
  const { Thread } = require('../models/threadModel');
6
6
  const { botIsPaused } = require('../helpers/pausedThreadHelper');
7
7
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
8
- const { inboundRecoveryLive } = require('../clinical/flags/inboundRecoveryFlags');
8
+ const { coldInboundMode, inboundRecoveryLive } = require('../clinical/flags/inboundRecoveryFlags');
9
9
  const { formatOpsAlert, recordUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
10
10
  const { WriteClaimStore } = require('../clinical/services/writeClaimStore');
11
11
  const { getMessages, countMessages, aggregateMessages } = require('./messageService');
@@ -18,6 +18,12 @@ const MAX_RECOVERIES_PER_PASS = 3;
18
18
  const CLAIM_TTL_MS = 24 * 60 * 60 * 1000;
19
19
  const REPLAY_SETTLE_MS = 5 * 60 * 1000;
20
20
  const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
21
+ const COLD_MIN_AGE_MS = 4 * 60 * 60 * 1000;
22
+ const COLD_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
23
+ const COLD_TICKETS_PER_PASS = 25;
24
+ // The cold band asks the same question of thirty days instead of one hour, so its page has
25
+ // to be wide enough that answered conversations at the head cannot mask the rest.
26
+ const COLD_SCAN_LIMIT = 1000;
21
27
  const PATIENT_CONTACT_WINDOW = { timeZone: 'America/Monterrey', startHour: 8, endHour: 21 };
22
28
 
23
29
  const recoveryClaims = new WriteClaimStore({ namespace: 'inbound-recovery', ttlMs: CLAIM_TTL_MS, maxSize: 500 });
@@ -26,35 +32,41 @@ const ticketClaims = new WriteClaimStore({ namespace: 'inbound-recovery-ticket',
26
32
  const FAILED_SEND = { 'statusInfo.status': 'failed', message_id: null };
27
33
  const UNANSWERED_QUESTION = 'El paciente escribió y no recibió respuesta.';
28
34
 
29
- async function unansweredThreads(now) {
35
+ async function unansweredThreads(now, { minAgeMs = MIN_AGE_MS, maxAgeMs = MAX_AGE_MS, limit = SCAN_LIMIT } = {}) {
30
36
  return Thread.find(
31
37
  {
32
38
  stopped: false,
33
39
  lastMessageFromMe: false,
34
- lastMessageAt: { $gte: new Date(now.getTime() - MAX_AGE_MS), $lte: new Date(now.getTime() - MIN_AGE_MS) },
40
+ lastMessageAt: { $gte: new Date(now.getTime() - maxAgeMs), $lte: new Date(now.getTime() - minAgeMs) },
35
41
  },
36
42
  { code: 1, lastMessageAt: 1 },
37
- ).sort({ lastMessageAt: 1 }).limit(SCAN_LIMIT).lean();
43
+ ).sort({ lastMessageAt: 1 }).limit(limit).lean();
38
44
  }
39
45
 
40
- async function codesWithAFailedSend(now) {
46
+ async function codesWithAFailedSend(now, { maxAgeMs = MAX_AGE_MS, limit = SCAN_LIMIT } = {}) {
41
47
  const rows = await aggregateMessages([
42
- { $match: { ...FAILED_SEND, from_me: true, createdAt: { $gte: new Date(now.getTime() - MAX_AGE_MS) } } },
48
+ { $match: { ...FAILED_SEND, from_me: true, createdAt: { $gte: new Date(now.getTime() - maxAgeMs) } } },
43
49
  { $group: { _id: '$numero', firstFailedAt: { $min: '$createdAt' } } },
44
- { $sort: { firstFailedAt: 1 } },
45
- { $limit: SCAN_LIMIT },
50
+ // _id breaks the tie: without it a page of shared timestamps orders differently each pass.
51
+ { $sort: { firstFailedAt: 1, _id: 1 } },
52
+ { $limit: limit },
46
53
  ]);
47
54
  return rows.map((row) => row._id);
48
55
  }
49
56
 
50
- async function candidateCodes(now) {
51
- const [threads, failedSends] = await Promise.all([unansweredThreads(now), codesWithAFailedSend(now)]);
52
- return [...new Set([...threads.map((thread) => thread.code), ...failedSends].filter(Boolean))];
57
+ async function candidateCodes(now, { threadBand = null, failedMaxAgeMs = MAX_AGE_MS, limit = SCAN_LIMIT } = {}) {
58
+ const [threads, failedSends] = await Promise.all([
59
+ unansweredThreads(now, { ...(threadBand || {}), limit }),
60
+ codesWithAFailedSend(now, { maxAgeMs: failedMaxAgeMs, limit }),
61
+ ]);
62
+ const atCeiling = threads.length >= limit || failedSends.length >= limit;
63
+ const codes = [...new Set([...threads.map((thread) => thread.code), ...failedSends].filter(Boolean))];
64
+ return { codes, atCeiling };
53
65
  }
54
66
 
55
67
  const threadIsOwnedByAHuman = (code) => botIsPaused(code, { label: '[inboundRecovery]' });
56
68
 
57
- async function stillUnanswered(code, now = new Date()) {
69
+ async function stillUnanswered(code, now = new Date(), { minAgeMs = MIN_AGE_MS, maxAgeMs = MAX_AGE_MS } = {}) {
58
70
  const [newest] = await getMessages(
59
71
  { numero: code, from_me: false, interactive_type: null },
60
72
  { select: { _id: 1, createdAt: 1, message_id: 1 }, sort: { createdAt: -1 }, limit: 1 },
@@ -62,14 +74,19 @@ async function stillUnanswered(code, now = new Date()) {
62
74
  if (!newest) return null;
63
75
 
64
76
  const ageMs = now.getTime() - new Date(newest.createdAt).getTime();
65
- if (!Number.isFinite(ageMs) || ageMs < MIN_AGE_MS || ageMs > MAX_AGE_MS) return null;
77
+ if (!Number.isFinite(ageMs) || ageMs < minAgeMs || ageMs > maxAgeMs) return null;
66
78
 
67
79
  const replies = await countMessages({ numero: code, from_me: true, createdAt: { $gt: newest.createdAt }, $nor: [FAILED_SEND] });
68
80
  return replies === 0 ? newest : null;
69
81
  }
70
82
 
71
- // This sweep only ever looks at the last hour, so minutes is the only unit it can reach.
72
- const waitedFor = (ageMs) => `lleva ${Math.max(0, Math.round(ageMs / 60000))} min sin respuesta`;
83
+ function waitedFor(ageMs) {
84
+ const minutes = Math.max(0, Math.round(ageMs / 60000));
85
+ if (minutes < 120) return `lleva ${minutes} min sin respuesta`;
86
+ const hours = Math.round(minutes / 60);
87
+ if (hours < 48) return `lleva ${hours} h sin respuesta`;
88
+ return `lleva ${Math.round(hours / 24)} días sin respuesta`;
89
+ }
73
90
 
74
91
  async function fileTicket(code, alert, ageMs) {
75
92
  try {
@@ -97,7 +114,7 @@ async function sweepUnansweredInbound({
97
114
  } = {}) {
98
115
  let codes;
99
116
  try {
100
- codes = await candidateCodes(now);
117
+ ({ codes } = await candidateCodes(now));
101
118
  } catch (error) {
102
119
  logger.error('[inboundRecovery] unanswered scan failed', { error: error.message });
103
120
  return { scanned: 0, recovered: 0, alerted: 0, skipped: 0 };
@@ -187,6 +204,66 @@ async function sweepUnansweredInbound({
187
204
  return { scanned: candidates.length, recovered, alerted, skipped };
188
205
  }
189
206
 
207
+ const COLD_BAND = { minAgeMs: COLD_MIN_AGE_MS, maxAgeMs: COLD_MAX_AGE_MS };
208
+
209
+ async function sweepColdUnansweredInbound({
210
+ now = new Date(),
211
+ mode = coldInboundMode(),
212
+ isProcessing = () => false,
213
+ isPaused = threadIsOwnedByAHuman,
214
+ ticketGate = ticketClaims,
215
+ alert = recordUnresolvedRequest,
216
+ } = {}) {
217
+ if (mode === 'off') return { waiting: 0, alerted: 0 };
218
+
219
+ const { codes, atCeiling } = await candidateCodes(now, {
220
+ threadBand: COLD_BAND, failedMaxAgeMs: COLD_MAX_AGE_MS, limit: COLD_SCAN_LIMIT,
221
+ });
222
+ // Answered conversations are filtered below, after the page is cut, so a full page is a page
223
+ // that may be hiding patients behind it. Say so rather than let the tail go unseen quietly.
224
+ if (atCeiling) {
225
+ logger.error('[inboundRecovery] the cold scan filled its page; patients may be waiting behind it', {
226
+ limit: COLD_SCAN_LIMIT, found: codes.length,
227
+ });
228
+ }
229
+
230
+ const waiting = [];
231
+ for (const code of codes) {
232
+ if (isProcessing(code)) continue;
233
+ try {
234
+ const inbound = await stillUnanswered(code, now, COLD_BAND);
235
+ if (inbound && !await isPaused(code)) waiting.push({ code, inbound });
236
+ } catch (error) {
237
+ logger.error('[inboundRecovery] could not read one cold conversation; leaving it for the next pass', {
238
+ code, error: error.message,
239
+ });
240
+ }
241
+ }
242
+
243
+ if (!waiting.length) return { waiting: 0, alerted: 0 };
244
+
245
+ waiting.sort((a, b) => new Date(a.inbound.createdAt) - new Date(b.inbound.createdAt));
246
+
247
+ if (mode === 'report') {
248
+ logger.error('[inboundRecovery] patients have been waiting since long before this sweep looked', {
249
+ waiting: waiting.length, oldest: waiting[0].inbound.createdAt, atCeiling, mode,
250
+ });
251
+ return { waiting: waiting.length, alerted: 0 };
252
+ }
253
+
254
+ let alerted = 0;
255
+ for (const { code, inbound } of waiting) {
256
+ if (alerted >= COLD_TICKETS_PER_PASS) break;
257
+ const key = String(inbound._id);
258
+ if (await ticketGate.acquire(key, 'alerted') !== 'acquired') continue;
259
+ if (await fileTicket(code, alert, now.getTime() - new Date(inbound.createdAt).getTime())) alerted += 1;
260
+ else await ticketGate.release(key);
261
+ }
262
+
263
+ logger.error('[inboundRecovery] filed for patients nobody had answered', { waiting: waiting.length, alerted });
264
+ return { waiting: waiting.length, alerted };
265
+ }
266
+
190
267
  function sweepIntervalMs() {
191
268
  const raw = Number(runtimeConfig.get('INBOUND_RECOVERY_SWEEP_INTERVAL_MS'));
192
269
  return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_SWEEP_INTERVAL_MS;
@@ -198,12 +275,18 @@ function startInboundRecoverySweep({ recover, isProcessing, intervalMs } = {}) {
198
275
  if (!sweeper) {
199
276
  sweeper = createIntervalSweeper({
200
277
  label: '[inboundRecovery]',
201
- sweep: () => sweepUnansweredInbound({
202
- recover: typeof recover === 'function'
203
- ? (code) => recover(code, { confirmStillUnanswered: async (c) => Boolean(await stillUnanswered(c)) })
204
- : null,
205
- isProcessing,
206
- }),
278
+ sweep: async () => {
279
+ const live = await sweepUnansweredInbound({
280
+ recover: typeof recover === 'function'
281
+ ? (code) => recover(code, { confirmStillUnanswered: async (c) => Boolean(await stillUnanswered(c)) })
282
+ : null,
283
+ isProcessing,
284
+ });
285
+ await sweepColdUnansweredInbound({ isProcessing }).catch((error) => logger.error(
286
+ '[inboundRecovery] the cold pass failed after the live pass had already run', { error: error.message },
287
+ ));
288
+ return live;
289
+ },
207
290
  defaultIntervalMs: sweepIntervalMs,
208
291
  });
209
292
  }
@@ -221,6 +304,7 @@ module.exports = {
221
304
  startInboundRecoverySweep,
222
305
  stopInboundRecoverySweep,
223
306
  sweepUnansweredInbound,
307
+ sweepColdUnansweredInbound,
224
308
  DEFAULT_SWEEP_INTERVAL_MS,
225
309
  stillUnanswered,
226
310
  threadIsOwnedByAHuman,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.56.13",
3
+ "version": "5.56.15",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",