@peopl-health/nexus 6.5.0-dev.19149 → 6.5.0-dev.20073

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.
Files changed (42) hide show
  1. package/lib/clinical/AssistantProcessor.js +3 -1
  2. package/lib/clinical/config/planTextsConfig.js +41 -0
  3. package/lib/clinical/flags/escalationFlags.js +15 -0
  4. package/lib/clinical/helpers/doctorPlanHelper.js +32 -23
  5. package/lib/clinical/helpers/legacyContextHelper.js +6 -2
  6. package/lib/clinical/helpers/planTextHelper.js +9 -2
  7. package/lib/clinical/protocols/treatmentFormulary.js +3 -3
  8. package/lib/clinical/services/bridgeService.js +2 -2
  9. package/lib/clinical/services/checkInDueService.js +3 -2
  10. package/lib/clinical/services/clinicalAirtableService.js +3 -2
  11. package/lib/clinical/services/clinicalExtractionService.js +9 -2
  12. package/lib/clinical/services/contingencyDispatchService.js +8 -4
  13. package/lib/clinical/services/doctorPlanService.js +27 -11
  14. package/lib/clinical/tools/deliverPatientMessageTool.js +1 -1
  15. package/lib/clinical/tools/getPatientRiskAssessmentTool.js +1 -1
  16. package/lib/clinical/tools/getRouterContextBundleTool.js +1 -1
  17. package/lib/clinical/tools/reportMedicalEscalationTool.js +1 -0
  18. package/lib/clinical/tools/schedulePatientReminderTool.js +10 -1
  19. package/lib/config/awsConfig.js +1 -1
  20. package/lib/controllers/assistantController.js +5 -2
  21. package/lib/controllers/escalationReviewController.js +16 -3
  22. package/lib/controllers/messageController.js +5 -6
  23. package/lib/core/NexusMessaging.js +16 -18
  24. package/lib/fhir/constants/escalationCaseStatus.js +1 -1
  25. package/lib/helpers/caregiverHelper.js +8 -0
  26. package/lib/helpers/templateFlowControllerHelper.js +9 -48
  27. package/lib/index.d.ts +3 -3
  28. package/lib/models/escalationReviewModel.js +32 -2
  29. package/lib/services/assistantMessageService.js +11 -6
  30. package/lib/services/caseFollowUpService.js +226 -0
  31. package/lib/services/caseFollowUpSweepService.js +89 -0
  32. package/lib/services/characterizationOutcomeService.js +25 -9
  33. package/lib/services/escalationCaseStateService.js +68 -0
  34. package/lib/services/escalationReviewService.js +90 -27
  35. package/lib/services/flowDataExchangeService.js +6 -35
  36. package/lib/services/reviewAlertSweepService.js +19 -1
  37. package/lib/services/reviewBoardService.js +24 -6
  38. package/lib/services/reviewDeadlineService.js +1 -1
  39. package/lib/services/untakenAlertService.js +9 -7
  40. package/lib/services/watchExpiryService.js +162 -0
  41. package/lib/utils/textMatchUtils.js +52 -18
  42. package/package.json +1 -1
@@ -0,0 +1,162 @@
1
+ const { logger } = require('../utils/logger');
2
+ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
+ const { getEscalationReview } = require('../models/escalationReviewModel');
4
+ const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
5
+ const { escalationWatchExpiryLive, escalationWatchTeamNoticeLive } = require('../clinical/flags/escalationFlags');
6
+
7
+ const { countMessages } = require('./messageService');
8
+ const { logPatientChange } = require('./patientService');
9
+ const { getThreadInfo } = require('./threadService');
10
+ const { BOOKKEEPING, teamAlertIdentity } = require('./escalationReviewService');
11
+ const { responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
12
+ const { sendGroupNotice } = require('./teamAlertService');
13
+
14
+ const OPERATOR = 'bot:watchExpiry';
15
+ const AUDIT_SOURCE = 'escalation_review';
16
+ const SWEEP_LIMIT = 50;
17
+ const REMINDER_TEXT = 'Hola, ¿cómo sigues? Cuéntame por aquí cómo te has sentido.';
18
+ const TEAM_HEADER = '⏰ Vigilancia vencida, sigue abierta';
19
+ const TEAM_ACTION = 'Qué hacer: ver cómo sigue y cerrar el caso o pedir indicaciones al médico';
20
+ const ANSWERED_NOTE = 'Respondió al recordatorio, pero no quedó claro que siga igual o mejor';
21
+ const MAX_TEAM_ATTEMPTS = 3;
22
+ // After the reminder the patient gets this long to answer before the team is told.
23
+ const TEAM_WAIT_MS = 2 * 60 * 60 * 1000;
24
+ // A reminder this late (an outage, a deploy) is not sent; the team notice still goes.
25
+ const STALE_MS = 30 * 60 * 1000;
26
+ const getMessaging = () => require('../core/NexusMessaging');
27
+ const REMINDED_UNTILS = { $map: { input: { $filter: { input: { $ifNull: ['$watchNotices', []] }, cond: { $eq: ['$$this.kind', 'reminder'] } } }, in: '$$this.until' } };
28
+
29
+ const timeOf = (value) => new Date(value).getTime();
30
+
31
+ const audit = (review, changes) => logPatientChange({
32
+ code: review.patientCode,
33
+ updatedBy: OPERATOR,
34
+ source: AUDIT_SOURCE,
35
+ requestId: null,
36
+ changes: { escalationReviewId: String(review._id), ...changes },
37
+ }).catch((error) => logger.error('[WatchExpiry] The audit was not written', {
38
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
39
+ }));
40
+
41
+ const noticesOf = (review, kind) => (review.watchNotices ?? []).filter((entry) => entry.kind === kind && timeOf(entry.until) === timeOf(review.monitoringUntil));
42
+ const failed = (entry) => entry.outcome === 'failed';
43
+
44
+ // A notice is claimed before it is sent, so two sweeps never send it twice; only a failed one is tried again.
45
+ async function claim(review, entry) {
46
+ const claimed = await getEscalationReview().updateOne(
47
+ {
48
+ _id: review._id, closedAt: null, status: 'monitoring', monitoringUntil: review.monitoringUntil,
49
+ watchNotices: { $not: { $elemMatch: { kind: entry.kind, until: review.monitoringUntil, outcome: { $ne: 'failed' } } } },
50
+ },
51
+ { $push: { watchNotices: entry } },
52
+ BOOKKEEPING,
53
+ );
54
+ return claimed.modifiedCount > 0;
55
+ }
56
+
57
+ // A crash between the claim and this leaves the outcome null, and the notice is not sent again.
58
+ const settle = (review, kind, fields) => getEscalationReview().updateOne(
59
+ { _id: review._id, watchNotices: { $elemMatch: { kind, until: review.monitoringUntil, outcome: null } } },
60
+ { $set: Object.fromEntries(Object.entries(fields).map(([key, value]) => [`watchNotices.$.${key}`, value])) },
61
+ BOOKKEEPING,
62
+ );
63
+
64
+ async function skipReasonOf(review, due, now) {
65
+ if (now.getTime() - due.getTime() > STALE_MS) return 'stale';
66
+ const thread = await getThreadInfo(review.patientCode);
67
+ if (thread?.stopped === true) return 'thread_paused';
68
+ return null;
69
+ }
70
+
71
+ // Outside the 24 h window sendMessage queues the recovery template, and the reminder goes once the patient answers it.
72
+ async function remindPatient(review, now) {
73
+ const due = teamOpenAt(new Date(review.monitoringUntil), responseDeadlinePolicy());
74
+ if (now < due) return false;
75
+ const skippedReason = await skipReasonOf(review, due, now);
76
+ if (!await claim(review, { until: review.monitoringUntil, kind: 'reminder', sentAt: now, skippedReason, outcome: skippedReason ? 'skipped' : null })) return false;
77
+ if (skippedReason) {
78
+ await audit(review, { action: 'watch_reminder_skipped', reason: skippedReason });
79
+ return true;
80
+ }
81
+ let outcome = 'failed';
82
+ let status = null;
83
+ try {
84
+ const result = await getMessaging().sendMessage({
85
+ code: review.patientCode, body: REMINDER_TEXT, triggeredBy: OPERATOR, idempotencyKey: `watch-reminder:${review._id}:${timeOf(review.monitoringUntil)}`,
86
+ });
87
+ if (result?.success) outcome = result.deferred ? 'queued' : 'sent';
88
+ status = result?.status ?? null;
89
+ } catch (error) {
90
+ status = 'threw';
91
+ logger.error('[WatchExpiry] The watch reminder was not sent', { escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)) });
92
+ }
93
+ // A reminder that failed is not tried again: the team notice still follows it.
94
+ const stored = outcome === 'failed' ? 'not_sent' : outcome;
95
+ await settle(review, 'reminder', { outcome: stored, status });
96
+ await audit(review, { action: `watch_reminder_${stored}`, status });
97
+ return true;
98
+ }
99
+
100
+ async function teamNoticeOf(review, reminder) {
101
+ const { patient, doctor, link } = await teamAlertIdentity(review);
102
+ const reminded = ['sent', 'queued'].includes(reminder.outcome);
103
+ const answered = reminded && await countMessages({ numero: review.patientCode, from_me: false, createdAt: { $gt: reminder.sentAt } });
104
+ const note = answered ? ANSWERED_NOTE : null;
105
+ return {
106
+ body: [TEAM_HEADER, `${patient} (${doctor})`, note, TEAM_ACTION, link].filter(Boolean).join('\n'),
107
+ threadBody: [TEAM_HEADER, note, TEAM_ACTION].filter(Boolean).join('\n'),
108
+ };
109
+ }
110
+
111
+ async function noticeTeam(review, reminder, now) {
112
+ const due = teamOpenAt(new Date(timeOf(reminder.sentAt) + TEAM_WAIT_MS), responseDeadlinePolicy());
113
+ if (now < due) return false;
114
+ const attempts = noticesOf(review, 'team').filter(failed).length;
115
+ if (attempts >= MAX_TEAM_ATTEMPTS) return false;
116
+ if (!await claim(review, { until: review.monitoringUntil, kind: 'team', sentAt: now, skippedReason: null, outcome: null })) return false;
117
+ let delivered = false;
118
+ try {
119
+ const { body, threadBody } = await teamNoticeOf(review, reminder);
120
+ const recordId = [...(review.alarms ?? [])].reverse().find((alarm) => alarm.emergencyRecordId)?.emergencyRecordId;
121
+ const quoted = await readGroupMessageId(recordId, review.patientCode);
122
+ delivered = (await sendGroupNotice(body, quoted, threadBody)).delivered === true;
123
+ } catch (error) {
124
+ logger.error('[WatchExpiry] The watch team notice failed', { escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)) });
125
+ }
126
+ await settle(review, 'team', { outcome: delivered ? 'sent' : 'failed' });
127
+ if (!delivered && attempts + 1 >= MAX_TEAM_ATTEMPTS) logger.error('[WatchExpiry] The watch team notice failed on every attempt', { escalationReviewId: String(review._id) });
128
+ await audit(review, { action: 'watch_team_notified', delivered, attempt: attempts + 1 });
129
+ return true;
130
+ }
131
+
132
+ // A watch that ran out is never closed silently: the patient gets one reminder, then the team is told while its flag is on.
133
+ async function sweepExpiredWatches({ now = new Date() } = {}) {
134
+ if (!escalationWatchExpiryLive()) return 0;
135
+ const teamNotice = escalationWatchTeamNoticeLive();
136
+ // A watch with a case follow-up is followed up there; only the older ones are reminded here.
137
+ const query = { closedAt: null, status: 'monitoring', monitoringUntil: { $lte: now }, caseFollowUp: null };
138
+ // With no team notice a reminded watch has nothing left to send, so it must not hold a sweep slot.
139
+ if (!teamNotice) query.$expr = { $not: [{ $in: ['$monitoringUntil', REMINDED_UNTILS] }] };
140
+ const reviews = await getEscalationReview()
141
+ .find(
142
+ query,
143
+ { patientCode: 1, status: 1, monitoringUntil: 1, watchNotices: 1, 'alarms.emergencyRecordId': 1 },
144
+ )
145
+ .sort({ monitoringUntil: 1 })
146
+ .limit(SWEEP_LIMIT)
147
+ .lean();
148
+ let sent = 0;
149
+ for (const review of reviews) {
150
+ try {
151
+ if (noticesOf(review, 'team').some((entry) => !failed(entry))) continue;
152
+ const [reminder] = noticesOf(review, 'reminder');
153
+ if (reminder && !teamNotice) continue;
154
+ if (await (reminder ? noticeTeam(review, reminder, now) : remindPatient(review, now))) sent += 1;
155
+ } catch (error) {
156
+ logger.error('[WatchExpiry] Could not check an expired watch', { escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)) });
157
+ }
158
+ }
159
+ return sent;
160
+ }
161
+
162
+ module.exports = { REMINDER_TEXT, sweepExpiredWatches };
@@ -30,47 +30,81 @@ function anchorTokens(value) {
30
30
  }
31
31
 
32
32
  const NEGATION_WORDS = new Set(['no', 'ni', 'nunca', 'jamas', 'tampoco']);
33
+ // These only flag a conflict, never drop: «no hay un día sin fiebre» is a fever.
34
+ const CONFLICT_CUES = new Set([...NEGATION_WORDS, 'sin', 'niego', 'nego', 'ningun', 'ninguna']);
35
+ // Words a cue may reach across before the symptom: «no he tenido fiebre», «sin la fiebre».
36
+ const CUE_BRIDGE = new Set(['he', 'ha', 'me', 'le', 'tengo', 'tenido', 'el', 'la', 'de']);
37
+ const CUE_REACH = 2;
38
+ const CLAUSE_BREAK = /[.,;:!?¿¡\n]+/;
33
39
 
34
40
  function hasNegation(text) {
35
41
  return text.split(' ').some((word) => NEGATION_WORDS.has(word));
36
42
  }
37
43
 
38
- function precededByNegation(padded, at) {
39
- const words = padded.slice(0, at + 1).trim().split(' ');
40
- return NEGATION_WORDS.has(words[words.length - 1] || '');
44
+ // Each word with whether a clause starts at it, so «No. Fiebre desde ayer» does not read as negated.
45
+ function clauseWords(value, forAnchor) {
46
+ return String(value ?? '').split(CLAUSE_BREAK).flatMap((clause) => {
47
+ const words = forAnchor(clause).split(' ').filter(Boolean);
48
+ return words.map((word, index) => ({ word, opensClause: index === 0 }));
49
+ });
41
50
  }
42
51
 
43
- function isQuoteAnchored(quote, source, { strict = false } = {}) {
52
+ // «nada de fiebre» negates and «nada más» means only; the «de» must precede the quote («de sangre» is not negated).
53
+ const isCueAt = (words, index, at, cues) => cues.has(words[index].word)
54
+ || (words[index].word === 'nada' && words[index + 1]?.word === 'de' && index + 1 < at);
55
+
56
+ function cueBefore(words, at, { reach, cues }) {
57
+ for (let index = at - 1, bridged = 0; index >= 0 && !words[index + 1].opensClause; index -= 1) {
58
+ if (isCueAt(words, index, at, cues)) return true;
59
+ if (!CUE_BRIDGE.has(words[index].word) || ++bridged > reach) return false;
60
+ }
61
+ return false;
62
+ }
63
+
64
+ function occurrencesOf(needle, words) {
65
+ const starts = [];
66
+ for (let at = 0; at + needle.length <= words.length; at += 1) {
67
+ if (needle.every((word, offset) => words[at + offset].word === word)) starts.push(at);
68
+ }
69
+ return starts;
70
+ }
71
+
72
+ function prepare(quote, source, strict) {
44
73
  const forAnchor = strict ? (value) => normalizeForAnchor(nameComparators(value)) : normalizeForAnchor;
45
- const haystack = forAnchor(source);
74
+ const words = clauseWords(strict ? nameComparators(source) : source, normalizeForAnchor);
46
75
  const needle = forAnchor(quote);
47
- if (!haystack || !needle) return false;
76
+ return { words, needle, starts: needle ? occurrencesOf(needle.split(' '), words) : [] };
77
+ }
48
78
 
49
- const padded = ` ${haystack} `;
50
- const target = ` ${needle} `;
51
- const quoteNegated = hasNegation(needle);
79
+ // A quote read as present must not follow «no» directly («no fiebre»); one read as negated may sit anywhere.
80
+ function isQuoteAnchored(quote, source, { strict = false, negated = false } = {}) {
81
+ const { words, needle, starts } = prepare(quote, source, strict);
82
+ if (!words.length || !needle) return false;
52
83
 
53
- let at = padded.indexOf(target);
54
- const anyOccurrence = at !== -1;
55
- while (at !== -1) {
56
- if (quoteNegated || !precededByNegation(padded, at)) return true;
57
- at = padded.indexOf(target, at + 1);
58
- }
59
- if (anyOccurrence) return false;
60
- if (strict) return false;
84
+ const quoteNegated = hasNegation(needle);
85
+ if (starts.some((at) => quoteNegated || negated || !cueBefore(words, at, { reach: 0, cues: NEGATION_WORDS }))) return true;
86
+ if (starts.length || strict) return false;
61
87
 
62
88
  const tokens = anchorTokens(quote);
63
89
  if (!tokens.length) return false;
64
- if (quoteNegated && !hasNegation(haystack)) return false;
90
+ if (quoteNegated && !words.some(({ word }) => NEGATION_WORDS.has(word))) return false;
65
91
  const present = new Set(anchorTokens(source));
66
92
  const matched = tokens.filter((token) => present.has(token)).length;
67
93
  return matched / tokens.length >= QUOTE_ANCHOR_MIN_OVERLAP;
68
94
  }
69
95
 
96
+ // A cue a few words before a quote read as present («no he tenido fiebre») contradicts the model's polarity.
97
+ function negationNearQuote(quote, source) {
98
+ const { needle, words, starts } = prepare(quote, source, false);
99
+ if (!needle || needle.split(' ').some((word) => CONFLICT_CUES.has(word))) return false;
100
+ return starts.length > 0 && starts.every((at) => cueBefore(words, at, { reach: CUE_REACH, cues: CONFLICT_CUES }));
101
+ }
102
+
70
103
  const escapeRegExp = (value) => String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
71
104
 
72
105
  module.exports = {
73
106
  escapeRegExp,
74
107
  isQuoteAnchored,
108
+ negationNearQuote,
75
109
  normalizeForAnchor,
76
110
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.5.0-dev.19149",
3
+ "version": "6.5.0-dev.20073",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",