@peopl-health/nexus 6.0.0-dev.718 → 6.0.0

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 (438) hide show
  1. package/README.md +104 -0
  2. package/lib/adapters/BaileysProvider.js +8 -37
  3. package/lib/adapters/MessageAdapter.js +3 -1
  4. package/lib/adapters/MessageProvider.js +0 -11
  5. package/lib/adapters/TwilioProvider.js +44 -77
  6. package/lib/clinical/AssistantProcessor.js +414 -19
  7. package/lib/clinical/assistants/BaseAssistant.js +0 -15
  8. package/lib/clinical/config/checkInConfig.js +3 -0
  9. package/lib/clinical/config/cohortConfig.js +3 -3
  10. package/lib/clinical/config/composerConfig.js +42 -0
  11. package/lib/clinical/config/divergenceConfig.js +80 -50
  12. package/lib/clinical/config/llmConfig.js +11 -2
  13. package/lib/clinical/config/safetyNetConfig.js +108 -0
  14. package/lib/clinical/config/subAgentsConfig.js +61 -2
  15. package/lib/clinical/context/ToolRuntimeContext.js +121 -6
  16. package/lib/clinical/context/turnContext.js +50 -0
  17. package/lib/clinical/flags/bridgeConfig.js +31 -0
  18. package/lib/clinical/flags/clinicalContextFlags.js +46 -0
  19. package/lib/clinical/flags/composerFlags.js +14 -0
  20. package/lib/clinical/flags/contingencyFlags.js +19 -0
  21. package/lib/clinical/flags/escalationFlags.js +43 -0
  22. package/lib/clinical/flags/flagSnapshot.js +58 -0
  23. package/lib/clinical/flags/inboundRecoveryFlags.js +17 -0
  24. package/lib/clinical/flags/llmAuditConfig.js +7 -0
  25. package/lib/clinical/flags/llmMonitorConfig.js +18 -0
  26. package/lib/clinical/flags/patternConsultFlags.js +10 -0
  27. package/lib/clinical/flags/recommendationRecoveryFlags.js +9 -0
  28. package/lib/clinical/flags/supportLightFlags.js +7 -0
  29. package/lib/clinical/flags/triageRecommendationFlags.js +16 -0
  30. package/lib/clinical/flags/turnEfficiencyFlags.js +19 -0
  31. package/lib/clinical/helpers/auditReasoningHelper.js +30 -0
  32. package/lib/clinical/helpers/carePlanInterventionDerivation.js +76 -0
  33. package/lib/clinical/helpers/carePlanValidationHelper.js +62 -0
  34. package/lib/clinical/helpers/ceilingGapHelper.js +21 -0
  35. package/lib/clinical/helpers/chemoContextHelper.js +217 -0
  36. package/lib/clinical/helpers/clinicalContextHelper.js +162 -0
  37. package/lib/clinical/helpers/clinicalFactsHelper.js +45 -4
  38. package/lib/clinical/helpers/clinicalMentionHelper.js +16 -13
  39. package/lib/clinical/helpers/clinicalProfileHelper.js +60 -0
  40. package/lib/clinical/helpers/clinicalWorkflowGuard.js +175 -0
  41. package/lib/clinical/helpers/cohortHelper.js +3 -1
  42. package/lib/clinical/helpers/contextMirrorHelper.js +68 -0
  43. package/lib/clinical/helpers/dateAnchorHelper.js +18 -0
  44. package/lib/clinical/helpers/doctorReviewMessageHelper.js +152 -0
  45. package/lib/clinical/helpers/drugIdentityHelper.js +67 -0
  46. package/lib/clinical/helpers/encodedPairHelper.js +12 -0
  47. package/lib/clinical/helpers/evidenceAnchorHelper.js +70 -0
  48. package/lib/clinical/helpers/factAssertionHelper.js +300 -0
  49. package/lib/clinical/helpers/gradeEstimateHelper.js +148 -0
  50. package/lib/clinical/helpers/hospitalizationContextHelper.js +8 -0
  51. package/lib/clinical/helpers/legacyContextHelper.js +122 -0
  52. package/lib/clinical/helpers/legacyRecommendationFormatHelper.js +107 -0
  53. package/lib/clinical/helpers/llmsHelper.js +170 -87
  54. package/lib/clinical/helpers/managedSymptomProjectionHelper.js +23 -0
  55. package/lib/clinical/helpers/medicationNamingRule.js +5 -0
  56. package/lib/clinical/helpers/palliativeAssessmentHelper.js +62 -0
  57. package/lib/clinical/helpers/palliativeCarePlanHelper.js +68 -0
  58. package/lib/clinical/helpers/recommendationGateHelper.js +208 -0
  59. package/lib/clinical/helpers/recommendationPlanHelper.js +104 -0
  60. package/lib/clinical/helpers/resultsHelper.js +56 -0
  61. package/lib/clinical/helpers/reviewUpdateHelper.js +68 -0
  62. package/lib/clinical/helpers/shadowHelper.js +1 -13
  63. package/lib/clinical/helpers/skillActivationHelper.js +53 -0
  64. package/lib/clinical/helpers/structuredTextHelper.js +13 -0
  65. package/lib/clinical/helpers/toolResultHelper.js +35 -0
  66. package/lib/clinical/helpers/triageCaseBaseHelper.js +483 -0
  67. package/lib/clinical/helpers/triageResultMessageHelper.js +30 -0
  68. package/lib/clinical/helpers/triageRetriggerHelper.js +85 -0
  69. package/lib/clinical/helpers/triageSymptomsHelper.js +33 -0
  70. package/lib/clinical/index.js +4 -0
  71. package/lib/clinical/memory/DefaultMemoryManager.js +211 -39
  72. package/lib/clinical/memory/EnhancedMemoryManager.js +14 -8
  73. package/lib/clinical/models/llmCallModel.js +19 -0
  74. package/lib/clinical/models/llmMonitorCheckpointModel.js +20 -0
  75. package/lib/clinical/models/llmMonitorEvaluationModel.js +56 -0
  76. package/lib/clinical/models/patternConsultModel.js +37 -0
  77. package/lib/clinical/models/riskWarmupEventModel.js +23 -0
  78. package/lib/clinical/models/supportCandidateModel.js +90 -0
  79. package/lib/clinical/models/supportLightModel.js +95 -0
  80. package/lib/clinical/models/triageRecommendationEventModel.js +110 -0
  81. package/lib/clinical/models/turnTraceModel.js +24 -7
  82. package/lib/clinical/monitoring/AirtableMonitorSink.js +488 -0
  83. package/lib/clinical/monitoring/LlmMonitorService.js +558 -0
  84. package/lib/clinical/monitoring/contingencyMonitorSpec.js +601 -0
  85. package/lib/clinical/promptPlacement.js +5 -0
  86. package/lib/clinical/protocols/treatmentFormulary.js +387 -0
  87. package/lib/clinical/providers/AnthropicProvider.js +459 -31
  88. package/lib/clinical/providers/BaseLLMProvider.js +689 -52
  89. package/lib/clinical/providers/GatewayProvider.js +14 -4
  90. package/lib/clinical/providers/OpenAIResponsesProvider.js +73 -11
  91. package/lib/clinical/providers/OpenAIResponsesProviderTools.js +24 -9
  92. package/lib/clinical/providers/OpenRouterProvider.js +9 -2
  93. package/lib/clinical/services/assistantService.js +51 -7
  94. package/lib/clinical/services/bridgeService.js +93 -0
  95. package/lib/clinical/services/checkInDueService.js +134 -0
  96. package/lib/clinical/services/clinicalAirtableService.js +752 -0
  97. package/lib/clinical/services/clinicalContextReadService.js +47 -0
  98. package/lib/clinical/services/clinicalExtractionService.js +156 -23
  99. package/lib/clinical/services/composerService.js +78 -0
  100. package/lib/clinical/services/conceptVerifierService.js +127 -0
  101. package/lib/clinical/services/conditionCloseService.js +138 -0
  102. package/lib/clinical/services/contextCleanupService.js +85 -0
  103. package/lib/clinical/services/contextMirrorService.js +72 -0
  104. package/lib/clinical/services/contextSyncRunner.js +20 -0
  105. package/lib/clinical/services/contextSyncService.js +258 -0
  106. package/lib/clinical/services/contingencyDispatchService.js +496 -0
  107. package/lib/clinical/services/ctcaeLadderService.js +70 -0
  108. package/lib/clinical/services/ctcaeTermService.js +44 -0
  109. package/lib/clinical/services/currentRegimenService.js +60 -0
  110. package/lib/clinical/services/deliverySettlementService.js +39 -0
  111. package/lib/clinical/services/deniedSymptomBoundaryService.js +218 -0
  112. package/lib/clinical/services/dispatcherService.js +142 -0
  113. package/lib/clinical/services/escalationDraftService.js +229 -0
  114. package/lib/clinical/services/escalationNoteFactsService.js +131 -0
  115. package/lib/clinical/services/escalationQuestionsService.js +131 -0
  116. package/lib/clinical/services/gradeAnchorService.js +85 -0
  117. package/lib/clinical/services/gradeClaimService.js +73 -0
  118. package/lib/clinical/services/gradeSourceService.js +138 -0
  119. package/lib/clinical/services/impressionValidationService.js +19 -0
  120. package/lib/clinical/services/legacyContextSyncService.js +255 -0
  121. package/lib/clinical/services/llmAuditService.js +23 -0
  122. package/lib/clinical/services/nutritionPlanService.js +97 -0
  123. package/lib/clinical/services/outreachCarrierService.js +88 -0
  124. package/lib/clinical/services/outreachSweepRunner.js +8 -0
  125. package/lib/clinical/services/outreachSweepService.js +644 -0
  126. package/lib/clinical/services/patientHistoryService.js +203 -0
  127. package/lib/clinical/services/patientIdentityService.js +43 -0
  128. package/lib/clinical/services/patientProfileService.js +145 -0
  129. package/lib/clinical/services/patternConsultService.js +127 -0
  130. package/lib/clinical/services/pausedSafetyNetService.js +387 -0
  131. package/lib/clinical/services/promptComposerService.js +74 -21
  132. package/lib/clinical/services/radiotherapyContextService.js +40 -0
  133. package/lib/clinical/services/radiotherapyPhaseService.js +272 -0
  134. package/lib/clinical/services/recommendationRankService.js +180 -0
  135. package/lib/clinical/services/recommendationRecoveryService.js +241 -0
  136. package/lib/clinical/services/recommendationValidationService.js +206 -0
  137. package/lib/clinical/services/regimenCloserService.js +205 -0
  138. package/lib/clinical/services/reminderDispatchService.js +36 -0
  139. package/lib/clinical/services/riskAssessmentService.js +469 -0
  140. package/lib/clinical/services/riskHeadlineService.js +56 -0
  141. package/lib/clinical/services/safetyNetPledgeService.js +231 -0
  142. package/lib/clinical/services/shadowMessageService.js +30 -12
  143. package/lib/clinical/services/shadowService.js +8 -4
  144. package/lib/clinical/services/skillService.js +117 -0
  145. package/lib/clinical/services/supportActionService.js +122 -0
  146. package/lib/clinical/services/supportCandidateService.js +607 -0
  147. package/lib/clinical/services/supportInvitability.js +86 -0
  148. package/lib/clinical/services/supportLightEvaluationService.js +231 -0
  149. package/lib/clinical/services/supportLightService.js +277 -0
  150. package/lib/clinical/services/supportRoutingAgentService.js +118 -0
  151. package/lib/clinical/services/symptomLandscapeService.js +153 -0
  152. package/lib/clinical/services/treatmentProposalService.js +136 -0
  153. package/lib/clinical/services/triageRecommendationService.js +1226 -0
  154. package/lib/clinical/services/turnRiskBriefService.js +217 -0
  155. package/lib/clinical/services/writeClaimStore.js +126 -0
  156. package/lib/clinical/stores/CtcaeCatalog.js +21 -0
  157. package/lib/clinical/tools/analyzeSymptomPatternsTool.js +276 -0
  158. package/lib/clinical/tools/deliverPatientMessageTool.js +294 -0
  159. package/lib/clinical/tools/extractClinicalInfoTool.js +252 -37
  160. package/lib/clinical/tools/getActiveRecommendationsTool.js +44 -0
  161. package/lib/clinical/tools/getActiveSymptomLandscapeTool.js +37 -0
  162. package/lib/clinical/tools/getPatientHistoryTool.js +45 -0
  163. package/lib/clinical/tools/getPatientRiskAssessmentTool.js +66 -0
  164. package/lib/clinical/tools/getRouterContextBundleTool.js +136 -0
  165. package/lib/clinical/tools/lookupCtcaeEntryTool.js +36 -0
  166. package/lib/clinical/tools/openClusterHypothesisTool.js +175 -0
  167. package/lib/clinical/tools/openConditionTool.js +198 -0
  168. package/lib/clinical/tools/recordClinicalImpressionTool.js +394 -0
  169. package/lib/clinical/tools/recordInterventionTool.js +138 -0
  170. package/lib/clinical/tools/recordRecommendationOutcomeTool.js +72 -0
  171. package/lib/clinical/tools/registerClinicalTools.js +51 -6
  172. package/lib/clinical/tools/reportCrisisTool.js +193 -0
  173. package/lib/clinical/tools/reportMedicalEscalationTool.js +471 -0
  174. package/lib/clinical/tools/reportResultsReceivedTool.js +176 -0
  175. package/lib/clinical/tools/reportUnresolvedRequestv2Tool.js +164 -0
  176. package/lib/clinical/tools/requestPatternConsultTool.js +70 -0
  177. package/lib/clinical/tools/schedulePatientReminderTool.js +292 -0
  178. package/lib/clinical/tools/sendBridgeMessageTool.js +33 -0
  179. package/lib/clinical/tools/setContingencyPlanTool.js +332 -0
  180. package/lib/clinical/tools/skillTool.js +81 -0
  181. package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
  182. package/lib/clinical/tools/submitOutreachDecisionTool.js +139 -0
  183. package/lib/clinical/tools/submitPalliativeAssessmentTool.js +75 -0
  184. package/lib/clinical/tools/submitPalliativeCarePlanTool.js +101 -0
  185. package/lib/clinical/tools/submitRecommendationPlanTool.js +145 -0
  186. package/lib/clinical/tools/submitRoutingDecisionTool.js +466 -0
  187. package/lib/clinical/tools/submitSafetyGateTool.js +130 -0
  188. package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +149 -0
  189. package/lib/clinical/tools/updateClusterHypothesisTool.js +178 -0
  190. package/lib/clinical/tools/updateConditionStatusTool.js +192 -0
  191. package/lib/clinical/tools/updatePalliativeAssessmentTool.js +78 -0
  192. package/lib/config/airtableArchiveConfig.js +177 -0
  193. package/lib/config/airtableConfig.js +24 -1
  194. package/lib/config/instructionConfig.js +5 -0
  195. package/lib/config/lifecycle.js +36 -1
  196. package/lib/config/programConfig.js +20 -0
  197. package/lib/controllers/assistantController.js +67 -11
  198. package/lib/controllers/contextSyncController.js +30 -0
  199. package/lib/controllers/contingencyController.js +28 -0
  200. package/lib/controllers/conversationController.js +7 -7
  201. package/lib/controllers/dashboardController.js +7 -4
  202. package/lib/controllers/escalationReviewController.js +299 -0
  203. package/lib/controllers/healthController.js +16 -0
  204. package/lib/controllers/interactionController.js +1 -1
  205. package/lib/controllers/messageController.js +67 -19
  206. package/lib/controllers/officeAssistantController.js +57 -0
  207. package/lib/controllers/patientController.js +216 -48
  208. package/lib/controllers/prescriptionController.js +10 -3
  209. package/lib/controllers/templateController.js +8 -17
  210. package/lib/controllers/traceController.js +26 -0
  211. package/lib/controllers/triageRecommendationController.js +41 -0
  212. package/lib/controllers/uploadController.js +2 -2
  213. package/lib/core/BatchingManager.js +146 -11
  214. package/lib/core/DeferredWorkRunner.js +257 -0
  215. package/lib/core/MessageParser.js +2 -2
  216. package/lib/core/NexusMessaging.js +948 -146
  217. package/lib/core/PhiProcessor.js +198 -17
  218. package/lib/core/ProcessingPipeline.js +49 -4
  219. package/lib/core/interactiveRouteService.js +64 -0
  220. package/lib/core/runtimeToolPolicy.js +3 -0
  221. package/lib/eval/EvalProvider.js +72 -25
  222. package/lib/fhir/config/catalogConfig.js +9 -14
  223. package/lib/fhir/config/fhirConfig.js +16 -12
  224. package/lib/fhir/constants/escalationCaseStatus.js +31 -0
  225. package/lib/fhir/constants/extensionSlugs.js +195 -0
  226. package/lib/fhir/constants/gradeMethods.js +12 -0
  227. package/lib/fhir/constants/projectionSlugs.js +69 -1
  228. package/lib/fhir/constants/severityPriority.js +8 -0
  229. package/lib/fhir/constants/variableRegistry.js +60 -0
  230. package/lib/fhir/helpers/compositeHelper.js +65 -12
  231. package/lib/fhir/helpers/contextArbitrationHelper.js +41 -0
  232. package/lib/fhir/helpers/elementHelper.js +39 -0
  233. package/lib/fhir/helpers/fhirHelper.js +4 -1
  234. package/lib/fhir/helpers/fhirReadHelper.js +62 -0
  235. package/lib/fhir/helpers/recommendationIds.js +44 -0
  236. package/lib/fhir/helpers/resourceDisplayHelper.js +9 -0
  237. package/lib/fhir/helpers/resourceHelper.js +46 -0
  238. package/lib/fhir/helpers/symptomAliasHelper.js +56 -0
  239. package/lib/fhir/helpers/termMatchHelper.js +42 -0
  240. package/lib/fhir/helpers/terminologyHelper.js +92 -5
  241. package/lib/fhir/helpers/triagePayloadHelper.js +133 -0
  242. package/lib/fhir/helpers/variableRegistryHelper.js +21 -0
  243. package/lib/fhir/index.js +75 -0
  244. package/lib/fhir/models/envelopeModel.js +22 -0
  245. package/lib/fhir/projections/clinicalMentionProjection.js +208 -46
  246. package/lib/fhir/projections/clusterProjection.js +124 -0
  247. package/lib/fhir/projections/contextFactProjection.js +380 -0
  248. package/lib/fhir/projections/contingencyProjection.js +224 -0
  249. package/lib/fhir/projections/dispatchedEscalationProjection.js +63 -0
  250. package/lib/fhir/projections/interventionProjection.js +245 -0
  251. package/lib/fhir/projections/palliativeCarePlanProjection.js +183 -0
  252. package/lib/fhir/projections/palliativeProjection.js +175 -0
  253. package/lib/fhir/projections/proctcaeProjection.js +62 -15
  254. package/lib/fhir/projections/recommendationPlanProjection.js +557 -0
  255. package/lib/fhir/projections/registerProjectors.js +10 -2
  256. package/lib/fhir/projections/reminderProjection.js +20 -0
  257. package/lib/fhir/projections/riskProjection.js +16 -0
  258. package/lib/fhir/projections/routingProjection.js +285 -0
  259. package/lib/fhir/projections/safetyGateProjection.js +42 -0
  260. package/lib/fhir/projections/symptomCaseProjection.js +324 -0
  261. package/lib/fhir/resources/CommunicationRequest.js +91 -0
  262. package/lib/fhir/resources/Condition.js +2 -24
  263. package/lib/fhir/resources/Encounter.js +30 -0
  264. package/lib/fhir/resources/Observation.js +22 -69
  265. package/lib/fhir/resources/Patient.js +57 -6
  266. package/lib/fhir/resources/Provenance.js +48 -12
  267. package/lib/fhir/resources/RiskAssessment.js +184 -0
  268. package/lib/fhir/resources/Task.js +102 -0
  269. package/lib/fhir/services/clinicalContextService.js +161 -0
  270. package/lib/fhir/services/clinicalMentionService.js +3 -5
  271. package/lib/fhir/services/clusterService.js +30 -0
  272. package/lib/fhir/services/contingencyService.js +47 -0
  273. package/lib/fhir/services/encounterService.js +16 -0
  274. package/lib/fhir/services/escalationService.js +85 -0
  275. package/lib/fhir/services/fhirService.js +20 -0
  276. package/lib/fhir/services/interventionService.js +50 -0
  277. package/lib/fhir/services/palliativeService.js +74 -0
  278. package/lib/fhir/services/patientService.js +41 -0
  279. package/lib/fhir/services/recommendationService.js +336 -0
  280. package/lib/fhir/services/resultObservationService.js +53 -0
  281. package/lib/fhir/services/riskService.js +202 -0
  282. package/lib/fhir/services/routingService.js +86 -0
  283. package/lib/fhir/services/snapshotService.js +18 -3
  284. package/lib/fhir/services/symptomCaseService.js +33 -0
  285. package/lib/fhir/services/terminologyService.js +16 -21
  286. package/lib/fhir/services/triageService.js +8 -4
  287. package/lib/fhir/stores/fhirStore.js +42 -19
  288. package/lib/fhir/utils/normalizeUtils.js +12 -0
  289. package/lib/helpers/airtableArchiveHelper.js +51 -0
  290. package/lib/helpers/airtableFormulaHelper.js +25 -0
  291. package/lib/helpers/caregiverHelper.js +136 -0
  292. package/lib/helpers/channelErrorHelper.js +31 -0
  293. package/lib/helpers/channelRetryHelper.js +156 -0
  294. package/lib/helpers/conversationWindowHelper.js +2 -2
  295. package/lib/helpers/deliveryAttemptHelper.js +14 -2
  296. package/lib/helpers/filesHelper.js +3 -3
  297. package/lib/helpers/healthHelper.js +40 -0
  298. package/lib/helpers/messageHelper.js +16 -6
  299. package/lib/helpers/messageStatusHelper.js +16 -22
  300. package/lib/helpers/metaSignatureHelper.js +6 -6
  301. package/lib/helpers/nerHelper.js +24 -0
  302. package/lib/helpers/outboundAllowlistHelper.js +51 -0
  303. package/lib/helpers/patientInformationHelper.js +20 -16
  304. package/lib/helpers/patientMessageHelper.js +79 -0
  305. package/lib/helpers/patientTaskRulesHelper.js +57 -0
  306. package/lib/helpers/pausedThreadHelper.js +37 -0
  307. package/lib/helpers/processHelper.js +47 -16
  308. package/lib/helpers/sendClaimHelper.js +126 -0
  309. package/lib/helpers/staffSendHelper.js +4 -0
  310. package/lib/helpers/templateFlowControllerHelper.js +1 -1
  311. package/lib/helpers/templateRecoveryHelper.js +66 -8
  312. package/lib/helpers/triageRecordHelper.js +124 -0
  313. package/lib/helpers/twilioHelper.js +7 -79
  314. package/lib/helpers/twilioMediaHelper.js +1 -1
  315. package/lib/helpers/whatsappHelper.js +3 -1
  316. package/lib/index.d.ts +844 -34
  317. package/lib/index.js +169 -11
  318. package/lib/jobs/ScheduledMessageJob.js +44 -0
  319. package/lib/jobs/TemplateApprovalJob.js +200 -33
  320. package/lib/models/agendaMessageModel.js +5 -0
  321. package/lib/models/airtableArchiveModel.js +225 -0
  322. package/lib/models/contactGateDecisionModel.js +27 -0
  323. package/lib/models/contextSyncStateModel.js +26 -0
  324. package/lib/models/deferredWorkModel.js +24 -0
  325. package/lib/models/deliveryAttemptModel.js +5 -1
  326. package/lib/models/escalationReviewModel.js +341 -0
  327. package/lib/models/flowRoutingModel.js +1 -1
  328. package/lib/models/messageModel.js +21 -1
  329. package/lib/models/patientProfileModel.js +24 -0
  330. package/lib/models/safetyNetPledgeModel.js +31 -0
  331. package/lib/models/sendClaimModel.js +18 -0
  332. package/lib/models/templateModel.js +1 -2
  333. package/lib/models/threadModel.js +7 -0
  334. package/lib/models/tokenMapModel.js +2 -1
  335. package/lib/models/writeClaimModel.js +14 -0
  336. package/lib/observability/telemetry.js +7 -7
  337. package/lib/providers/NerClient.js +2 -2
  338. package/lib/queue/QueueAdapter.js +1 -0
  339. package/lib/queue/RedisQueueAdapter.js +104 -7
  340. package/lib/routes/index.js +132 -2
  341. package/lib/services/airtableArchivePlanService.js +197 -0
  342. package/lib/services/airtableArchiveReadService.js +48 -0
  343. package/lib/services/airtableArchiveService.js +561 -0
  344. package/lib/services/airtableMirrorService.js +223 -0
  345. package/lib/services/airtableService.js +198 -18
  346. package/lib/services/assistantMessageService.js +140 -0
  347. package/lib/services/carePlanHistoryService.js +610 -0
  348. package/lib/services/characterizationOutcomeService.js +294 -0
  349. package/lib/services/contactGateService.js +178 -0
  350. package/lib/services/conversationService.js +66 -20
  351. package/lib/services/dashboard-provider-registry.js +38 -0
  352. package/lib/services/dashboardService.js +31 -4
  353. package/lib/services/escalationCaseTaskService.js +134 -0
  354. package/lib/services/escalationContextService.js +92 -0
  355. package/lib/services/escalationReviewService.js +2214 -0
  356. package/lib/services/flowDataExchangeService.js +1 -1
  357. package/lib/services/globalEntityService.js +1 -1
  358. package/lib/services/gravePendingService.js +41 -0
  359. package/lib/services/healthService.js +252 -0
  360. package/lib/services/heldMessageService.js +141 -0
  361. package/lib/services/inboundRecoveryService.js +354 -0
  362. package/lib/services/instructionInFlightService.js +17 -0
  363. package/lib/services/officeAssistantService.js +217 -0
  364. package/lib/services/orbisService.js +44 -0
  365. package/lib/services/patientClinicalStatusService.js +189 -0
  366. package/lib/services/patientResourceService.js +24 -0
  367. package/lib/services/patientService.js +28 -16
  368. package/lib/services/patientTaskService.js +221 -0
  369. package/lib/services/patientTaskSummaryService.js +93 -0
  370. package/lib/services/physicianService.js +31 -0
  371. package/lib/services/preprocessingService.js +18 -6
  372. package/lib/services/queueReconciliationService.js +161 -0
  373. package/lib/services/recommendationCarouselService.js +398 -0
  374. package/lib/services/reviewAlertSweepService.js +99 -0
  375. package/lib/services/reviewBoardService.js +75 -0
  376. package/lib/services/reviewDeadlineService.js +116 -0
  377. package/lib/services/reviewDraftSweepService.js +85 -0
  378. package/lib/services/teamAlertService.js +140 -0
  379. package/lib/services/templateService.js +1 -2
  380. package/lib/{helpers/threadHelper.js → services/threadService.js} +38 -6
  381. package/lib/services/tokenMapService.js +119 -22
  382. package/lib/services/toolRegistryService.js +43 -2
  383. package/lib/services/triageHistoryService.js +128 -0
  384. package/lib/services/twilioMediaService.js +79 -0
  385. package/lib/services/undeliverableService.js +36 -0
  386. package/lib/services/untakenAlertService.js +210 -0
  387. package/lib/shared/dtos/ClinicalAssertion.js +21 -0
  388. package/lib/shared/dtos/ClinicalMention.js +4 -0
  389. package/lib/shared/dtos/ClusterImpression.js +16 -5
  390. package/lib/shared/dtos/ContingencySafetyNet.js +69 -7
  391. package/lib/shared/dtos/DispatchedEscalation.js +4 -8
  392. package/lib/shared/dtos/GradedSymptom.js +2 -0
  393. package/lib/shared/dtos/Intervention.js +10 -3
  394. package/lib/shared/dtos/ManagedSymptom.js +40 -11
  395. package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
  396. package/lib/shared/dtos/PalliativeAssessment.js +62 -0
  397. package/lib/shared/dtos/PalliativeCarePlan.js +47 -0
  398. package/lib/shared/dtos/PatientRiskAssessment.js +25 -1
  399. package/lib/shared/dtos/RecommendationPlan.js +102 -0
  400. package/lib/shared/dtos/RecommendationSafetyGate.js +64 -0
  401. package/lib/shared/dtos/Reminder.js +2 -2
  402. package/lib/shared/dtos/RoutingDecision.js +2 -1
  403. package/lib/shared/dtos/SupportAction.js +28 -0
  404. package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
  405. package/lib/shared/dtos/TriageCompletion.js +50 -0
  406. package/lib/shared/dtos/TriageResponse.js +7 -1
  407. package/lib/storage/MongoStorage.js +10 -1
  408. package/lib/templates/predefinedTemplates.js +1 -1
  409. package/lib/templates/templateStructure.js +15 -2
  410. package/lib/utils/MapCache.js +1 -1
  411. package/lib/utils/coercionUtils.js +11 -0
  412. package/lib/utils/concurrencyUtils.js +13 -0
  413. package/lib/utils/dateUtils.js +114 -6
  414. package/lib/utils/errorUtils.js +26 -1
  415. package/lib/utils/formatUtils.js +43 -37
  416. package/lib/utils/httpErrorUtils.js +9 -0
  417. package/lib/utils/intervalSweeper.js +75 -0
  418. package/lib/utils/jsonUtils.js +51 -0
  419. package/lib/utils/logger.js +8 -6
  420. package/lib/utils/paginationUtils.js +30 -0
  421. package/lib/utils/retryUtils.js +9 -1
  422. package/lib/utils/sanitizerUtils.js +87 -1
  423. package/lib/utils/scheduleUtils.js +70 -1
  424. package/lib/utils/shadowScope.js +13 -0
  425. package/lib/utils/statsUtils.js +21 -0
  426. package/lib/utils/textMatchUtils.js +76 -0
  427. package/lib/utils/timeoutUtils.js +16 -0
  428. package/lib/utils/tokenMapUtils.js +3 -3
  429. package/package.json +11 -11
  430. package/lib/clinical/helpers/divergenceHelper.js +0 -100
  431. package/lib/clinical/models/divergenceModel.js +0 -41
  432. package/lib/clinical/services/clinicalAgentService.js +0 -18
  433. package/lib/clinical/services/divergenceService.js +0 -90
  434. package/lib/core/workflowRunner.js +0 -35
  435. package/lib/fhir/resources/Appointment.js +0 -28
  436. package/lib/fhir/resources/MedicationStatement.js +0 -42
  437. package/lib/fhir/resources/Procedure.js +0 -30
  438. package/lib/services/twilioService.js +0 -13
@@ -0,0 +1,644 @@
1
+ const moment = require('moment-timezone');
2
+
3
+ const airtableService = require('../../services/airtableService');
4
+ const { Symptoms_ID } = require('../../config/airtableConfig');
5
+ const { getMessages } = require('../../services/messageService');
6
+ const { DEFAULT_TIMEZONE, isWithinHourWindow } = require('../../utils/scheduleUtils');
7
+ const { logger } = require('../../utils/logger');
8
+ const { botIsPaused } = require('../../helpers/pausedThreadHelper');
9
+ const { isArchivedPatientCode } = require('../../helpers/twilioHelper');
10
+ const { Thread } = require('../../models/threadModel');
11
+ const { PATIENT_CONTACT_WINDOW } = require('./contingencyDispatchService');
12
+ const { hasPendingReminderForPatient } = require('./clinicalAirtableService');
13
+ const { WriteClaimStore } = require('./writeClaimStore');
14
+
15
+ const TABLE = 'weekly_questionnaires';
16
+ const VIEW = 'seguimiento_72hrs_principal';
17
+
18
+ // Kept only for the shadow comparison against the legacy Thursday/Saturday automations. The live
19
+ // continuity sweep is daily and lets inactivity plus the agent decide, rather than a weekday label.
20
+ const TARGET_DAYS_BY_WEEKDAY = {
21
+ 4: ['lunes', 'martes'],
22
+ 6: ['miércoles', 'jueves'],
23
+ };
24
+
25
+ const F = {
26
+ patientLink: 'patient_id',
27
+ firstName: 'first_name (from patient_id)',
28
+ whatsapp: 'whatsapp_id (from patient_id)',
29
+ diaLast: 'dia_last_triage',
30
+ symptomDate: 'Date (from triage_symptoms_id) 2',
31
+ grade: 'max_grade_in_triaje (from triage_symptoms_id)',
32
+ positiveSymptoms: 'symptom_name_positive (from triage_symptoms_id) 4',
33
+ createdAt: 'created_at',
34
+ review: 'revisión_sistema',
35
+ optOut: 'enviar_mensaje_seguimiento',
36
+ optOutDate: 'no_enviar_mensaje_fecha',
37
+ disableFollowUp: 'desactivar_seguimiento_48hrs (from patient_id)',
38
+ contentSid: 'sid',
39
+ typeQuest: 'type_quest',
40
+ triageLink: 'triage_symptoms_id',
41
+ triageAnswer: 'triage_answered',
42
+ triageSent: 'sent',
43
+ triageSentAt: 'date_sent',
44
+ twilioStatus: 'twilio_sent',
45
+ deliveryStatus: 'delivered',
46
+ };
47
+
48
+ // Write-only. Deliberately NOT in F: F is the field list for the view query, and naming a column
49
+ // there that does not exist makes the whole read throw.
50
+ const AUDIT = {
51
+ rationale: 'seguimiento_decision_rationale',
52
+ turnId: 'seguimiento_turn_id',
53
+ };
54
+
55
+ const WEEKLY_SOURCE = 'weekly';
56
+ const SCOPE_SOURCE = 'patient_scope';
57
+
58
+ const sweepClaims = new WriteClaimStore({ namespace: 'outreach_sweep', ttlMs: 8 * 24 * 60 * 60 * 1000 });
59
+
60
+ const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
61
+ const CONTACT_SENT = {
62
+ from_me: true,
63
+ origin: { $nin: ['instruction', 'system'] },
64
+ $or: [
65
+ { 'statusInfo.status': { $nin: UNDELIVERED_STATUSES } },
66
+ { 'statusInfo.recoveryTemplateSid': { $ne: null }, 'statusInfo.recoverySentAt': null },
67
+ ],
68
+ };
69
+
70
+ const RECENT_OUTBOUND_HOURS = 24;
71
+ const COLLIDING_REMINDER_MINUTES = 24 * 60;
72
+ const INACTIVITY_DAYS = 7;
73
+ const MAX_SILENCE_DAYS = 30;
74
+ const TRIAGE_PROTECTION_START_MINUTE = (7 * 60) + 30;
75
+ const TRIAGE_PROTECTION_END_MINUTE = 11 * 60;
76
+
77
+ function first(value) {
78
+ if (Array.isArray(value)) return value.length ? value[0] : null;
79
+ return value ?? null;
80
+ }
81
+
82
+ function asList(value) {
83
+ if (Array.isArray(value)) return value.filter(Boolean).map(String);
84
+ if (value === null || value === undefined || value === '') return [];
85
+ return [String(value)];
86
+ }
87
+
88
+ function hasGrade(row) {
89
+ const grade = first(row?.[F.grade]);
90
+ return grade !== null && grade !== undefined;
91
+ }
92
+
93
+ function startOfLocalWeek(now) {
94
+ return moment.tz(now, DEFAULT_TIMEZONE).startOf('isoWeek');
95
+ }
96
+
97
+ /* Groups the view's rows into one candidate per patient. Daily cadence keeps the most recent
98
+ * available clinical anchor; legacy cadence reproduces the old Thu/Sat cohort for shadow parity. */
99
+ function isWithinTriageProtectionWindow(now) {
100
+ const local = moment.tz(now, DEFAULT_TIMEZONE);
101
+ const minute = (local.hour() * 60) + local.minute();
102
+ return minute >= TRIAGE_PROTECTION_START_MINUTE && minute < TRIAGE_PROTECTION_END_MINUTE;
103
+ }
104
+
105
+ function startOfLocalDay(now) {
106
+ return moment.tz(now, DEFAULT_TIMEZONE).startOf('day').toDate();
107
+ }
108
+
109
+ function isMondayTriageRecoveryRow(row, now) {
110
+ const sentAt = first(row?.[F.triageSentAt]);
111
+ const delivery = String(first(row?.[F.deliveryStatus]) || '').trim().toLowerCase();
112
+ return moment.tz(now, DEFAULT_TIMEZONE).isoWeekday() === 1
113
+ && String(first(row?.[F.typeQuest]) || '').trim().toLowerCase() === 'weekly'
114
+ && first(row?.[F.triageSent]) === true
115
+ && String(first(row?.[F.twilioStatus]) || '').trim().toLowerCase() === 'sent'
116
+ && ['sent', 'delivered', 'read'].includes(delivery)
117
+ && Boolean(sentAt)
118
+ && moment.tz(sentAt, DEFAULT_TIMEZONE).isSame(moment.tz(now, DEFAULT_TIMEZONE), 'day')
119
+ && asList(row?.[F.triageLink]).length === 0
120
+ && String(first(row?.[F.triageAnswer]) || '').trim().toLowerCase() === 'no contestado';
121
+ }
122
+
123
+ function buildCandidates(rows, { now, cadence = 'daily', mode = 'continuity' }) {
124
+ const weekday = moment.tz(now, DEFAULT_TIMEZONE).isoWeekday();
125
+ const targetDays = cadence === 'legacy' ? (TARGET_DAYS_BY_WEEKDAY[weekday] || []) : [];
126
+ if (cadence === 'legacy' && !targetDays.length) return { candidates: [], targetDays, weekday, cadence };
127
+
128
+ const sourceRows = mode === 'monday_triage_recovery'
129
+ ? rows.filter((row) => isMondayTriageRecoveryRow(row, now))
130
+ : rows;
131
+
132
+ const byPatient = new Map();
133
+ for (const row of sourceRows) {
134
+ const patientId = first(row[F.patientLink]);
135
+ if (!patientId) continue;
136
+ if (!byPatient.has(patientId)) byPatient.set(patientId, []);
137
+ byPatient.get(patientId).push(row);
138
+ }
139
+
140
+ const candidates = [];
141
+ for (const [patientId, patientRows] of byPatient) {
142
+ const graded = patientRows.filter(hasGrade).sort((a, b) =>
143
+ new Date(first(b[F.symptomDate]) || 0) - new Date(first(a[F.symptomDate]) || 0));
144
+ const current = graded[0] || null;
145
+
146
+ let row = null;
147
+ let reason = null;
148
+ // Read the weekday off the row being acted on. It is a patient-level lookup so siblings agree
149
+ // today, but taking it from an arbitrary sibling would silently pick the wrong day if that ever
150
+ // stops being true.
151
+ const diaLast = current ? first(current[F.diaLast]) : first(patientRows[0][F.diaLast]);
152
+ if (mode === 'monday_triage_recovery') {
153
+ row = patientRows.slice().sort((a, b) =>
154
+ new Date(first(b[F.triageSentAt]) || 0) - new Date(first(a[F.triageSentAt]) || 0))[0];
155
+ reason = 'monday_triage_incomplete';
156
+ } else if (cadence === 'legacy') {
157
+ if (current && targetDays.includes(diaLast)) {
158
+ row = current;
159
+ reason = 'triage_answered';
160
+ } else if (!current) {
161
+ row = patientRows.slice().sort((a, b) =>
162
+ new Date(b[F.createdAt] || 0) - new Date(a[F.createdAt] || 0))[0];
163
+ reason = 'no_triage_this_week';
164
+ } else {
165
+ continue;
166
+ }
167
+ } else {
168
+ row = current || patientRows.slice().sort((a, b) =>
169
+ new Date(b[F.createdAt] || 0) - new Date(a[F.createdAt] || 0))[0];
170
+ reason = current ? 'triage_answered' : 'no_triage_history';
171
+ }
172
+
173
+ // Keep the `whatsapp:` prefix. It is the canonical key everywhere inside nexus — threads.code,
174
+ // messages.numero and reminder.whatsapp_id all carry it — so stripping it (as the Airtable
175
+ // script does, because /api/message/send re-adds it) silently kills every guard that reads a
176
+ // store, and stops the thread resolving at all.
177
+ const code = String(first(row[F.whatsapp]) || '').trim();
178
+ const name = String(first(row[F.firstName]) || '').trim();
179
+ if (!code || !name || isArchivedPatientCode(code)) {
180
+ logger.info('[outreachSweep] candidate skipped — missing code or name', { recordId: row._recordId });
181
+ continue;
182
+ }
183
+
184
+ candidates.push({
185
+ patientId,
186
+ recordId: row._recordId,
187
+ code,
188
+ name,
189
+ reason,
190
+ ...(mode === 'monday_triage_recovery' ? {
191
+ triageSentAt: first(row[F.triageSentAt]),
192
+ triageContentSid: first(row[F.contentSid]),
193
+ } : {}),
194
+ rows: patientRows,
195
+ brief: {
196
+ ...(reason === 'monday_triage_incomplete' ? { kind: 'seguimiento' } : {}),
197
+ reason: reason === 'monday_triage_incomplete'
198
+ ? 'no completó su triaje semanal enviado hoy'
199
+ : (reason === 'triage_answered'
200
+ ? `contestó su triaje el ${diaLast}`
201
+ : (reason === 'no_triage_this_week'
202
+ ? 'no contestó ningún triaje esta semana'
203
+ : 'no hay un triaje contestado que sirva como ancla clínica')),
204
+ lastTriageAt: first(row[F.symptomDate]) || null,
205
+ maxGrade: reason === 'triage_answered' ? first(row[F.grade]) : null,
206
+ positiveSymptoms: asList(row[F.positiveSymptoms]),
207
+ },
208
+ });
209
+ }
210
+
211
+ return { candidates, targetDays, weekday, cadence, mode };
212
+ }
213
+
214
+ function firstWord(value) {
215
+ return String(value || '').trim().split(/\s+/)[0];
216
+ }
217
+
218
+ function buildScopeCandidates({ threads, excludedCodes }) {
219
+ const threadsByCode = new Map();
220
+ for (const thread of threads) threadsByCode.set(thread.code, [...(threadsByCode.get(thread.code) || []), thread]);
221
+
222
+ const candidates = [];
223
+ for (const [code, docs] of threadsByCode) {
224
+ const [thread] = docs.sort((a, b) => String(a._id).localeCompare(String(b._id)));
225
+ const name = firstWord(thread.nombre);
226
+ const names = new Set(docs.map((doc) => firstWord(doc.nombre).toLowerCase()));
227
+ if (excludedCodes.has(code) || !name || names.size !== 1 || !thread.patient_id) continue;
228
+ candidates.push({
229
+ source: SCOPE_SOURCE,
230
+ patientId: thread.patient_id,
231
+ recordId: String(thread._id),
232
+ code,
233
+ name,
234
+ reason: 'no_triage_history',
235
+ rows: [],
236
+ brief: {
237
+ reason: 'no hay un triaje contestado que sirva como ancla clínica',
238
+ lastTriageAt: null,
239
+ maxGrade: null,
240
+ positiveSymptoms: [],
241
+ },
242
+ });
243
+ }
244
+ return candidates;
245
+ }
246
+
247
+ async function loadScopeCandidates({ now, viewRows, patientScope }) {
248
+ const weekStart = startOfLocalWeek(now).toISOString();
249
+ const [threads, weekRows] = await Promise.all([
250
+ Thread.find({ code: { $in: patientScope } }, { code: 1, nombre: 1, patient_id: 1 }).lean(),
251
+ airtableService.getRecordByFilter(
252
+ Symptoms_ID, TABLE, `NOT(IS_BEFORE({${F.createdAt}}, DATETIME_PARSE("${weekStart}")))`, null, [F.whatsapp],
253
+ ),
254
+ ]);
255
+ const excludedCodes = new Set([...viewRows, ...(weekRows || [])]
256
+ .map((row) => String(first(row[F.whatsapp]) || '').trim()));
257
+ return buildScopeCandidates({ threads: threads || [], excludedCodes });
258
+ }
259
+
260
+ function sweepClaimKey(candidate, now) {
261
+ return `${candidate.code}:${startOfLocalWeek(now).format('YYYY-MM-DD')}`;
262
+ }
263
+
264
+ function opsOptedOut(candidate, { now }) {
265
+ const weekStart = startOfLocalWeek(now);
266
+ for (const row of candidate.rows) {
267
+ if (first(row[F.disableFollowUp]) === true) return 'patient_follow_up_disabled';
268
+ if (String(first(row[F.optOut]) || '').toLowerCase() !== 'no') continue;
269
+ const marked = row[F.optOutDate];
270
+ if (marked && moment.tz(marked, DEFAULT_TIMEZONE).isSameOrAfter(weekStart)) return 'ops_opt_out';
271
+ }
272
+ return null;
273
+ }
274
+
275
+ // Patient-scoped, not row-scoped: a patient with two questionnaires this week is one person, and
276
+ // the old automation's per-row stamp is what let her be contacted twice.
277
+ function priorSweepReason(candidate) {
278
+ const stamps = candidate.rows.map((row) => String(row[F.review] || '').trim()).filter(Boolean);
279
+ if (stamps.some((stamp) => stamp.endsWith('_en curso'))) return 'stuck_in_progress';
280
+ return stamps.length ? 'already_swept_this_week' : null;
281
+ }
282
+
283
+ async function mondayTriageStillPending(candidate) {
284
+ const rows = await airtableService.getRecordByFilter(
285
+ Symptoms_ID,
286
+ TABLE,
287
+ `RECORD_ID() = "${candidate.recordId}"`,
288
+ null,
289
+ [F.typeQuest, F.triageLink, F.triageAnswer, F.triageSent, F.twilioStatus, F.deliveryStatus, F.triageSentAt],
290
+ );
291
+ return rows?.length === 1 && isMondayTriageRecoveryRow(rows[0], candidate.triageSentAt);
292
+ }
293
+
294
+ async function rejectionReason(candidate, {
295
+ now, includePreviouslySwept = false, cadence = 'daily', mode = 'continuity',
296
+ } = {}) {
297
+ const opsReason = opsOptedOut(candidate, { now });
298
+ if (opsReason) return opsReason;
299
+ if (await Thread.exists({ code: candidate.code, outreachOptOut: true })) return 'outreach_opt_out';
300
+ if (await botIsPaused(candidate.code, { label: '[outreachSweep]' })) return 'bot_paused';
301
+ if (!includePreviouslySwept) {
302
+ const sweptReason = candidate.source === SCOPE_SOURCE
303
+ ? (await sweepClaims.has(sweepClaimKey(candidate, now)) ? 'already_swept_this_week' : null)
304
+ : priorSweepReason(candidate);
305
+ if (sweptReason) return sweptReason;
306
+
307
+ const since = mode === 'monday_triage_recovery'
308
+ ? new Date(candidate.triageSentAt)
309
+ : moment.tz(now, DEFAULT_TIMEZONE).subtract(RECENT_OUTBOUND_HOURS, 'hours').toDate();
310
+ const recentOutbound = await getMessages(
311
+ {
312
+ numero: candidate.code,
313
+ ...CONTACT_SENT,
314
+ createdAt: { $gt: since },
315
+ ...(mode === 'monday_triage_recovery' && candidate.triageContentSid
316
+ ? { content_sid: { $ne: candidate.triageContentSid } }
317
+ : {}),
318
+ },
319
+ { limit: 1 },
320
+ );
321
+ if (recentOutbound?.length) {
322
+ return mode === 'monday_triage_recovery' ? 'wrote_to_her_after_triage' : 'wrote_to_her_recently';
323
+ }
324
+
325
+ if (mode === 'monday_triage_recovery') {
326
+ const recentInbound = await getMessages(
327
+ { numero: candidate.code, from_me: false, createdAt: { $gt: since } },
328
+ { sort: { createdAt: -1 }, limit: 1 },
329
+ );
330
+ if (recentInbound?.length) return 'patient_active_since_triage';
331
+ if (!await mondayTriageStillPending(candidate)) return 'triage_no_longer_pending';
332
+ } else if (cadence === 'daily') {
333
+ const inactiveSince = moment.tz(now, DEFAULT_TIMEZONE).subtract(INACTIVITY_DAYS, 'days').toDate();
334
+ const silentSince = moment.tz(now, DEFAULT_TIMEZONE).subtract(MAX_SILENCE_DAYS, 'days').toDate();
335
+ const [lastInbound] = await getMessages(
336
+ { numero: candidate.code, from_me: false, createdAt: { $gte: silentSince } },
337
+ { select: { createdAt: 1 }, sort: { createdAt: -1 }, limit: 1 },
338
+ );
339
+ if (!lastInbound) return 'patient_silent_beyond_max_window';
340
+ if (new Date(lastInbound.createdAt) >= inactiveSince) return 'patient_active_within_inactivity_window';
341
+
342
+ const lastTriageAt = candidate?.brief?.lastTriageAt;
343
+ if (lastTriageAt && moment.tz(lastTriageAt, DEFAULT_TIMEZONE).isSameOrAfter(inactiveSince)) {
344
+ return 'triage_within_inactivity_window';
345
+ }
346
+
347
+ const recentOutreach = await getMessages(
348
+ {
349
+ numero: candidate.code,
350
+ ...CONTACT_SENT,
351
+ triggeredBy: { $regex: '^(?:seguimiento:|followup_)' },
352
+ createdAt: { $gte: inactiveSince },
353
+ },
354
+ { sort: { createdAt: -1 }, limit: 1 },
355
+ );
356
+ if (recentOutreach?.length) return 'outreach_within_cooldown';
357
+
358
+ const unansweredSince = moment.tz(now, DEFAULT_TIMEZONE).subtract(30, 'days').toDate();
359
+ const lastTwoOutreaches = await getMessages(
360
+ {
361
+ numero: candidate.code,
362
+ ...CONTACT_SENT,
363
+ triggeredBy: { $regex: '^(?:seguimiento:|followup_)' },
364
+ createdAt: { $gte: unansweredSince },
365
+ },
366
+ { sort: { createdAt: -1 }, limit: 2 },
367
+ );
368
+ if (lastTwoOutreaches?.length >= 2) {
369
+ const oldest = lastTwoOutreaches[lastTwoOutreaches.length - 1]?.createdAt;
370
+ const reply = oldest
371
+ ? await getMessages(
372
+ { numero: candidate.code, from_me: false, createdAt: { $gt: oldest } },
373
+ { sort: { createdAt: 1 }, limit: 1 },
374
+ )
375
+ : [];
376
+ if (!reply?.length) return 'unanswered_outreach_limit';
377
+ }
378
+ }
379
+ }
380
+
381
+ if (await hasPendingReminderForPatient({ code: candidate.code, withinMinutes: COLLIDING_REMINDER_MINUTES })) {
382
+ return 'proactive_message_already_scheduled';
383
+ }
384
+
385
+ return null;
386
+ }
387
+
388
+ // Final guard for a previously scheduled routine follow-up. The plan may have been valid when it
389
+ // was created; same-day triage or conversation activity makes it stale before its due time.
390
+ async function routineOutreachCollisionReason(code, { now = new Date() } = {}) {
391
+ if (isWithinTriageProtectionWindow(now)) return 'triage_protection_window';
392
+ const today = startOfLocalDay(now);
393
+ const [inbound, outbound] = await Promise.all([
394
+ getMessages(
395
+ { numero: code, from_me: false, createdAt: { $gte: today } },
396
+ { sort: { createdAt: -1 }, limit: 1 },
397
+ ),
398
+ getMessages(
399
+ { numero: code, ...CONTACT_SENT, createdAt: { $gte: today } },
400
+ { sort: { createdAt: -1 }, limit: 1 },
401
+ ),
402
+ ]);
403
+ if (inbound?.length) return 'patient_active_today';
404
+ if (outbound?.length) return 'outbound_today';
405
+ return null;
406
+ }
407
+
408
+ async function enrichBrief(candidate) {
409
+ const [lastInbound] = await getMessages({ numero: candidate.code, from_me: false }, { sort: { createdAt: -1 }, limit: 1 });
410
+ const [lastOutbound] = await getMessages({ numero: candidate.code, ...CONTACT_SENT }, { sort: { createdAt: -1 }, limit: 1 });
411
+ const fmt = (doc) => (doc?.createdAt ? moment.tz(doc.createdAt, DEFAULT_TIMEZONE).format('YYYY-MM-DD HH:mm') : null);
412
+ return {
413
+ ...candidate.brief,
414
+ lastInboundAt: fmt(lastInbound),
415
+ lastOutboundAt: fmt(lastOutbound),
416
+ };
417
+ }
418
+
419
+ // Stamps the row BEFORE the turn runs. `alreadySweptThisWeek` rejects any patient carrying a stamp,
420
+ // so a second overlapping sweep sees this one and stands down. A turn that then dies leaves the
421
+ // patient uncontacted for the week, which is the safe direction: a free-text send carries no
422
+ // contentSid and no idempotency key, so nothing downstream would catch a duplicate.
423
+ async function claimCandidate({ candidate, weekdayLabel, dryRun, now }) {
424
+ if (dryRun) return true;
425
+ if ((await sweepClaims.acquire(sweepClaimKey(candidate, now))) !== 'acquired') return false;
426
+ if (candidate.source === SCOPE_SOURCE) return true;
427
+ try {
428
+ const claimed = await airtableService.updateRecordByFilter(
429
+ Symptoms_ID,
430
+ TABLE,
431
+ `AND(RECORD_ID() = "${candidate.recordId}", {${F.review}} = "")`,
432
+ { [F.review]: `${weekdayLabel}_en curso` },
433
+ candidate.code,
434
+ );
435
+ if (!claimed?.length) {
436
+ logger.info('[outreachSweep] candidate already claimed by another run', { recordId: candidate.recordId });
437
+ return false;
438
+ }
439
+ return true;
440
+ } catch (error) {
441
+ logger.warn('[outreachSweep] claim failed; skipping rather than risking a double send', {
442
+ recordId: candidate.recordId, error: error.message,
443
+ });
444
+ return false;
445
+ }
446
+ }
447
+
448
+ async function recordOutcome({ candidate, outcome, weekdayLabel, dryRun }) {
449
+ if (dryRun || candidate.source === SCOPE_SOURCE) return;
450
+ // Three outcomes, not two: a `write` whose delivery never happened is neither "escrito" nor a
451
+ // deliberate hold, and collapsing it into either would hide the failure from the ops queue.
452
+ let stamp;
453
+ if (outcome.error) stamp = `${weekdayLabel}_error`;
454
+ else if (outcome.delivered) stamp = `${weekdayLabel}_entregado`;
455
+ else if (outcome.accepted) stamp = `${weekdayLabel}_enviado`;
456
+ else if (outcome.decision === 'write') stamp = `${weekdayLabel}_no entregado`;
457
+ else stamp = `${weekdayLabel}_omitido`;
458
+ const where = `RECORD_ID() = "${candidate.recordId}"`;
459
+ await airtableService.updateRecordByFilter(Symptoms_ID, TABLE, where, {
460
+ [F.review]: stamp,
461
+ [AUDIT.rationale]: outcome.rationale || outcome.error || '',
462
+ [AUDIT.turnId]: outcome.turnId || '',
463
+ }, candidate.code);
464
+ }
465
+
466
+ async function mapWithConcurrency(items, limit, worker) {
467
+ const results = new Array(items.length);
468
+ let cursor = 0;
469
+ const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
470
+ while (cursor < items.length) {
471
+ const index = cursor++;
472
+ results[index] = await worker(items[index], index);
473
+ }
474
+ });
475
+ await Promise.all(runners);
476
+ return results;
477
+ }
478
+
479
+ async function runOutreachSweep({
480
+ now = new Date(),
481
+ dryRun = false,
482
+ limit = 100,
483
+ concurrency = 3,
484
+ patientScope = null,
485
+ includePreviouslySwept = false,
486
+ cadence = 'daily',
487
+ mode = 'continuity',
488
+ source = WEEKLY_SOURCE,
489
+ runOutreachTurn,
490
+ } = {}) {
491
+ if (typeof runOutreachTurn !== 'function') {
492
+ throw new Error('runOutreachSweep requires a runOutreachTurn function');
493
+ }
494
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) {
495
+ throw new Error('limit must be an integer from 1 to 100');
496
+ }
497
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 10) {
498
+ throw new Error('concurrency must be an integer from 1 to 10');
499
+ }
500
+ if (patientScope !== null && (!Array.isArray(patientScope)
501
+ || patientScope.some((code) => typeof code !== 'string'))) {
502
+ throw new Error('patientScope must be null or an array of canonical patient codes');
503
+ }
504
+ if (includePreviouslySwept && !dryRun) {
505
+ throw new Error('includePreviouslySwept is permitted only on a dry run');
506
+ }
507
+ if (!['continuity', 'monday_triage_recovery'].includes(mode)) {
508
+ throw new Error('mode must be continuity or monday_triage_recovery');
509
+ }
510
+ if (![WEEKLY_SOURCE, SCOPE_SOURCE].includes(source)) {
511
+ throw new Error('source must be weekly or patient_scope');
512
+ }
513
+ if (source === SCOPE_SOURCE && (mode !== 'continuity' || cadence !== 'daily' || !Array.isArray(patientScope))) {
514
+ throw new Error('the patient_scope source requires continuity mode, daily cadence and a patientScope');
515
+ }
516
+
517
+ const localWeekday = moment.tz(now, DEFAULT_TIMEZONE).isoWeekday();
518
+ if (mode === 'monday_triage_recovery' && localWeekday !== 1) {
519
+ return { ran: false, weekday: localWeekday, reason: 'not_monday', counts: {} };
520
+ }
521
+
522
+ // Triage owns the morning. This is deliberately enforced below the cron so a manual invocation
523
+ // cannot race the 08:00 questionnaire send or its delivery reconciliation.
524
+ if (isWithinTriageProtectionWindow(now)) {
525
+ const weekday = moment.tz(now, DEFAULT_TIMEZONE).isoWeekday();
526
+ logger.info('[outreachSweep] triage protection window — nothing sent', { weekday });
527
+ return { ran: false, weekday, reason: 'triage_protection_window', counts: {} };
528
+ }
529
+
530
+ const rows = await airtableService.getRecordByFilter(
531
+ Symptoms_ID, TABLE, 'TRUE()', mode === 'monday_triage_recovery' ? null : VIEW, Object.values(F), true,
532
+ );
533
+ const { candidates, targetDays, weekday } = source === SCOPE_SOURCE
534
+ ? { candidates: await loadScopeCandidates({ now, viewRows: rows || [], patientScope }), targetDays: [], weekday: localWeekday }
535
+ : buildCandidates(rows || [], { now, cadence, mode });
536
+ if (cadence === 'legacy' && !targetDays.length) {
537
+ logger.info('[outreachSweep] not a sweep day — nothing to do', { weekday });
538
+ return { ran: false, weekday, reason: 'not_a_sweep_day', counts: {} };
539
+ }
540
+
541
+ // The scheduler is not the guard. An operator running the sweep by hand at 03:00 must not wake
542
+ // every candidate, so the window is checked here as well as by whatever invoked us.
543
+ if (!isWithinHourWindow(now, PATIENT_CONTACT_WINDOW)) {
544
+ logger.info('[outreachSweep] outside patient contact hours — nothing sent', { weekday });
545
+ return { ran: false, weekday, reason: 'quiet_hours', counts: {} };
546
+ }
547
+
548
+ // An explicit empty scope means "nobody", not "scope omitted". This matters for a canary
549
+ // allowlist that does not intersect the consumer's owned patients: falling back to all patients
550
+ // would turn a one-number launch into an unbounded live batch.
551
+ const scoped = Array.isArray(patientScope)
552
+ ? candidates.filter((c) => patientScope.includes(c.code))
553
+ : candidates;
554
+
555
+ const counts = { candidates: scoped.length, rejected: 0, run: 0, write: 0, accepted: 0, delivered: 0, hold: 0, skipped: 0, error: 0 };
556
+ const rejectedBy = {};
557
+ const admitted = [];
558
+
559
+ for (const candidate of scoped) {
560
+ const reason = await rejectionReason(candidate, { now, includePreviouslySwept, cadence, mode });
561
+ if (reason) {
562
+ counts.rejected++;
563
+ rejectedBy[reason] = (rejectedBy[reason] || 0) + 1;
564
+ continue;
565
+ }
566
+ admitted.push(candidate);
567
+ if (admitted.length >= limit) break;
568
+ }
569
+
570
+ const weekdayLabel = moment.tz(now, DEFAULT_TIMEZONE).locale('es').format('dddd');
571
+ const decisions = await mapWithConcurrency(admitted, concurrency, async (candidate) => {
572
+ const brief = await enrichBrief(candidate);
573
+ if (!dryRun && !await claimCandidate({ candidate, weekdayLabel, dryRun, now })) {
574
+ counts.rejected++;
575
+ rejectedBy.claim_lost = (rejectedBy.claim_lost || 0) + 1;
576
+ return { code: candidate.code, recordId: candidate.recordId, decision: 'skipped', holdReason: 'claim_lost' };
577
+ }
578
+ try {
579
+ const outcome = await runOutreachTurn(candidate.code, {
580
+ brief,
581
+ reason: candidate.reason,
582
+ firstName: candidate.name,
583
+ dryRun,
584
+ reminderType: 'seguimiento',
585
+ reminderPrefix: mode === 'monday_triage_recovery' ? 'recovery' : null,
586
+ allowFollowUp: mode === 'monday_triage_recovery',
587
+ triggeredBy: `seguimiento:${candidate.recordId}`,
588
+ });
589
+ counts.run++;
590
+ if (outcome.decision === 'skipped') {
591
+ counts.skipped++;
592
+ await recordOutcome({
593
+ candidate,
594
+ outcome: { ...outcome, decision: 'hold', rationale: outcome.rationale || outcome.holdReason || 'turn skipped' },
595
+ weekdayLabel,
596
+ dryRun,
597
+ });
598
+ return { code: candidate.code, recordId: candidate.recordId, ...outcome };
599
+ }
600
+ counts[outcome.decision === 'write' ? 'write' : 'hold']++;
601
+ if (outcome.accepted) counts.accepted++;
602
+ if (outcome.delivered) counts.delivered++;
603
+ await recordOutcome({ candidate, outcome, weekdayLabel, dryRun });
604
+ return { code: candidate.code, recordId: candidate.recordId, dryRun, brief, ...outcome };
605
+ } catch (error) {
606
+ counts.error++;
607
+ logger.error('[outreachSweep] outreach turn failed', { code: candidate.code, error: error.message });
608
+ try {
609
+ await recordOutcome({ candidate, outcome: { error: error.message }, weekdayLabel, dryRun });
610
+ } catch (auditError) {
611
+ // An audit-schema outage must be loud, but it must not abort the other patients in this
612
+ // bounded batch. The pre-send claim remains `_en curso`, which the next sweep surfaces as
613
+ // stuck instead of retrying and risking a duplicate message.
614
+ logger.error('[outreachSweep] failed to record outreach error', {
615
+ code: candidate.code,
616
+ error: auditError.message,
617
+ originalError: error.message,
618
+ });
619
+ }
620
+ return { code: candidate.code, recordId: candidate.recordId, error: error.message };
621
+ }
622
+ });
623
+
624
+ logger.info('[outreachSweep] complete', { dryRun, counts, rejectedBy });
625
+ return { ran: true, weekday, cadence, mode, source, targetDays, dryRun, counts, rejectedBy, decisions };
626
+ }
627
+
628
+ module.exports = {
629
+ runOutreachSweep,
630
+ buildCandidates,
631
+ buildScopeCandidates,
632
+ rejectionReason,
633
+ priorSweepReason,
634
+ TARGET_DAYS_BY_WEEKDAY,
635
+ INACTIVITY_DAYS,
636
+ isWithinTriageProtectionWindow,
637
+ startOfLocalDay,
638
+ routineOutreachCollisionReason,
639
+ mondayTriageStillPending,
640
+ VIEW,
641
+ F,
642
+ AUDIT,
643
+ sweepClaims,
644
+ };