@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,2214 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ const runtimeConfig = require('../config/runtimeConfig');
4
+ const { httpError, requiredText } = require('../utils/httpErrorUtils');
5
+ const { inlineOf, oneLineOf } = require('../utils/coercionUtils');
6
+ const { logger } = require('../utils/logger');
7
+ const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
8
+ const { isoDay, mexicoDay } = require('../utils/dateUtils');
9
+ const {
10
+ CALL_OUTCOMES,
11
+ CANCELLABLE_AFTER_HANDOFF_STATUSES,
12
+ CANCELLABLE_STATUSES,
13
+ DECISION_SOURCES,
14
+ DOCTOR_DECISIONS,
15
+ HANDOFF_MODES,
16
+ INTERRUPTED_STATUSES,
17
+ FOLLOWUP_STATUSES,
18
+ RETURN_REASONS,
19
+ URGENCY_LEVELS,
20
+ URGENCY_RANK,
21
+ caseIdsOf,
22
+ getEscalationReview,
23
+ supersededCaseIds,
24
+ } = require('../models/escalationReviewModel');
25
+ const { getPatientAuditLog } = require('../models/patientAuditLogModel');
26
+ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
27
+ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
28
+ const { DrainingError } = require('../core/BatchingManager');
29
+ const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
30
+ const { conversationLink, writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
31
+ const { renderDoctorMessage, templateSummary, withIdentity } = require('../clinical/helpers/doctorReviewMessageHelper');
32
+ const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
33
+ const { drugsNamedIn } = require('../clinical/services/treatmentProposalService');
34
+ const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
35
+ const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
36
+ const { humanReplyFilter } = require('../clinical/config/safetyNetConfig');
37
+ const {
38
+ feverPatientTimerLive: feverTimerLive,
39
+ escalationPatientTimerLive: escalationTimerLive,
40
+ escalationApproverAlertLive,
41
+ escalationAutoHandoffLive,
42
+ } = require('../clinical/flags/escalationFlags');
43
+ const { chemoContextLive } = require('../clinical/flags/clinicalContextFlags');
44
+ const { cytotoxicWindowDays, daysSinceLastCytotoxic } = require('../clinical/helpers/chemoContextHelper');
45
+ const { readRecordedChemo } = require('../clinical/helpers/clinicalProfileHelper');
46
+ const { composePrompt } = require('../clinical/services/promptComposerService');
47
+ const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
48
+
49
+ const { getPatientInformation, logPatientChange } = require('./patientService');
50
+ const { MAX_NOTE_LENGTH, openCaseIds, readPatientCases, updatePatientTask } = require('./patientTaskService');
51
+ const { countMessages } = require('./messageService');
52
+ const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
53
+ const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
54
+ const { effectiveUrgencyOf, patientTimerMinutes, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
55
+ const { caseTaskLive, scheduleCaseSync } = require('./escalationCaseTaskService');
56
+ const { groupConfigured, sendTeamAlert, teamChannelConfigured } = require('./teamAlertService');
57
+
58
+ const getMessaging = () => require('../core/NexusMessaging');
59
+
60
+ const AUDIT_SOURCE = 'escalation_review';
61
+ const RECENT_REVIEW_LIMIT = 20;
62
+ const TIMELINE_LIMIT = 500;
63
+ const MAX_REVIEW_UPDATES = 50;
64
+ const DRAFT_DEBOUNCE_MS = 20 * 1000;
65
+ const DRAFT_OPERATOR = 'bot:escalationDraft';
66
+ const AUTO_HANDOFF_OPERATOR = 'bot:characterizationOutcome';
67
+ const MAX_DOCTOR_UPDATES = 3;
68
+ const DIRECT_CHAT_ATTEMPTS = 3;
69
+ const RECHECK_DELAY_MS = 60 * 1000;
70
+ const ALERT_RETRY_DELAY_MS = 2 * 60 * 1000;
71
+ const MAX_ALERT_ATTEMPTS = 3;
72
+ const BOOKKEEPING = { timestamps: false };
73
+ const PREVIOUS_REVIEW_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
74
+ const DUPLICATE_KEY_ERROR = 11000;
75
+ const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
76
+ const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
77
+ const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
78
+ const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'monitoring', 'needs_intervention'];
79
+ const SENDABLE_STATUSES = ['approved', 'needs_intervention'];
80
+ const DECIDABLE_STATUSES = ['draft_ready', 'awaiting_doctor'];
81
+ const SETTLEABLE_STATUSES = ['indications_sent', 'monitoring'];
82
+ const DRAFTLESS_DECISIONS = ['monitor', 'returned'];
83
+ const SETTLED_TRAJECTORIES = ['improving', 'stable'];
84
+ const ALERTED_URGENCIES = ['stat', 'asap'];
85
+ const ALERT_MARKS = { stat: '🔴', asap: '🟠', urgent: '🟡' };
86
+ const DEFAULT_FEVER_TIMER_MINUTES = 15;
87
+ const FEVER_TIMER_PROMPT_ID = 'fever_patient_timer';
88
+ const FEVER_TIMER_OPERATOR = 'fever_patient_timer';
89
+ const FEVER_CATEGORY = 'febrile_neutropenia';
90
+ const PATIENT_TIMER_PROMPT_IDS = { stat: 'stat_patient_timer', asap: 'asap_patient_timer' };
91
+ const PATIENT_TIMER_OPERATOR = 'escalation_patient_timer';
92
+ const STAFF_ORIGINS = ['whatsapp_platform', 'instruction', 'system'];
93
+ const PRE_DECISION_STATUSES = ['open', 'documenting', 'draft_ready', 'handing_off', 'awaiting_doctor'];
94
+ const ALERT_OPERATOR = 'bot:escalationAlert';
95
+ const AIRTABLE_TRANSPORT = 'airtable';
96
+ const NOT_RECORDED = 'no se registró en Airtable';
97
+ const RECLASSIFIABLE_STATUSES = [...DOCUMENTING_STATUSES, 'awaiting_doctor'];
98
+ const SAME_URGENCY = 'The review is already at that urgency';
99
+ const RECLASSIFY_CHANGED = 'The review changed while you were reclassifying it; read it again before changing the urgency';
100
+ const DIRECT_CHAT_STATUSES = ['open', 'documenting', 'draft_ready', 'returned', 'awaiting_doctor', 'approved', 'needs_intervention'];
101
+ const APPROVALS = ['approved', 'edited_approved'];
102
+ const STALE_DRAFT = 'New information reached the review after this draft; wait for the updated draft before approving';
103
+ const STALE_HANDOFF = 'New information reached the review after the draft the doctor received; it went back to documenting for a new draft';
104
+ const DRAFT_CHANGED = 'A newer draft was written after the one you saw; read it before deciding';
105
+ const OUTSIDE_WINDOW_ROUTES = ['template_recovery', 'predefined_template'];
106
+ const MAX_TEMPLATE_TEXT_LENGTH = 800;
107
+ const STATUS_CONFLICT = 'The escalation review does not allow this action in its current status';
108
+ const CANCEL_NEEDS_REASON = 'The doctor is already waiting on this review; cancelling it requires a reason';
109
+ const INTERRUPTION_CONFLICT = 'The escalation review was interrupted; closing it requires interruptionNotes stating what was verified';
110
+ const INTERRUPTION_GRACE_MS = 10 * 60 * 1000;
111
+ const INTERRUPTION_TOO_SOON = 'The escalation review may still be sending; wait for it to settle before adjudicating it';
112
+
113
+ const patientCodeOf = (code) => {
114
+ const patientCode = ensureWhatsAppFormat(String(code ?? '').trim());
115
+ if (!PATIENT_CODE.test(patientCode)) throw httpError(400, 'A valid WhatsApp ID is required');
116
+ return patientCode;
117
+ };
118
+
119
+ const optionalText = (value) => (value == null ? null : String(value));
120
+
121
+ // The open triage cases the team saw when closing the review; null when the caller did not say.
122
+ function closingCaseIdsOf(value) {
123
+ if (value == null) return null;
124
+ if (!Array.isArray(value) || value.some((recordId) => typeof recordId !== 'string')) throw httpError(400, 'closingCaseIds must be a list of case ids');
125
+ return [...new Set(value.map((recordId) => recordId.trim()).filter(Boolean))];
126
+ }
127
+
128
+ const reviewIdOf = (id) => {
129
+ if (!mongoose.Types.ObjectId.isValid(id)) throw httpError(400, 'A valid escalation review id is required');
130
+ return id;
131
+ };
132
+
133
+ const configured = (key) => {
134
+ const value = runtimeConfig.get(key);
135
+ if (!value) throw httpError(503, `${key} is not configured`);
136
+ return value;
137
+ };
138
+
139
+ const STATUS_AFTER = { edited_approved: 'approved', monitor: 'monitoring' };
140
+ const statusAfter = (decision) => STATUS_AFTER[decision] ?? decision;
141
+
142
+ const redactedError = (error) => redactDirectIdentifiers(String(error?.message || ''));
143
+
144
+ const redactedStack = (error) => redactDirectIdentifiers(String(error?.stack || ''));
145
+
146
+ const sendDidNotHappen = (error) => Boolean(error?.statusCode) || (Number.isInteger(error?.status) && error?.code != null);
147
+
148
+ const audit = (review, updatedBy, requestId, changes) => logPatientChange({
149
+ code: review.patientCode,
150
+ updatedBy,
151
+ source: AUDIT_SOURCE,
152
+ requestId,
153
+ changes: { escalationReviewId: String(review._id), ...changes },
154
+ });
155
+
156
+ async function resumeAssistant(review, operator = null, requestId = null) {
157
+ if (review.assistantPausedByReview !== true) return review;
158
+ const stopClaiming = () => getEscalationReview()
159
+ .updateOne({ _id: review._id }, { $set: { assistantPausedByReview: false } });
160
+ try {
161
+ await switchThreadStoppedStatus(review.patientCode, false);
162
+ await stopClaiming();
163
+ return { ...review, assistantPausedByReview: false };
164
+ } catch (error) {
165
+ logger.error('[EscalationReview] The assistant could not be resumed after this review', {
166
+ escalationReviewId: String(review._id), error: error.message,
167
+ });
168
+ await audit(review, operator ?? review.closedBy ?? 'system', requestId, { action: 'assistant_resume_failed' });
169
+ return review;
170
+ }
171
+ }
172
+
173
+ const withCaseMirror = (review, update, changes) => {
174
+ const recordIds = caseIdsOf(review);
175
+ if (!recordIds.length) return update;
176
+ return {
177
+ ...update,
178
+ $push: {
179
+ ...update.$push,
180
+ pendingCaseMirrors: { $each: recordIds.map((recordId) => ({ recordId, changes })) },
181
+ },
182
+ };
183
+ };
184
+
185
+ async function updateReview(id, allowedStatuses, update, extraFilter = {}) {
186
+ const EscalationReview = getEscalationReview();
187
+ const review = await EscalationReview.findOneAndUpdate({ _id: id, status: { $in: allowedStatuses }, ...extraFilter }, update, { new: true }).lean();
188
+ if (review) return review;
189
+ const exists = await EscalationReview.exists({ _id: id });
190
+ if (!exists) throw httpError(404, 'Escalation review not found');
191
+ throw httpError(409, STATUS_CONFLICT);
192
+ }
193
+
194
+ async function loadReview(id) {
195
+ const review = await getEscalationReview().findById(id).lean();
196
+ if (!review) throw httpError(404, 'Escalation review not found');
197
+ return review;
198
+ }
199
+
200
+ const newOperationClaim = () => String(new mongoose.Types.ObjectId());
201
+
202
+ const releaseReview = (id, from, to, claim = null) => getEscalationReview().updateOne(
203
+ { _id: id, status: from, ...(claim ? { operationClaim: claim } : {}) },
204
+ { $set: { status: to, operationClaim: null } },
205
+ );
206
+
207
+ async function completeOperation(id, claim, fromStatus, recordUpdate, nextStatus, lateUpdate = recordUpdate) {
208
+ const EscalationReview = getEscalationReview();
209
+ const claimCleared = (update) => ({ ...update, $set: { ...update.$set, operationClaim: null } });
210
+ const record = claimCleared(recordUpdate);
211
+ const settled = await EscalationReview.findOneAndUpdate(
212
+ { _id: id, status: fromStatus, operationClaim: claim },
213
+ { ...record, $set: { ...record.$set, status: nextStatus } },
214
+ { new: true },
215
+ ).lean();
216
+ if (settled) return settled;
217
+
218
+ const recorded = await EscalationReview.findOneAndUpdate(
219
+ { _id: id, operationClaim: claim },
220
+ claimCleared(lateUpdate),
221
+ { new: true },
222
+ ).lean();
223
+ if (recorded) {
224
+ logger.error('[EscalationReview] The review moved on while sending; the record was kept and the status left alone', {
225
+ escalationReviewId: String(id),
226
+ status: recorded.status,
227
+ expected: fromStatus,
228
+ });
229
+ return recorded;
230
+ }
231
+
232
+ if (!await EscalationReview.exists({ _id: id })) throw httpError(404, 'Escalation review not found');
233
+ throw httpError(409, STATUS_CONFLICT);
234
+ }
235
+
236
+ const summarise = (outcomes) => {
237
+ if (!outcomes.length) return 'skipped';
238
+ if (outcomes.every((outcome) => outcome.status === 'superseded')) return 'superseded';
239
+ if (outcomes.every((outcome) => outcome.status === 'failed')) return 'failed';
240
+ if (outcomes.some((outcome) => outcome.status === 'failed')) return 'partial';
241
+ return 'updated';
242
+ };
243
+
244
+ async function syncCase(review, operator, requestId) {
245
+ const recordIds = caseIdsOf(review);
246
+ if (!recordIds.length) return { review, caseMirror: 'skipped', caseMirrors: [] };
247
+ const EscalationReview = getEscalationReview();
248
+ const pending = review.pendingCaseMirrors || [];
249
+ if (!pending.length) return { review, caseMirror: 'updated', caseMirrors: [] };
250
+
251
+ const covered = new Set(recordIds);
252
+ const byRecord = new Map();
253
+ const abandoned = [];
254
+ for (const mirror of pending) {
255
+ const recordId = mirror.recordId ?? review.patientCaseRecordId;
256
+ if (recordId && !covered.has(recordId)) {
257
+ abandoned.push(mirror._id);
258
+ continue;
259
+ }
260
+ if (!recordId) {
261
+ logger.error('[EscalationReview] A queued case change names no case and the review has none', {
262
+ escalationReviewId: String(review._id),
263
+ });
264
+ continue;
265
+ }
266
+ const entries = byRecord.get(recordId) || [];
267
+ entries.push(mirror);
268
+ byRecord.set(recordId, entries);
269
+ }
270
+
271
+ let superseded;
272
+ try {
273
+ superseded = await supersededCaseIds(EscalationReview, review);
274
+ } catch (error) {
275
+ logger.error('[EscalationReview] Could not check whether a newer review supersedes these cases', {
276
+ escalationReviewId: String(review._id),
277
+ error: redactedError(error),
278
+ stack: redactedStack(error),
279
+ });
280
+ const outcomes = [...byRecord.keys()].map((recordId) => ({ recordId, status: 'failed' }));
281
+ return { review, caseMirror: summarise(outcomes), caseMirrors: outcomes };
282
+ }
283
+
284
+ const applied = await Promise.all([...byRecord].map(async ([recordId, entries]) => {
285
+ const ids = entries.map((entry) => entry._id);
286
+ if (superseded.has(recordId)) {
287
+ logger.warn('[EscalationReview] Dropping case changes a newer review has superseded', {
288
+ escalationReviewId: String(review._id),
289
+ recordId,
290
+ });
291
+ return { outcome: { recordId, status: 'superseded' }, ids };
292
+ }
293
+ try {
294
+ await updatePatientTask({
295
+ code: review.patientCode,
296
+ kind: 'cases',
297
+ recordId,
298
+ changes: Object.assign({}, ...entries.map((entry) => entry.changes)),
299
+ updatedBy: operator,
300
+ source: AUDIT_SOURCE,
301
+ requestId,
302
+ });
303
+ return { outcome: { recordId, status: 'updated' }, ids };
304
+ } catch (error) {
305
+ logger.error('[EscalationReview] Patient case mirror failed', {
306
+ escalationReviewId: String(review._id),
307
+ recordId,
308
+ error: redactedError(error),
309
+ stack: redactedStack(error),
310
+ });
311
+ return { outcome: { recordId, status: 'failed' }, ids: [] };
312
+ }
313
+ }));
314
+
315
+ const outcomes = applied.map((entry) => entry.outcome);
316
+ const settled = [...abandoned, ...applied.flatMap((entry) => entry.ids)];
317
+
318
+ const caseMirror = summarise(outcomes);
319
+ if (!settled.length) return { review, caseMirror, caseMirrors: outcomes };
320
+
321
+ try {
322
+ const synced = await EscalationReview.findOneAndUpdate(
323
+ { _id: review._id },
324
+ { $pull: { pendingCaseMirrors: { _id: { $in: settled } } } },
325
+ { new: true },
326
+ ).lean();
327
+ return { review: synced || review, caseMirror, caseMirrors: outcomes };
328
+ } catch (error) {
329
+ logger.error('[EscalationReview] Could not record the applied case changes', {
330
+ escalationReviewId: String(review._id),
331
+ error: redactedError(error),
332
+ stack: redactedStack(error),
333
+ });
334
+ return { review, caseMirror, caseMirrors: outcomes };
335
+ }
336
+ }
337
+
338
+ function doctorLink(review) {
339
+ return `${configured('PEOPL_INTERFACE_URL').replace(/\/+$/, '')}/escalation-review/${review._id}`;
340
+ }
341
+
342
+ function doctorIdentity(patient) {
343
+ const patientName = inlineOf(patient?.name);
344
+ const treatingDoctor = inlineOf(patient?.doctor) || inlineOf(patient?.doctor_auna);
345
+ const missing = [];
346
+ if (patientName.split(/\s+/).filter(Boolean).length < 2) missing.push('nombre completo del paciente');
347
+ if (!treatingDoctor) missing.push('médico tratante');
348
+ return { patientName, treatingDoctor, missing };
349
+ }
350
+
351
+ async function readDoctorIdentity(review) {
352
+ let patient;
353
+ try {
354
+ patient = await getPatientInformation(review.patientCode);
355
+ } catch (error) {
356
+ logger.error('[EscalationReview] The patient record could not be read for the doctor message', {
357
+ escalationReviewId: String(review._id), error: redactedError(error),
358
+ });
359
+ throw httpError(503, 'The patient record could not be read; the doctor message needs the patient name and the treating doctor');
360
+ }
361
+ return doctorIdentity(patient);
362
+ }
363
+
364
+ async function blockForMissingIdentity({ review, missing, operator }) {
365
+ const blocked = `No se puede preparar ni enviar el mensaje al médico: falta ${missing.join(' y ')} en el expediente`;
366
+ await getEscalationReview().updateOne(
367
+ { _id: review._id },
368
+ { $set: { identityBlock: { missing, blockedAt: new Date(), blockedBy: operator } } },
369
+ );
370
+ const { written, duplicate } = await writeUnresolvedRequest({
371
+ code: review.patientCode,
372
+ trace: null,
373
+ question: blocked,
374
+ details: `Revisión de escalación ${review._id}: completa ${missing.join(' y ')} en estado_general y vuelve a enviar al médico.`,
375
+ category: 'contact_team_member',
376
+ urgency: 'soon',
377
+ });
378
+ if (!written && !duplicate) {
379
+ logger.error('[EscalationReview] A doctor message was blocked for missing identity and the team ticket was not written', {
380
+ escalationReviewId: String(review._id), missing,
381
+ });
382
+ }
383
+ return httpError(422, blocked);
384
+ }
385
+
386
+ async function sendDoctorAlert({ message, approver, operator }) {
387
+ const doctorCode = ensureWhatsAppFormat(String(approver.phone ?? '').replace(/[^\d+]/g, ''));
388
+ if (!PATIENT_CODE.test(doctorCode)) throw httpError(422, 'The physician has no usable WhatsApp number on record');
389
+ const inWindow = await isWithin24HourWindow(doctorCode);
390
+ const outgoing = inWindow
391
+ ? { code: doctorCode, body: message.body, triggeredBy: operator }
392
+ : { code: doctorCode, contentSid: configured('ESCALATION_REVIEW_DOCTOR_ALERT_IDENTIFIED_CONTENT_SID'), variables: message.template, triggeredBy: operator };
393
+ const result = await getMessaging().sendMessage(outgoing);
394
+ if (!result?.success && !result?.completed) {
395
+ throw httpError(502, 'The WhatsApp message to the physician could not be sent');
396
+ }
397
+ return { transport: inWindow ? 'text' : 'template', messageId: result?.messageId || null };
398
+ }
399
+
400
+ async function patientIndicationsMessage({ review, finalText, outsideWindowRoute, operator }) {
401
+ const message = { code: review.patientCode, triggeredBy: operator };
402
+ if (await isWithin24HourWindow(review.patientCode)) return { ...message, body: finalText };
403
+ if (!outsideWindowRoute) {
404
+ throw httpError(422, `The patient is outside the 24-hour window; outsideWindowRoute must be one of: ${OUTSIDE_WINDOW_ROUTES.join(', ')}`);
405
+ }
406
+ if (outsideWindowRoute === 'template_recovery') return { ...message, body: finalText };
407
+
408
+ const text = finalText.replace(/\s+/g, ' ').trim();
409
+ if (text.length > MAX_TEMPLATE_TEXT_LENGTH) {
410
+ throw httpError(422, `The indications exceed ${MAX_TEMPLATE_TEXT_LENGTH} characters for the predefined template; use template_recovery`);
411
+ }
412
+ const patient = await getPatientInformation(review.patientCode);
413
+ const firstName = String(patient?.first_name ?? '').trim();
414
+ if (!firstName) throw httpError(422, 'The patient has no first name on record for the predefined template');
415
+ return {
416
+ ...message,
417
+ contentSid: configured('ESCALATION_REVIEW_PATIENT_INDICATIONS_CONTENT_SID'),
418
+ variables: { 1: firstName, 2: text },
419
+ };
420
+ }
421
+
422
+ const deliveryTransport = (message, result) => {
423
+ if (message.contentSid) return 'predefined_template';
424
+ return result.deferred ? 'template_recovery' : 'text';
425
+ };
426
+
427
+ let indexesReady = new WeakMap();
428
+
429
+ function ensureActiveReviewIndex(EscalationReview) {
430
+ const pending = indexesReady.get(EscalationReview);
431
+ if (pending) return pending;
432
+
433
+ const building = EscalationReview.ensureIndexes().catch((error) => {
434
+ indexesReady.delete(EscalationReview);
435
+ if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
436
+ logger.error('[EscalationReview] A uniqueness index could not be built', { error: redactedError(error) });
437
+ throw httpError(409, 'Escalation reviews cannot be opened: a uniqueness index could not be built. The server log names the index and the conflict; resolve it and retry.');
438
+ });
439
+ indexesReady.set(EscalationReview, building);
440
+ return building;
441
+ }
442
+
443
+ const _resetEscalationReviewIndexes = () => { indexesReady = new WeakMap(); };
444
+
445
+ async function reviewCaseIds(review) {
446
+ try {
447
+ return [...new Set([...caseIdsOf(review), ...await openCaseIds(review.patientCode)])];
448
+ } catch (error) {
449
+ logger.error('[EscalationReview] The patient cases could not be read; the review keeps the cases it had', {
450
+ escalationReviewId: String(review._id), error: redactedError(error),
451
+ });
452
+ return caseIdsOf(review);
453
+ }
454
+ }
455
+
456
+ async function requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseRecordIds }) {
457
+ const requested = patientCaseRecordIds ?? (patientCaseRecordId === null ? [] : [patientCaseRecordId]);
458
+ if (!Array.isArray(requested)) throw httpError(400, 'patientCaseRecordIds must be an array of case ids');
459
+ if (requested.some((recordId) => !String(recordId ?? '').trim())) {
460
+ throw httpError(400, 'patientCaseRecordIds must not contain blank case ids');
461
+ }
462
+ const recordIds = [...new Set(requested.map((recordId) => String(recordId ?? '').trim()).filter(Boolean))];
463
+ if (!recordIds.length) return [];
464
+
465
+ const cases = await readPatientCases(patientCode);
466
+ const known = new Set(cases.map((patientCase) => patientCase.recordId));
467
+ const stranger = recordIds.find((recordId) => !known.has(recordId));
468
+ if (stranger) throw httpError(404, 'Patient case not found for this patient');
469
+ return recordIds;
470
+ }
471
+
472
+ const BOT_OPERATOR = 'bot:reportMedicalEscalation';
473
+ const AGENT_OPERATOR = 'bot:clinicalAgent';
474
+
475
+ async function previousReviewIdOf(EscalationReview, patientCode, now) {
476
+ try {
477
+ const previous = await EscalationReview
478
+ .findOne({ patientCode, closedAt: { $gte: new Date(now.getTime() - PREVIOUS_REVIEW_WINDOW_MS) } }, { _id: 1 })
479
+ .sort({ closedAt: -1 })
480
+ .lean();
481
+ return previous ? String(previous._id) : null;
482
+ } catch (error) {
483
+ logger.warn('[EscalationReview] The previous review lookup failed; opening the review unlinked', { error: redactedError(error) });
484
+ return null;
485
+ }
486
+ }
487
+
488
+ async function recordReviewUpdate({ code, update, now = new Date(), settleInBackground = true } = {}) {
489
+ if (!update) return null;
490
+ try {
491
+ const patientCode = patientCodeOf(code);
492
+ const EscalationReview = getEscalationReview();
493
+ const pushed = await EscalationReview.findOneAndUpdate(
494
+ { patientCode, closedAt: null },
495
+ {
496
+ $push: { updates: { $each: [update], $slice: -MAX_REVIEW_UPDATES } },
497
+ $set: { draftDueAt: new Date(now.getTime() + DRAFT_DEBOUNCE_MS), draftAttempts: 0 },
498
+ },
499
+ { new: true },
500
+ ).lean();
501
+ if (!pushed) return null;
502
+
503
+ if (FOLLOWUP_STATUSES.includes(pushed.status)) {
504
+ await audit(pushed, AGENT_OPERATOR, null, { action: 'case_updated', turnId: update.turnId, tools: update.tools });
505
+ return await settleFollowUp(pushed, { background: settleInBackground });
506
+ }
507
+
508
+ const openingTurn = pushed.alarms?.[0]?.turnId === update.turnId;
509
+ const updated = openingTurn ? pushed : (await EscalationReview
510
+ .findOneAndUpdate({ _id: pushed._id }, { $set: { updatedSinceSeen: true } }, { new: true })
511
+ .lean()) ?? pushed;
512
+ const requeued = updated.status === 'returned'
513
+ ? await EscalationReview
514
+ .findOneAndUpdate({ _id: updated._id, status: 'returned' }, { $set: { status: 'documenting' } }, { new: true })
515
+ .lean()
516
+ : null;
517
+ await audit(updated, AGENT_OPERATOR, null, {
518
+ action: 'case_updated',
519
+ turnId: update.turnId,
520
+ tools: update.tools,
521
+ ...(requeued && { statusFrom: 'returned', statusTo: 'documenting' }),
522
+ });
523
+ return requeued || updated;
524
+ } catch (error) {
525
+ logger.error('[EscalationReview] The agent update was not recorded against the review', {
526
+ error: redactedError(error), stack: redactedStack(error),
527
+ });
528
+ return null;
529
+ }
530
+ }
531
+
532
+ const STALE_INTERRUPTION_NOTES = 'Cerrada automáticamente al llegar una alarma nueva; nadie verificó si la operación interrumpida se completó';
533
+
534
+ async function closeStaleInterruption(EscalationReview, patientCode, now) {
535
+ try {
536
+ const stale = await EscalationReview.findOne({
537
+ patientCode,
538
+ closedAt: null,
539
+ status: { $in: INTERRUPTED_STATUSES },
540
+ updatedAt: { $lte: new Date(now.getTime() - INTERRUPTION_GRACE_MS) },
541
+ }, { updatedAt: 1 }).lean();
542
+ if (!stale) return;
543
+ await closeEscalationReview({
544
+ id: String(stale._id), closedBy: BOT_OPERATOR, interruptionNotes: STALE_INTERRUPTION_NOTES, expectedUpdatedAt: stale.updatedAt,
545
+ });
546
+ } catch (error) {
547
+ logger[error?.statusCode === 409 ? 'warn' : 'error']('[EscalationReview] The interrupted review was not closed before the new alarm', { error: redactedError(error) });
548
+ }
549
+ }
550
+
551
+ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
552
+ try {
553
+ const patientCode = patientCodeOf(code);
554
+ const entry = { ...alarm, raisedAt: alarm?.raisedAt ?? now };
555
+ const EscalationReview = getEscalationReview();
556
+ const draftDueAt = new Date(now.getTime() + DRAFT_DEBOUNCE_MS);
557
+ const join = () => EscalationReview
558
+ .findOneAndUpdate({ patientCode, closedAt: null }, { $push: { alarms: entry }, $set: { draftDueAt, draftAttempts: 0 } }, { new: true })
559
+ .lean();
560
+
561
+ await ensureActiveReviewIndex(EscalationReview);
562
+ await closeStaleInterruption(EscalationReview, patientCode, now);
563
+ const joined = await join();
564
+ if (joined) {
565
+ await scheduleDoctorAlert(joined, entry, now);
566
+ await armPatientTimerOnJoin(joined, entry, now);
567
+ if (FOLLOWUP_STATUSES.includes(joined.status)) return await reopenFromFollowUp(joined, 'new_alarm');
568
+ if (!DOCUMENTING_STATUSES.includes(joined.status)) {
569
+ logger.error('[EscalationReview] An alarm arrived after the doctor already had the case', {
570
+ escalationReviewId: String(joined._id), status: joined.status, urgencyLevel: entry.urgencyLevel,
571
+ });
572
+ }
573
+ return joined;
574
+ }
575
+ try {
576
+ const created = (await EscalationReview.create({
577
+ patientCode,
578
+ openedBy: BOT_OPERATOR,
579
+ alarms: [entry],
580
+ assistantPausedByReview: false,
581
+ previousReviewId: await previousReviewIdOf(EscalationReview, patientCode, now),
582
+ draftDueAt,
583
+ })).toObject();
584
+ await scheduleDoctorAlert(created, entry, now);
585
+ return created;
586
+ } catch (error) {
587
+ if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
588
+ return await join();
589
+ }
590
+ } catch (error) {
591
+ logger.error('[EscalationReview] The alarm was not recorded against a review', {
592
+ error: error.message, stack: redactedStack(error),
593
+ });
594
+ return null;
595
+ }
596
+ }
597
+
598
+ function escalationAnchorOf(review, alarmId) {
599
+ const prior = currentAlarms(review).filter((alarm) => alarm.alarmId !== alarmId);
600
+ if (!prior.length) return null;
601
+ const levelOf = (alarm) => alarm.appliedLevel || alarm.urgencyLevel;
602
+ const rankOf = (alarm) => URGENCY_RANK[levelOf(alarm)] || 0;
603
+ const topRank = Math.max(...prior.map(rankOf));
604
+ const top = prior.filter((alarm) => rankOf(alarm) === topRank);
605
+ const topRow = [...top].reverse().find((alarm) => alarm.emergencyRecordId);
606
+ return { urgencyLevel: levelOf(top[0]), emergencyRecordId: topRow?.emergencyRecordId || null };
607
+ }
608
+
609
+ async function attachEmergencyRow({ reviewId, alarmId, emergencyRecordId, appliedLevel = null }) {
610
+ try {
611
+ await getEscalationReview().updateOne(
612
+ { _id: reviewId, 'alarms.alarmId': alarmId },
613
+ { $set: { 'alarms.$.emergencyRecordId': emergencyRecordId, 'alarms.$.appliedLevel': appliedLevel } },
614
+ { timestamps: false },
615
+ );
616
+ } catch (error) {
617
+ logger.error('[EscalationReview] The emergency row was not linked to its alarm', {
618
+ error: error.message, stack: redactedStack(error),
619
+ });
620
+ }
621
+ }
622
+
623
+ async function openEscalationReview({
624
+ code,
625
+ patientCaseRecordId = null,
626
+ patientCaseRecordIds = null,
627
+ openedBy,
628
+ requestId = null,
629
+ } = {}) {
630
+ const patientCode = patientCodeOf(code);
631
+ const operator = requiredText(openedBy, 'openedBy');
632
+ const patient = await getPatientInformation(patientCode);
633
+ if (!patient) throw httpError(404, 'Patient not found');
634
+
635
+ const recordIds = await requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseRecordIds });
636
+ const fields = {
637
+ patientCode,
638
+ openedBy: operator,
639
+ patientCaseRecordIds: recordIds,
640
+ assistantPausedByReview: false,
641
+ draftDueAt: new Date(Date.now() + DRAFT_DEBOUNCE_MS),
642
+ };
643
+
644
+ const EscalationReview = getEscalationReview();
645
+ let review;
646
+ try {
647
+ await ensureActiveReviewIndex(EscalationReview);
648
+ review = (await EscalationReview.create(fields)).toObject();
649
+ } catch (error) {
650
+ if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
651
+ let existing = await EscalationReview.findOne({ patientCode, closedAt: null }).lean();
652
+ if (!existing) {
653
+ throw httpError(409, 'This patient already has a review being opened; try again in a moment');
654
+ }
655
+ if (recordIds.length && !(existing.patientCaseRecordIds ?? []).length) {
656
+ const adopted = await EscalationReview.findOneAndUpdate(
657
+ { _id: existing._id, closedAt: null, patientCaseRecordIds: { $size: 0 } },
658
+ { $set: { patientCaseRecordIds: recordIds } },
659
+ { new: true },
660
+ ).lean();
661
+ if (adopted) {
662
+ existing.patientCaseRecordIds = adopted.patientCaseRecordIds;
663
+ await audit(existing, operator, requestId, { action: 'cases_attached', patientCaseRecordIds: recordIds });
664
+ } else {
665
+ const fresh = await EscalationReview.findOne({ _id: existing._id, closedAt: null }).lean();
666
+ if (!fresh) {
667
+ throw httpError(409, 'The review closed while this one was being opened; try again');
668
+ }
669
+ existing = fresh;
670
+ }
671
+ }
672
+ return { review: existing, created: false };
673
+ }
674
+ await audit(review, operator, requestId, { action: 'opened', patientCaseRecordIds: recordIds });
675
+ return { review, created: true };
676
+ }
677
+
678
+ async function requestBotDraft({ id, requestedBy, requestId = null } = {}) {
679
+ const reviewId = reviewIdOf(id);
680
+ const operator = requiredText(requestedBy, 'requestedBy');
681
+ const review = await loadReview(reviewId);
682
+ if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
683
+ if ((review.drafts ?? []).at(-1)?.writtenBy && review.drafts.at(-1).writtenBy !== DRAFT_OPERATOR) {
684
+ throw httpError(409, 'The latest draft was written by the team; edit it instead of asking for a new one');
685
+ }
686
+ const now = new Date();
687
+ if (review.draftDueAt && new Date(review.draftDueAt) > now) return review;
688
+ const scheduled = await getEscalationReview().findOneAndUpdate(
689
+ {
690
+ _id: reviewId,
691
+ status: { $in: DOCUMENTING_STATUSES },
692
+ drafts: { $size: (review.drafts ?? []).length },
693
+ $or: [{ draftDueAt: null }, { draftDueAt: { $lte: now } }],
694
+ },
695
+ { $set: { draftDueAt: now, draftAttempts: 0 } },
696
+ { new: true },
697
+ ).lean();
698
+ if (!scheduled) {
699
+ const latest = await loadReview(reviewId);
700
+ if (latest.draftDueAt && new Date(latest.draftDueAt) > now) return latest;
701
+ throw httpError(409, STATUS_CONFLICT);
702
+ }
703
+ await audit(scheduled, operator, requestId, { action: 'draft_requested' });
704
+ return scheduled;
705
+ }
706
+
707
+ async function isEscalationApprover(operator) {
708
+ try {
709
+ return Boolean(await getEscalationApprover(operator));
710
+ } catch (error) {
711
+ logger.error('[EscalationReview] Approver lookup failed; serving the review as read only', {
712
+ error: redactedError(error),
713
+ stack: redactedStack(error),
714
+ });
715
+ return false;
716
+ }
717
+ }
718
+
719
+ async function getEscalationReviewById({ id, requestedBy } = {}) {
720
+ const reviewId = reviewIdOf(id);
721
+ const operator = requiredText(requestedBy, 'requestedBy');
722
+ const review = await loadReview(reviewId);
723
+ const readAt = new Date();
724
+ const isApprover = await isEscalationApprover(operator);
725
+ const EscalationReview = getEscalationReview();
726
+ const warnUnmarked = (error) => logger.warn('[EscalationReview] The review read was not marked', {
727
+ escalationReviewId: String(review._id), error: redactedError(error),
728
+ });
729
+ if (review.updatedSinceSeen) {
730
+ await EscalationReview
731
+ .updateOne({ _id: review._id, updatedAt: review.updatedAt }, { $set: { updatedSinceSeen: false } }, { timestamps: false })
732
+ .catch(warnUnmarked);
733
+ }
734
+ if (isApprover) {
735
+ await EscalationReview
736
+ .updateOne({ _id: review._id }, { $max: { approverViewedAt: readAt } }, { timestamps: false })
737
+ .catch(warnUnmarked);
738
+ }
739
+ return { review, isApprover, responseDeadline: responseDeadlineOf(review, responseDeadlinePolicy()) };
740
+ }
741
+
742
+ async function getReviewTimeline({ id } = {}) {
743
+ const review = await loadReview(reviewIdOf(id));
744
+ const rows = await getPatientAuditLog()
745
+ .find({ code: review.patientCode, source: AUDIT_SOURCE, 'changes.escalationReviewId': String(review._id) })
746
+ .sort({ createdAt: -1 })
747
+ .limit(TIMELINE_LIMIT)
748
+ .lean();
749
+ const alarms = (review.alarms ?? []).map((alarm) => ({
750
+ at: alarm.raisedAt,
751
+ action: 'alarm',
752
+ by: BOT_OPERATOR,
753
+ details: { urgencyLevel: alarm.urgencyLevel, symptom: alarm.symptom ?? null },
754
+ }));
755
+ const steps = rows.map(({ createdAt, updatedBy, changes }) => {
756
+ const details = { ...changes };
757
+ delete details.escalationReviewId;
758
+ delete details.action;
759
+ return { at: createdAt, action: changes?.action ?? null, by: updatedBy, details };
760
+ });
761
+ return [...alarms, ...steps].sort((a, b) => new Date(a.at) - new Date(b.at)).slice(-TIMELINE_LIMIT);
762
+ }
763
+
764
+ async function listEscalationReviews({ code } = {}) {
765
+ const patientCode = patientCodeOf(code);
766
+ return getEscalationReview().find({ patientCode }).sort({ createdAt: -1 }).limit(RECENT_REVIEW_LIMIT).lean();
767
+ }
768
+
769
+ const redraftAfterCall = () => ({ draftDueAt: new Date(Date.now() + DRAFT_DEBOUNCE_MS), draftAttempts: 0 });
770
+
771
+ async function appendKeepingDraft(id, entry) {
772
+ const EscalationReview = getEscalationReview();
773
+ for (let attempt = 0; attempt < 2; attempt += 1) {
774
+ const kept = await EscalationReview
775
+ .findOneAndUpdate({ _id: id, status: 'draft_ready' }, { $push: { callLogs: entry }, $set: redraftAfterCall() }, { new: true })
776
+ .lean();
777
+ if (kept) return kept;
778
+
779
+ const moved = await EscalationReview
780
+ .findOneAndUpdate(
781
+ { _id: id, status: { $in: UNDRAFTED_STATUSES } },
782
+ { $push: { callLogs: entry }, $set: { status: 'documenting', ...redraftAfterCall() } },
783
+ { new: true },
784
+ )
785
+ .lean();
786
+ if (moved) return moved;
787
+ }
788
+ if (!await EscalationReview.exists({ _id: id })) throw httpError(404, 'Escalation review not found');
789
+ throw httpError(409, STATUS_CONFLICT);
790
+ }
791
+
792
+ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId = null } = {}) {
793
+ const reviewId = reviewIdOf(id);
794
+ const operator = requiredText(updatedBy, 'updatedBy');
795
+ if (!Array.isArray(patientCaseRecordIds)) throw httpError(400, 'patientCaseRecordIds must be an array of case ids');
796
+ const current = await loadReview(reviewId);
797
+ if (!DOCUMENTING_STATUSES.includes(current.status)) throw httpError(409, STATUS_CONFLICT);
798
+
799
+ const recordIds = await requestedCaseIds({ patientCode: current.patientCode, patientCaseRecordIds });
800
+ const casesChanged = {
801
+ $not: [{
802
+ $setEquals: [
803
+ {
804
+ $ifNull: [
805
+ '$patientCaseRecordIds',
806
+ { $cond: [{ $ifNull: ['$patientCaseRecordId', false] }, ['$patientCaseRecordId'], []] },
807
+ ],
808
+ },
809
+ recordIds,
810
+ ],
811
+ }],
812
+ };
813
+ const isBotDraft = (current.drafts ?? []).at(-1)?.writtenBy === DRAFT_OPERATOR;
814
+
815
+ const review = await updateReview(reviewId, DOCUMENTING_STATUSES, [{
816
+ $set: {
817
+ patientCaseRecordIds: recordIds,
818
+ status: { $cond: [{ $and: [{ $eq: ['$status', 'draft_ready'] }, casesChanged] }, 'documenting', '$status'] },
819
+ ...(isBotDraft && {
820
+ draftDueAt: { $cond: [casesChanged, new Date(Date.now() + DRAFT_DEBOUNCE_MS), '$draftDueAt'] },
821
+ draftAttempts: { $cond: [casesChanged, 0, '$draftAttempts'] },
822
+ }),
823
+ pendingCaseMirrors: {
824
+ $filter: {
825
+ input: { $ifNull: ['$pendingCaseMirrors', []] },
826
+ as: 'mirror',
827
+ cond: { $in: [{ $ifNull: ['$$mirror.recordId', null] }, [...recordIds, null]] },
828
+ },
829
+ },
830
+ },
831
+ }]);
832
+ await audit(review, operator, requestId, { action: 'cases_selected', patientCaseRecordIds: recordIds });
833
+ return review;
834
+ }
835
+
836
+ async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy, requestId = null } = {}) {
837
+ const reviewId = reviewIdOf(id);
838
+ const operator = requiredText(loggedBy, 'loggedBy');
839
+ if (!CALL_OUTCOMES.includes(outcome)) throw httpError(400, `outcome must be one of: ${CALL_OUTCOMES.join(', ')}`);
840
+ const callTime = calledAt == null ? new Date() : new Date(calledAt);
841
+ if (Number.isNaN(callTime.getTime())) throw httpError(400, 'calledAt must be a valid date');
842
+
843
+ const entry = { outcome, notes: optionalText(notes), calledAt: callTime, loggedBy: operator };
844
+ const review = outcome === 'contacted'
845
+ ? await updateReview(reviewId, DOCUMENTING_STATUSES, { $push: { callLogs: entry }, $set: { status: 'documenting', ...redraftAfterCall() } })
846
+ : await appendKeepingDraft(reviewId, entry);
847
+ await audit(review, operator, requestId, { action: 'call_logged', outcome });
848
+ if (outcome !== 'contacted') return review;
849
+ return proposeNoteFacts(review, operator, requestId);
850
+ }
851
+
852
+ // Generation writes nothing: it fills the two boxes the navigator then edits and saves with addDraft.
853
+ // It is refused outside the statuses that accept a draft, so no one waits on a model for text that
854
+ // the review could no longer keep.
855
+ async function suggestDraft({ id, requestedBy, requestId = null } = {}) {
856
+ const reviewId = reviewIdOf(id);
857
+ const operator = requiredText(requestedBy, 'requestedBy');
858
+ const review = await loadReview(reviewId);
859
+ if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
860
+ const identity = await readDoctorIdentity(review);
861
+ if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
862
+ if (review.identityBlock) await getEscalationReview().updateOne({ _id: review._id }, { $unset: { identityBlock: '' } });
863
+
864
+ const draft = await generateEscalationDraft({
865
+ code: review.patientCode,
866
+ callLogs: review.callLogs ?? [],
867
+ alarms: review.alarms ?? [],
868
+ heldUrgentFlags: review.drafts?.at(-1)?.urgentUnassessedRedFlags ?? [],
869
+ reviewId: String(review._id),
870
+ });
871
+ // A generation run sends the patient's context to a model. That is what the audit exists to
872
+ // record, so it is written before the failure is reported, not after it.
873
+ if (draft.attempted) {
874
+ const recorded = await audit(review, operator, requestId, draft.completed
875
+ ? { action: 'draft_generated', protocolVersion: draft.protocolVersion }
876
+ : { action: 'draft_generation_failed', reason: redactedError({ message: draft.reason }) });
877
+ // logPatientChange swallows its own failures and answers null, so an unrecorded generation is
878
+ // otherwise indistinguishable from a recorded one. Say so where operations will see it.
879
+ if (!recorded) {
880
+ logger.error('[EscalationReview] A draft generation reached a model but was not recorded in the audit log', {
881
+ escalationReviewId: String(review._id),
882
+ completed: Boolean(draft.completed),
883
+ });
884
+ }
885
+ }
886
+ if (!draft.completed) throw httpError(draft.configured === false ? 503 : 502, draft.reason);
887
+
888
+ // Generating takes as long as a model call, and a review can be cancelled underneath it. Saying so
889
+ // here is what stops a navigator from editing text that addDraft would then refuse to keep.
890
+ const settled = await loadReview(reviewId);
891
+ if (!DOCUMENTING_STATUSES.includes(settled.status)) throw httpError(409, STATUS_CONFLICT);
892
+
893
+ return { ...draft, doctorText: withIdentity({ identity, review, doctorText: draft.doctorText }) };
894
+ }
895
+
896
+ const alertedRankOf = (review) => {
897
+ const decidedAt = (review.decisions ?? []).at(-1)?.createdAt;
898
+ const sinceMs = decidedAt ? new Date(decidedAt).getTime() : -Infinity;
899
+ return Math.max(0, ...(review.doctorAlerts ?? [])
900
+ .filter((sent) => sent.kind === 'initial' && !sent.error && new Date(sent.sentAt).getTime() > sinceMs)
901
+ .map((sent) => URGENCY_RANK[sent.urgencyLevel] || 0));
902
+ };
903
+
904
+ async function scheduleDoctorAlert(review, alarm, now) {
905
+ try {
906
+ if (!ALERTED_URGENCIES.includes(alarm?.urgencyLevel)) return;
907
+ if (URGENCY_RANK[alarm.urgencyLevel] <= alertedRankOf(review)) return;
908
+ const scheduled = await getEscalationReview().updateOne(
909
+ { _id: review._id, $nor: [{ doctorAlertKind: 'initial', doctorAlertDueAt: { $gt: now } }] },
910
+ { $set: { doctorAlertDueAt: now, doctorAlertKind: 'initial', doctorAlertAttempts: 0 } },
911
+ BOOKKEEPING,
912
+ );
913
+ if (scheduled.matchedCount) Object.assign(review, { doctorAlertDueAt: now, doctorAlertKind: 'initial' });
914
+ } catch (error) {
915
+ logger.error('[EscalationReview] The doctor alert was not scheduled', { escalationReviewId: String(review?._id), error: redactedError(error) });
916
+ }
917
+ }
918
+
919
+ const timerMs = (key, fallback) => {
920
+ const minutes = Number(runtimeConfig.get(key, fallback));
921
+ return (Number.isFinite(minutes) && minutes > 0 ? minutes : fallback) * 60 * 1000;
922
+ };
923
+
924
+ const appliedLevelOf = (alarm) => alarm.appliedLevel || alarm.urgencyLevel;
925
+
926
+ const feverAlarmsOf = (review) => currentAlarms(review)
927
+ .filter((alarm) => appliedLevelOf(alarm) === 'asap' && alarm.category === FEVER_CATEGORY);
928
+
929
+ async function feverTimerGap(patientCode, now) {
930
+ if (!chemoContextLive()) return 'chemo_context_off';
931
+ const chemo = await readRecordedChemo(patientCode);
932
+ if (chemo === undefined) return 'chemo_record_unreadable';
933
+ if (!chemo?.ultimaCitotoxica) return 'no_recorded_cytotoxic';
934
+ const days = daysSinceLastCytotoxic(chemo, mexicoDay(now));
935
+ if (days < 0) return 'last_cycle_in_future';
936
+ return days > cytotoxicWindowDays() ? 'outside_chemo_window' : null;
937
+ }
938
+
939
+ // The timer runs from the first alert of this episode at its level, so a retried alert never restarts it
940
+ // and a decision taken after it (which counts as taking the case) never moves it.
941
+ function timerSince(review, level) {
942
+ const alerts = (review.doctorAlerts ?? []).filter((sent) => sent.kind === 'initial' && sent.urgencyLevel === level);
943
+ if (!alerts.length) return null;
944
+ const lastMs = new Date(alerts.at(-1).sentAt).getTime();
945
+ const decidedMs = Math.max(-Infinity, ...(review.decisions ?? [])
946
+ .map((decision) => new Date(decision.createdAt).getTime())
947
+ .filter((ms) => ms < lastMs));
948
+ return new Date(alerts.find((sent) => new Date(sent.sentAt).getTime() > decidedMs).sentAt);
949
+ }
950
+
951
+ // The level whose timer is running: the highest alert sent since the last decision.
952
+ function timerLevelOf(review) {
953
+ const decidedMs = Math.max(-Infinity, ...(review.decisions ?? []).map((decision) => new Date(decision.createdAt).getTime()));
954
+ const alerted = (level) => (review.doctorAlerts ?? [])
955
+ .some((sent) => sent.kind === 'initial' && sent.urgencyLevel === level && new Date(sent.sentAt).getTime() > decidedMs);
956
+ return alerted('stat') ? 'stat' : 'asap';
957
+ }
958
+
959
+ // An asap fever on a recent cytotoxic cycle gets the fever prompt; any other stat or asap case gets its
960
+ // level's prompt while that timer is live. `gap` says why the fever prompt does not apply. Without the
961
+ // level timers, a prompt that fires was armed as the fever prompt and fires as armed.
962
+ async function patientTimerOf(review, level, now, { firing = false } = {}) {
963
+ const levelTimer = escalationTimerLive() && Boolean(PATIENT_TIMER_PROMPT_IDS[level]);
964
+ const armedAsFever = firing && !levelTimer && (review.alarms ?? []).some((alarm) => appliedLevelOf(alarm) === 'asap' && alarm.category === FEVER_CATEGORY);
965
+ const fever = level === 'asap' && feverTimerLive() && (armedAsFever || feverAlarmsOf(review).length > 0);
966
+ const gap = fever && !armedAsFever ? await feverTimerGap(review.patientCode, now) : null;
967
+ if (fever && !gap) {
968
+ return { timer: { level, fever: true, promptId: FEVER_TIMER_PROMPT_ID, operator: FEVER_TIMER_OPERATOR, ms: timerMs('FEVER_PATIENT_TIMER_MINUTES', DEFAULT_FEVER_TIMER_MINUTES) }, gap };
969
+ }
970
+ if (levelTimer) {
971
+ return { timer: { level, fever: false, promptId: PATIENT_TIMER_PROMPT_IDS[level], operator: PATIENT_TIMER_OPERATOR, ms: patientTimerMinutes(level) * 60 * 1000 }, gap };
972
+ }
973
+ return { timer: null, gap };
974
+ }
975
+
976
+ // One prompt per episode: a prompt delivered (or possibly delivered) since the episode began, or one whose
977
+ // turn is still running, blocks another; an errored or dropped attempt does not. `ownStart` is the
978
+ // marker of the run asking, so its own in-flight marker never blocks it.
979
+ function promptedSince(review, since, ownStart = null) {
980
+ const sinceMs = since.getTime();
981
+ const delivered = (review.doctorAlerts ?? [])
982
+ .some((sent) => sent.kind === 'patient_prompt' && (!sent.error || sent.possiblyDelivered) && new Date(sent.sentAt).getTime() >= sinceMs);
983
+ const startedMs = review.feverPromptStartedAt ? new Date(review.feverPromptStartedAt).getTime() : null;
984
+ return delivered || (startedMs != null && startedMs >= sinceMs && startedMs !== ownStart?.getTime());
985
+ }
986
+
987
+ // An approver merely opening the review does not count: only an answer, a stat escalation of an asap
988
+ // case, a paused thread or a staff member writing to the patient means someone took the case.
989
+ async function takenReason(review, since, timer, ownStart = null) {
990
+ // Staff acting before the case reached its timed level (on an earlier alarm of the same episode) did
991
+ // not take it: those signals count only from the first alarm the timer is for.
992
+ const atLevel = (alarm) => alarm.urgencyLevel === timer.level || appliedLevelOf(alarm) === timer.level;
993
+ const first = (timer.fever ? feverAlarmsOf(review) : currentAlarms(review).filter(atLevel))[0];
994
+ const from = new Date(Math.max(since.getTime(), first ? new Date(first.raisedAt).getTime() : -Infinity));
995
+ if (review.closedAt || !PRE_DECISION_STATUSES.includes(review.status)) return 'review_moved_on';
996
+ if (promptedSince(review, since, ownStart)) return 'already_prompted';
997
+ return caseTakenReason(review, from, timer.level);
998
+ }
999
+
1000
+ // What says the team took the case from `from` on, for a case timed at `level`.
1001
+ async function caseTakenReason(review, from, level) {
1002
+ const atOrAfter = (at) => at != null && new Date(at).getTime() >= from.getTime();
1003
+ if ((review.decisions ?? []).some((decision) => atOrAfter(decision.createdAt))) return 'decision';
1004
+ const stat = (alarm) => alarm.urgencyLevel === 'stat' || alarm.appliedLevel === 'stat';
1005
+ if (level !== 'stat' && currentAlarms(review).some(stat)) return 'stat_alarm';
1006
+ if ((review.urgencyReclassifications ?? []).some((change) => atOrAfter(change.at))) return 'reclassified';
1007
+ if ((review.callLogs ?? []).some((call) => call.outcome === 'contacted' && atOrAfter(call.calledAt))) return 'call_contacted';
1008
+ // A read error goes back to the sweep to retry; only a thread that does not exist (no turn to run
1009
+ // anyway) skips the prompt.
1010
+ const thread = await getThreadInfo(review.patientCode, { rethrow: true });
1011
+ if (!thread) return 'thread_missing';
1012
+ if (thread.stopped === true) return 'thread_paused';
1013
+ if (thread.hospitalizedAt) return 'patient_hospitalized';
1014
+ // Staff write from the platform or act through add-instruction / add-msg, always under their email;
1015
+ // automations (the timer itself included) sign with a name and never count.
1016
+ const staffMessages = await countMessages({ ...humanReplyFilter(review.patientCode, from), origin: { $in: STAFF_ORIGINS }, $and: [{ triggeredBy: /@/ }] });
1017
+ return staffMessages ? 'staff_message' : null;
1018
+ }
1019
+
1020
+ async function armPatientTimerOnJoin(review, alarm, now) {
1021
+ try {
1022
+ const level = appliedLevelOf(alarm);
1023
+ if (!escalationTimerLive() && !(feverTimerLive() && level === 'asap' && alarm.category === FEVER_CATEGORY)) return;
1024
+ if (!ALERTED_URGENCIES.includes(level) || alertedRankOf(review) !== URGENCY_RANK[level]) return;
1025
+ const since = timerSince(review, level);
1026
+ if (!since || promptedSince(review, since)) return;
1027
+ if (review.doctorAlertDueAt) return;
1028
+ const { timer, gap } = await patientTimerOf(review, level, now);
1029
+ if (!timer) {
1030
+ if (gap) await audit(review, ALERT_OPERATOR, null, { action: 'patient_prompt_not_armed', reason: gap });
1031
+ return;
1032
+ }
1033
+ // The patient gets the full timer from when the case became eligible, not from the earlier alert.
1034
+ await getEscalationReview().updateOne(
1035
+ { _id: review._id, doctorAlertDueAt: null },
1036
+ { $set: { doctorAlertDueAt: new Date(now.getTime() + timer.ms), doctorAlertKind: 'patient_prompt', doctorAlertAttempts: 0 } },
1037
+ BOOKKEEPING,
1038
+ );
1039
+ } catch (error) {
1040
+ logger.error('[EscalationReview] The patient timer was not set for a joining alarm', { escalationReviewId: String(review?._id), error: redactedError(error) });
1041
+ }
1042
+ }
1043
+
1044
+ // The alarm an alert is about: the one named, else the latest at its level, else the latest.
1045
+ const alarmFor = (review, urgencyLevel, alarmId) => (alarmId && (review.alarms ?? []).find((raised) => raised.alarmId === alarmId))
1046
+ ?? (review.alarms ?? []).findLast((raised) => raised.urgencyLevel === urgencyLevel) ?? review.alarms?.at(-1);
1047
+
1048
+ async function prepareDoctorAlert(review, urgencyLevel, { recipient = null, alarmId = null } = {}) {
1049
+ const identity = await readDoctorIdentity(review);
1050
+ if (identity.missing.length) throw new Error(`missing ${identity.missing.join(' and ')}`);
1051
+ const approver = recipient ?? await soleApprover();
1052
+ const link = conversationLink(review.patientCode);
1053
+ if (!link) throw new Error('missing the interface URL for the chat link');
1054
+ const alarm = alarmFor(review, urgencyLevel, alarmId);
1055
+ const symptom = inlineOf(alarm?.symptom);
1056
+ const urgency = urgencyLevel.toUpperCase();
1057
+ const patient = `${identity.patientName} (${identity.treatingDoctor})`;
1058
+ const message = {
1059
+ body: `${ALERT_MARKS[urgencyLevel]} ${[urgency, patient, symptom].filter(Boolean).join(' · ')}\n${link}`,
1060
+ template: { 1: identity.patientName, 2: identity.treatingDoctor, 3: [urgency, symptom].filter(Boolean).join(' · '), 4: link },
1061
+ };
1062
+ return { approver, message };
1063
+ }
1064
+
1065
+ const currentAlarms = (review) => {
1066
+ const alarms = review?.alarms ?? [];
1067
+ const decidedAt = (review?.decisions ?? []).at(-1)?.createdAt;
1068
+ return decidedAt ? alarms.filter((alarm) => new Date(alarm.raisedAt) > new Date(decidedAt)) : alarms;
1069
+ };
1070
+
1071
+ const topUrgencyOf = (review) => {
1072
+ const open = currentAlarms(review);
1073
+ return (open.length ? open : review.alarms ?? [])
1074
+ .reduce((top, alarm) => (URGENCY_RANK[alarm.urgencyLevel] > (URGENCY_RANK[top] || 0) ? alarm.urgencyLevel : top), null);
1075
+ };
1076
+
1077
+ const SENT_OUTCOMES = ['sent', 'unknown', 'already_answered'];
1078
+
1079
+ async function sendPatientPrompt({ id, release, lease, now }) {
1080
+ const review = await loadReview(reviewIdOf(id));
1081
+ const skip = async (current, reason) => {
1082
+ await release();
1083
+ await audit(current, ALERT_OPERATOR, null, { action: 'patient_prompt_skipped', reason });
1084
+ return null;
1085
+ };
1086
+ if (!feverTimerLive() && !escalationTimerLive()) return skip(review, 'flag_off');
1087
+ const level = timerLevelOf(review);
1088
+ const since = timerSince(review, level);
1089
+ if (!since) return skip(review, `no_${level}_alert`);
1090
+ const { timer, gap } = await patientTimerOf(review, level, now, { firing: true });
1091
+ if (!timer) return skip(review, gap ?? 'flag_off');
1092
+ const taken = await takenReason(review, since, timer);
1093
+ if (taken) return skip(review, taken);
1094
+
1095
+ let directive;
1096
+ try {
1097
+ directive = String((await composePrompt({ promptId: timer.promptId }))?.resolvedPrompt ?? '').trim();
1098
+ } catch (composeError) {
1099
+ // A failed read may be transient: the same slot comes back shortly, and the sweep's attempt cap
1100
+ // drops it (with a ledger entry) if Airtable stays unreachable.
1101
+ logger.error('[EscalationReview] The patient prompt could not be read; trying again shortly', { escalationReviewId: String(review._id), error: redactedError(composeError) });
1102
+ await release({ doctorAlertDueAt: new Date(Date.now() + ALERT_RETRY_DELAY_MS), doctorAlertKind: 'patient_prompt' });
1103
+ return null;
1104
+ }
1105
+ let error = directive ? null : `the ${timer.promptId} prompt is empty or missing`;
1106
+ let outcome = null;
1107
+ let startedAt = null;
1108
+ const settle = () => getEscalationReview()
1109
+ .updateOne({ _id: review._id, feverPromptStartedAt: startedAt }, { $set: { feverPromptStartedAt: null } }, BOOKKEEPING);
1110
+ if (error) {
1111
+ logger.error('[EscalationReview] The patient prompt has no directive; nothing was sent', { escalationReviewId: String(review._id), error });
1112
+ await release();
1113
+ } else {
1114
+ const fresh = await loadReview(review._id);
1115
+ const takenNow = await takenReason(fresh, since, timer);
1116
+ if (takenNow) return skip(fresh, takenNow);
1117
+ // The instruction runs a whole agent turn, which can outlast the sweep's lease; letting go of the
1118
+ // slot first keeps a second sweep from prompting the patient twice.
1119
+ const released = await release();
1120
+ if (lease && !released?.modifiedCount) {
1121
+ await audit(fresh, ALERT_OPERATOR, null, { action: 'lease_lost' });
1122
+ return null;
1123
+ }
1124
+ // While the turn runs, this marker stops both arming paths from setting a second prompt; it is
1125
+ // cleared once the turn settles, after the ledger entry that takes over is written.
1126
+ startedAt = new Date();
1127
+ await getEscalationReview().updateOne({ _id: review._id }, { $set: { feverPromptStartedAt: startedAt } }, BOOKKEEPING);
1128
+ // No turn ran: the same prompt comes back shortly, under the sweep's attempt cap. A draining
1129
+ // instance refused it before doing anything, so that refusal does not use up an attempt.
1130
+ const rearm = async (why) => {
1131
+ logger.warn('[EscalationReview] The patient prompt ran no turn; trying again shortly', { escalationReviewId: String(review._id), why });
1132
+ const attempts = review.doctorAlertAttempts ?? 0;
1133
+ await settle();
1134
+ await getEscalationReview().updateOne(
1135
+ { _id: review._id, doctorAlertDueAt: null },
1136
+ { $set: { doctorAlertDueAt: new Date(Date.now() + ALERT_RETRY_DELAY_MS), doctorAlertKind: 'patient_prompt', doctorAlertAttempts: why === 'draining' ? Math.max(0, attempts - 1) : attempts } },
1137
+ BOOKKEEPING,
1138
+ );
1139
+ return null;
1140
+ };
1141
+ // The gate runs again under the chat lock, right before the turn: a patient turn queued ahead of
1142
+ // this one can raise the case to stat, pause the bot or bring staff in while the prompt waits.
1143
+ const beforeRun = async () => takenReason(await loadReview(review._id), since, timer, startedAt);
1144
+ try {
1145
+ const result = await getMessaging().processInstruction(review.patientCode, directive, 'developer', { triggeredBy: timer.operator, beforeRun });
1146
+ outcome = result?.outcome ?? null;
1147
+ if (outcome === 'gated') {
1148
+ await settle();
1149
+ await audit(fresh, ALERT_OPERATOR, null, { action: 'patient_prompt_skipped', reason: result.reason });
1150
+ return null;
1151
+ }
1152
+ if (outcome === 'gate_error') return rearm(result.error ?? 'gate_error');
1153
+ if (outcome === null) return rearm('no_turn');
1154
+ // A send that threw ('threw') may still have reached the patient: recorded as possibly delivered,
1155
+ // so it is never sent again this episode.
1156
+ if (!SENT_OUTCOMES.includes(outcome)) error = `the instruction turn was not sent (outcome: ${outcome})`;
1157
+ } catch (sendError) {
1158
+ // processInstruction swallows send errors (they come back as 'threw'), so a throw here means no
1159
+ // send happened: the same prompt comes back under the sweep's attempt cap.
1160
+ return rearm(sendError instanceof DrainingError ? 'draining' : redactedError(sendError));
1161
+ }
1162
+ if (error) logger.error('[EscalationReview] The patient prompt was not sent', { escalationReviewId: String(review._id), error });
1163
+ }
1164
+
1165
+ const sent = { kind: 'patient_prompt', urgencyLevel: level, error, ...(outcome === 'threw' ? { possiblyDelivered: true } : {}), sentAt: now };
1166
+ const updated = await getEscalationReview()
1167
+ .findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
1168
+ if (startedAt) await settle();
1169
+ await audit(updated ?? review, ALERT_OPERATOR, null, { action: 'patient_prompted', delivered: !error, outcome });
1170
+ return updated;
1171
+ }
1172
+
1173
+ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date() } = {}) {
1174
+ const EscalationReview = getEscalationReview();
1175
+ const ours = lease ? { doctorAlertDueAt: lease } : {};
1176
+ const release = (set = { doctorAlertDueAt: null, doctorAlertKind: null, doctorAlertAttempts: 0 }) => EscalationReview
1177
+ .updateOne({ _id: id, ...ours }, { $set: set }, BOOKKEEPING);
1178
+
1179
+ // Stat re-alerts were retired; a review that still holds one lets the slot go without sending.
1180
+ if (kind === 'realert') {
1181
+ await release();
1182
+ return null;
1183
+ }
1184
+ if (kind === 'patient_prompt') return sendPatientPrompt({ id, release, lease, now });
1185
+
1186
+ const review = await loadReview(reviewIdOf(id));
1187
+ if (review.closedAt || !PRE_DECISION_STATUSES.includes(review.status)) {
1188
+ await release();
1189
+ return null;
1190
+ }
1191
+ const urgencyLevel = topUrgencyOf(review);
1192
+ if (!ALERTED_URGENCIES.includes(urgencyLevel)) {
1193
+ await release();
1194
+ return null;
1195
+ }
1196
+ if ((URGENCY_RANK[urgencyLevel] || 0) <= alertedRankOf(review)) {
1197
+ await release();
1198
+ return null;
1199
+ }
1200
+
1201
+ let delivery;
1202
+ try {
1203
+ if (escalationApproverAlertLive()) {
1204
+ const { approver, message } = await prepareDoctorAlert(review, urgencyLevel);
1205
+ const fresh = await loadReview(review._id);
1206
+ if (fresh.closedAt || !PRE_DECISION_STATUSES.includes(fresh.status)) {
1207
+ await release();
1208
+ return null;
1209
+ }
1210
+ delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator: ALERT_OPERATOR })) };
1211
+ } else {
1212
+ // Airtable's notifyEmergency alerts the team; the entry still starts this level's patient timer.
1213
+ delivery = { transport: AIRTABLE_TRANSPORT };
1214
+ }
1215
+ } catch (error) {
1216
+ delivery = { error: redactedError(error) };
1217
+ logger.error('[EscalationReview] The doctor alert was not sent', { escalationReviewId: String(review._id), kind, error: delivery.error });
1218
+ }
1219
+
1220
+ const sent = { kind, urgencyLevel, transport: null, messageId: null, physicianEmail: null, error: null, ...delivery, sentAt: now };
1221
+ const updated = await EscalationReview.findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
1222
+ // A timed case gets the patient timer even when the doctor alert failed: the doctor is retried while
1223
+ // there is time before the prompt and attempts left, then the patient prompt is the safety net.
1224
+ const latestReview = updated ?? review;
1225
+ const since = timerSince(latestReview, urgencyLevel) ?? now;
1226
+ const { timer, gap } = promptedSince(latestReview, since) ? {} : await patientTimerOf(latestReview, urgencyLevel, now);
1227
+ const promptAt = timer ? since.getTime() + timer.ms : null;
1228
+ const retriesDoctor = sent.error
1229
+ && (promptAt == null || (now.getTime() + ALERT_RETRY_DELAY_MS < promptAt && (review.doctorAlertAttempts ?? 0) < MAX_ALERT_ATTEMPTS));
1230
+ if (promptAt != null && !retriesDoctor) {
1231
+ await release({ doctorAlertDueAt: new Date(promptAt), doctorAlertKind: 'patient_prompt', doctorAlertAttempts: 0 });
1232
+ } else if (sent.error) {
1233
+ await release({ doctorAlertDueAt: new Date(Date.now() + ALERT_RETRY_DELAY_MS), doctorAlertKind: 'initial' });
1234
+ } else {
1235
+ await release();
1236
+ }
1237
+ if (urgencyLevel !== 'stat' && !sent.error) {
1238
+ try {
1239
+ const latest = await loadReview(review._id);
1240
+ const topNow = topUrgencyOf(latest);
1241
+ if (URGENCY_RANK[topNow] > (URGENCY_RANK[urgencyLevel] || 0)) await scheduleDoctorAlert(latest, { urgencyLevel: topNow }, new Date());
1242
+ } catch (error) {
1243
+ logger.error('[EscalationReview] Could not check for a more urgent alarm after the alert', { escalationReviewId: String(review._id), error: redactedError(error) });
1244
+ await EscalationReview.updateOne(
1245
+ { _id: review._id, doctorAlertDueAt: null },
1246
+ { $set: { doctorAlertDueAt: new Date(Date.now() + RECHECK_DELAY_MS), doctorAlertKind: 'initial', doctorAlertAttempts: 0 } },
1247
+ BOOKKEEPING,
1248
+ ).catch(() => {});
1249
+ }
1250
+ }
1251
+ await audit(updated ?? review, ALERT_OPERATOR, null, {
1252
+ action: 'doctor_alerted', urgencyLevel, delivered: sent.transport === AIRTABLE_TRANSPORT ? null : !sent.error, transport: sent.transport,
1253
+ });
1254
+ if (gap && !timer) await audit(updated ?? review, ALERT_OPERATOR, null, { action: 'patient_prompt_not_armed', reason: gap });
1255
+ return updated;
1256
+ }
1257
+
1258
+ async function fallbackRecipient() {
1259
+ const phone = String(runtimeConfig.get('ESCALATION_FALLBACK_ALERT_PHONE', '') ?? '').trim();
1260
+ return phone ? { name: null, email: null, phone } : soleApprover();
1261
+ }
1262
+
1263
+ // Who and where for a team alert; a patient record that cannot be read never holds the alert back.
1264
+ async function teamAlertIdentity(review) {
1265
+ let identity = { patientName: '', treatingDoctor: '' };
1266
+ try {
1267
+ identity = doctorIdentity(await getPatientInformation(review.patientCode));
1268
+ } catch (error) {
1269
+ logger.error('[EscalationReview] The patient record could not be read; the team alert goes out without the name', { escalationReviewId: String(review._id), error: redactedError(error) });
1270
+ }
1271
+ return {
1272
+ patient: oneLineOf(identity.patientName) || 'sin nombre registrado',
1273
+ doctor: oneLineOf(identity.treatingDoctor) || 'sin médico registrado',
1274
+ link: conversationLink(review.patientCode) || 'abrir el chat en la plataforma',
1275
+ };
1276
+ }
1277
+
1278
+ async function teamFallbackNotice(review, urgencyLevel, alarmId) {
1279
+ const { patient, doctor, link } = await teamAlertIdentity(review);
1280
+ const alarm = alarmFor(review, urgencyLevel, alarmId);
1281
+ const what = [urgencyLevel.toUpperCase(), oneLineOf(alarm?.symptom), NOT_RECORDED].filter(Boolean).join(' · ');
1282
+ return {
1283
+ body: `⚠️ ${ALERT_MARKS[urgencyLevel]} ${what}\n${patient} (${doctor})\n${link}`,
1284
+ template: { 1: what, 2: patient, 3: doctor, 4: link },
1285
+ };
1286
+ }
1287
+
1288
+ async function alertTeamWithoutEmergencyRow(review, urgencyLevel, alarmId) {
1289
+ try {
1290
+ const result = await sendTeamAlert({ message: await teamFallbackNotice(review, urgencyLevel, alarmId), operator: ALERT_OPERATOR, notice: true });
1291
+ const missed = result.phones.filter((phone) => !phone.delivered).length + (groupConfigured() && !result.group.delivered ? 1 : 0);
1292
+ if (result.delivered && missed) logger.warn('[EscalationReview] The team notice missed some recipients', { escalationReviewId: String(review._id), delivered: result.delivered, missed });
1293
+ return result.delivered ? { transport: 'team' } : null;
1294
+ } catch (error) {
1295
+ logger.error('[EscalationReview] The team notice failed; falling back to one phone', { escalationReviewId: String(review._id), error: redactedError(error) });
1296
+ return null;
1297
+ }
1298
+ }
1299
+
1300
+ async function alertOneWithoutEmergencyRow(review, urgencyLevel, alarmId) {
1301
+ const recipient = await fallbackRecipient();
1302
+ const { approver, message } = await prepareDoctorAlert(review, urgencyLevel, { recipient, alarmId });
1303
+ return { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator: ALERT_OPERATOR })) };
1304
+ }
1305
+
1306
+ async function alertWithoutEmergencyRow({ reviewId, alarmId = null, urgencyLevel, now = new Date() }) {
1307
+ if (escalationApproverAlertLive() || !ALERT_MARKS[urgencyLevel]) return null;
1308
+ let review;
1309
+ let delivery;
1310
+ try {
1311
+ review = await loadReview(reviewIdOf(reviewId));
1312
+ // Airtable alerts the team only once its emergencies row exists; a team notice that reached no one falls back to one phone.
1313
+ delivery = (await teamChannelConfigured() && await alertTeamWithoutEmergencyRow(review, urgencyLevel, alarmId))
1314
+ || await alertOneWithoutEmergencyRow(review, urgencyLevel, alarmId);
1315
+ } catch (error) {
1316
+ delivery = { error: redactedError(error) };
1317
+ logger.error('[EscalationReview] The alert for a missing emergencies row was not sent', { escalationReviewId: String(reviewId), urgencyLevel, error: delivery.error });
1318
+ }
1319
+ if (!review) return null;
1320
+ const sent = { kind: 'fallback', urgencyLevel, transport: null, messageId: null, physicianEmail: null, error: null, ...delivery, sentAt: now };
1321
+ try {
1322
+ const updated = await getEscalationReview().findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
1323
+ await audit(updated ?? review, ALERT_OPERATOR, null, { action: 'emergency_row_fallback_alerted', urgencyLevel, delivered: !sent.error, transport: sent.transport });
1324
+ return updated;
1325
+ } catch (error) {
1326
+ logger.error('[EscalationReview] The fallback alert was not recorded', { escalationReviewId: String(reviewId), error: redactedError(error) });
1327
+ return null;
1328
+ }
1329
+ }
1330
+
1331
+ async function reopenFromFollowUp(review, reason) {
1332
+ const reopened = await getEscalationReview()
1333
+ .findOneAndUpdate({ _id: review._id, status: review.status }, { $set: { status: 'documenting', updatedSinceSeen: true } }, { new: true })
1334
+ .lean();
1335
+ if (!reopened) return review;
1336
+ await audit(reopened, AGENT_OPERATOR, null, { action: 'followup_result', result: reason, statusFrom: review.status });
1337
+ return reopened;
1338
+ }
1339
+
1340
+ const readingOf = (impression) => (['close', 'resolve_episode'].includes(impression.event) ? 'improving' : impression.trajectory);
1341
+
1342
+ async function followUpCasesOf(review, sinceMs) {
1343
+ const decisionNumber = (review.decisions ?? []).length;
1344
+ if (review.followUpCases && review.followUpDecision === decisionNumber) return { review, known: new Set(review.followUpCases) };
1345
+ const caseIdsOfUpdates = (isBefore) => (review.updates ?? [])
1346
+ .filter((entry) => (new Date(entry.at).getTime() <= sinceMs) === isBefore)
1347
+ .flatMap((entry) => (entry.impressions ?? []).map((impression) => impression.caseId).filter(Boolean));
1348
+ let known = [...new Set([...(review.followUpCases ?? []), ...caseIdsOfUpdates(true)])];
1349
+ if (!known.length) known = [...new Set(caseIdsOfUpdates(false))];
1350
+ if (!known.length) return { review, known: new Set() };
1351
+ const stored = await getEscalationReview()
1352
+ .findOneAndUpdate(
1353
+ { _id: review._id, followUpDecision: review.followUpDecision ?? null, decisions: { $size: decisionNumber } },
1354
+ { $set: { followUpCases: known, followUpDecision: decisionNumber } },
1355
+ { new: true },
1356
+ )
1357
+ .lean();
1358
+ if (!stored) return { review, known: new Set() };
1359
+ return { review: stored, known: new Set(known) };
1360
+ }
1361
+
1362
+ async function closeSettled(review) {
1363
+ try {
1364
+ const { review: closed } = await closeEscalationReview({
1365
+ id: String(review._id),
1366
+ closedBy: AGENT_OPERATOR,
1367
+ expectedAlarmCount: (review.alarms ?? []).length,
1368
+ expectedUpdatedAt: review.updatedAt,
1369
+ });
1370
+ await audit(closed, AGENT_OPERATOR, null, { action: 'followup_result', result: 'settled' });
1371
+ return closed;
1372
+ } catch (error) {
1373
+ logger.warn('[EscalationReview] The follow-up settled the case but the review did not close', {
1374
+ escalationReviewId: String(review._id), error: redactedError(error),
1375
+ });
1376
+ return review;
1377
+ }
1378
+ }
1379
+
1380
+ async function settleFollowUp(snapshot, { background = true } = {}) {
1381
+ const since = (snapshot.decisions ?? []).at(-1)?.createdAt;
1382
+ if (!since) return snapshot;
1383
+ const sinceMs = new Date(since).getTime();
1384
+ const { review, known } = await followUpCasesOf(snapshot, sinceMs);
1385
+ if (!known.size) return review;
1386
+
1387
+ const latest = new Map();
1388
+ (review.updates ?? []).filter((entry) => new Date(entry.at).getTime() > sinceMs)
1389
+ .sort((a, b) => new Date(a.at) - new Date(b.at))
1390
+ .forEach((entry) => (entry.impressions ?? [])
1391
+ .filter((impression) => known.has(impression.caseId) && readingOf(impression))
1392
+ .forEach((impression) => latest.set(impression.caseId, readingOf(impression))));
1393
+
1394
+ if ([...latest.values()].includes('worsening')) return reopenFromFollowUp(review, 'worsening');
1395
+ const settled = [...known].every((caseId) => SETTLED_TRAJECTORIES.includes(latest.get(caseId)));
1396
+ if (!settled || !SETTLEABLE_STATUSES.includes(review.status)) {
1397
+ await getEscalationReview().updateOne({ _id: review._id }, { $set: { updatedSinceSeen: true } });
1398
+ return review;
1399
+ }
1400
+ if (!background) return closeSettled(review);
1401
+ void closeSettled(review);
1402
+ return review;
1403
+ }
1404
+
1405
+ // A case the bot handed over by itself is redrafted where it stands, so the doctor can get what the patient said next.
1406
+ function updatesDoctor(review) {
1407
+ if (!escalationAutoHandoffLive() || review.status !== 'awaiting_doctor' || review.doctorHandoffs?.at(-1)?.sentBy !== AUTO_HANDOFF_OPERATOR) return false;
1408
+ const decidedAt = Math.max(0, ...(review.decisions ?? []).map((decision) => new Date(decision.createdAt).getTime()));
1409
+ const botHandoffs = review.doctorHandoffs.filter((handoff) => handoff.sentBy === AUTO_HANDOFF_OPERATOR && new Date(handoff.createdAt).getTime() > decidedAt);
1410
+ return botHandoffs.length <= MAX_DOCTOR_UPDATES;
1411
+ }
1412
+
1413
+ async function generateBotDraft({ id, lease = null } = {}) {
1414
+ const startedAt = new Date();
1415
+ const review = await loadReview(reviewIdOf(id));
1416
+ const updating = updatesDoctor(review);
1417
+ if (review.closedAt || (!DOCUMENTING_STATUSES.includes(review.status) && !updating)) return { review: null, retry: false };
1418
+ const latest = (review.drafts ?? []).at(-1);
1419
+ if (latest && latest.writtenBy !== DRAFT_OPERATOR) return { review: null, retry: false };
1420
+
1421
+ const identity = await readDoctorIdentity(review);
1422
+ if (identity.missing.length) {
1423
+ if (!review.identityBlock) await blockForMissingIdentity({ review, missing: identity.missing, operator: DRAFT_OPERATOR });
1424
+ return { review: null, retry: false };
1425
+ }
1426
+
1427
+ const draft = await generateEscalationDraft({
1428
+ code: review.patientCode,
1429
+ callLogs: review.callLogs ?? [],
1430
+ alarms: review.alarms ?? [],
1431
+ agentCharacterization: characterizationSeedOf(review.updates),
1432
+ heldUrgentFlags: review.drafts?.at(-1)?.urgentUnassessedRedFlags ?? [],
1433
+ reviewId: String(review._id),
1434
+ });
1435
+ if (draft.attempted) {
1436
+ await audit(review, DRAFT_OPERATOR, null, draft.completed
1437
+ ? { action: 'draft_generated', protocolVersion: draft.protocolVersion }
1438
+ : { action: 'draft_generation_failed', reason: redactedError({ message: draft.reason }) });
1439
+ }
1440
+ if (!draft.completed) {
1441
+ logger.warn('[EscalationReview] The automatic draft was not written', { escalationReviewId: String(review._id), reason: draft.reason });
1442
+ return { review: null, retry: draft.configured !== false, rejected: draft.rejected === true };
1443
+ }
1444
+
1445
+ const entry = {
1446
+ snapshotAt: startedAt,
1447
+ doctorText: withIdentity({ identity, review, doctorText: draft.doctorText }),
1448
+ patientMessage: draft.patientMessage,
1449
+ writtenBy: DRAFT_OPERATOR,
1450
+ protocolVersion: draft.protocolVersion,
1451
+ keyQuestions: draft.keyQuestions,
1452
+ unassessedRedFlags: draft.unassessedRedFlags,
1453
+ urgentUnassessedRedFlags: draft.urgentUnassessedRedFlags,
1454
+ unobtainableRedFlags: draft.unobtainableRedFlags,
1455
+ urgentPresentRedFlags: draft.urgentPresentRedFlags,
1456
+ sufficientForDoctor: draft.sufficientForDoctor,
1457
+ blockingQuestion: draft.blockingQuestion,
1458
+ missingCharacterization: draft.missingCharacterization,
1459
+ ...(draft.suggestCall && { suggestCall: draft.suggestCall }),
1460
+ ...(draft.sectionsUnavailable?.length && { sectionsUnavailable: draft.sectionsUnavailable }),
1461
+ };
1462
+ const EscalationReview = getEscalationReview();
1463
+ const saved = await EscalationReview.findOneAndUpdate(
1464
+ {
1465
+ _id: review._id,
1466
+ ...(updating ? { status: 'awaiting_doctor', doctorHandoffs: { $size: review.doctorHandoffs.length } } : { status: { $in: DOCUMENTING_STATUSES } }),
1467
+ draftDueAt: { $lte: lease },
1468
+ drafts: { $size: (review.drafts ?? []).length },
1469
+ },
1470
+ { $push: { drafts: entry }, $set: { status: updating ? 'awaiting_doctor' : 'draft_ready', draftFailedAt: null }, $unset: { identityBlock: '' } },
1471
+ { new: true },
1472
+ ).lean();
1473
+ if (!saved) return { review: null, retry: false };
1474
+ const released = await EscalationReview.updateOne({ _id: review._id, draftDueAt: lease }, { $set: { draftDueAt: null } }, BOOKKEEPING);
1475
+ await audit(saved, DRAFT_OPERATOR, null, { action: 'draft_saved', draftNumber: saved.drafts.length });
1476
+ return { review: released.matchedCount ? { ...saved, draftDueAt: null } : saved, retry: false };
1477
+ }
1478
+
1479
+ async function noteFactsContext(review) {
1480
+ try {
1481
+ return await readContextFacts({ patientId: review.patientCode });
1482
+ } catch (error) {
1483
+ logger.warn('[EscalationReview] The clinical context could not be read for the call note', {
1484
+ escalationReviewId: String(review._id), error: error.message,
1485
+ });
1486
+ return null;
1487
+ }
1488
+ }
1489
+
1490
+ async function proposeNoteFacts(review, operator, requestId) {
1491
+ try {
1492
+ const callLogNumber = review.callLogs.length;
1493
+ const note = review.callLogs[callLogNumber - 1]?.notes;
1494
+ if (!String(note ?? '').trim()) return review;
1495
+
1496
+ const read = await readNoteFacts({
1497
+ note, clinicalContext: await noteFactsContext(review), reviewId: String(review._id),
1498
+ });
1499
+ if (read.attempted) {
1500
+ await audit(review, operator, requestId, read.completed
1501
+ ? { action: 'note_facts_proposed', count: read.facts.length }
1502
+ : { action: 'note_facts_reading_failed', reason: redactedError({ message: read.reason }) });
1503
+ }
1504
+ if (!read.facts.length) return review;
1505
+
1506
+ const proposed = read.facts.map((fact) => ({ ...fact, callLogNumber, state: 'proposed' }));
1507
+ const updated = await getEscalationReview()
1508
+ .findOneAndUpdate({ _id: review._id }, { $push: { noteFacts: { $each: proposed } } }, { new: true })
1509
+ .lean();
1510
+ return updated ?? review;
1511
+ } catch (error) {
1512
+ logger.error('[EscalationReview] The call note could not be read for facts', {
1513
+ escalationReviewId: String(review._id), error: error.message, stack: redactedStack(error),
1514
+ });
1515
+ return review;
1516
+ }
1517
+ }
1518
+
1519
+ // A process that dies between the claim and the settlement leaves its facts in 'settling' with
1520
+ // nothing left to move them. After this long they are offered again: re-storing an assertion the
1521
+ // record already holds merges onto the same claim rather than adding a second one.
1522
+ const SETTLING_TTL_MS = 10 * 60 * 1000;
1523
+
1524
+ function settleable(fact, now) {
1525
+ if (fact.state === 'proposed') return true;
1526
+ if (fact.state !== 'settling') return false;
1527
+ const since = Date.parse(fact.settlingAt ?? '');
1528
+ return !Number.isFinite(since) || now.getTime() - since >= SETTLING_TTL_MS;
1529
+ }
1530
+
1531
+ function factIndexes(values, field) {
1532
+ if (!Array.isArray(values)) throw httpError(400, `${field} must be an array`);
1533
+ const indexes = new Set();
1534
+ for (const value of values) {
1535
+ if (!Number.isInteger(value) || value < 0) throw httpError(400, `${field} must hold whole indexes`);
1536
+ if (indexes.has(value)) throw httpError(400, `${field} names the same fact twice`);
1537
+ indexes.add(value);
1538
+ }
1539
+ return indexes;
1540
+ }
1541
+
1542
+ async function confirmNoteFacts({ id, accepted = [], declined = [], confirmedBy, requestId = null, now = new Date() } = {}) {
1543
+ const reviewId = reviewIdOf(id);
1544
+ const operator = requiredText(confirmedBy, 'confirmedBy');
1545
+ const wanted = factIndexes(accepted, 'accepted');
1546
+ const refused = factIndexes(declined, 'declined');
1547
+ const both = [...wanted].find((index) => refused.has(index));
1548
+ if (both !== undefined) throw httpError(400, 'A fact cannot be accepted and declined at once');
1549
+
1550
+ const review = await loadReview(reviewId);
1551
+ if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
1552
+ const proposed = (review.noteFacts ?? []).map((fact, index) => ({ fact, index }))
1553
+ .filter(({ fact }) => settleable(fact, now));
1554
+ const unknown = [...wanted, ...refused].find((index) => !proposed.some((entry) => entry.index === index));
1555
+ if (unknown !== undefined) throw httpError(409, 'That fact is not waiting to be confirmed');
1556
+ if (!wanted.size && !refused.size) return review;
1557
+
1558
+ // Nothing is final until the record has taken it, declines included: a request that fails
1559
+ // halfway has to leave the whole selection offerable again. The filter names the state each
1560
+ // fact was in when it was read, so a claim that raced another request finds nothing and loses.
1561
+ const claim = { _id: reviewId, status: { $in: DOCUMENTING_STATUSES } };
1562
+ const claimed = {};
1563
+ for (const { fact, index } of proposed.filter((entry) => wanted.has(entry.index) || refused.has(entry.index))) {
1564
+ claim[`noteFacts.${index}.state`] = fact.state;
1565
+ claimed[`noteFacts.${index}.state`] = 'settling';
1566
+ claimed[`noteFacts.${index}.settlingAt`] = now;
1567
+ claimed[`noteFacts.${index}.settledBy`] = operator;
1568
+ }
1569
+ const held = await getEscalationReview().findOneAndUpdate(claim, { $set: claimed }, { new: true }).lean();
1570
+ if (!held) throw httpError(409, 'That fact is not waiting to be confirmed');
1571
+
1572
+ // One fact at a time: storeResources writes sequentially and does not roll back, so a batch that
1573
+ // throws can already have written part of itself. Stored is the only thing we can prove.
1574
+ const stored = new Set();
1575
+ let failure = null;
1576
+ for (const { fact, index } of proposed.filter((entry) => wanted.has(entry.index))) {
1577
+ try {
1578
+ await storeContextFacts({
1579
+ patientId: review.patientCode,
1580
+ assertions: [assertionOf(fact, { patientId: review.patientCode, now })],
1581
+ });
1582
+ stored.add(index);
1583
+ } catch (error) {
1584
+ failure = error;
1585
+ break;
1586
+ }
1587
+ }
1588
+
1589
+ const settledAs = (index) => {
1590
+ if (wanted.has(index)) return stored.has(index) ? 'confirmed' : 'proposed';
1591
+ return failure ? 'proposed' : 'declined';
1592
+ };
1593
+ const settle = {};
1594
+ for (const index of [...wanted, ...refused]) {
1595
+ const state = settledAs(index);
1596
+ settle[`noteFacts.${index}.state`] = state;
1597
+ settle[`noteFacts.${index}.settlingAt`] = null;
1598
+ // A fact handed back never got settled, so it must stop naming the operator who tried.
1599
+ if (state === 'proposed') settle[`noteFacts.${index}.settledBy`] = null;
1600
+ }
1601
+ const updated = await getEscalationReview()
1602
+ .findOneAndUpdate({ _id: reviewId }, { $set: settle }, { new: true }).lean()
1603
+ .catch((error) => {
1604
+ logger.error('[EscalationReview] The note facts were written but could not be settled', {
1605
+ escalationReviewId: String(reviewId), stored: stored.size, error: error.message,
1606
+ });
1607
+ return null;
1608
+ });
1609
+
1610
+ await audit(updated ?? held, operator, requestId, {
1611
+ action: 'note_facts_settled', confirmed: stored.size, declined: failure ? 0 : refused.size,
1612
+ });
1613
+ if (failure) throw failure;
1614
+ return updated ?? held;
1615
+ }
1616
+
1617
+ async function suggestKeyQuestions({ id, requestedBy, requestId = null } = {}) {
1618
+ const reviewId = reviewIdOf(id);
1619
+ const operator = requiredText(requestedBy, 'requestedBy');
1620
+ const review = await loadReview(reviewId);
1621
+ if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
1622
+
1623
+ const latest = (review.drafts ?? []).at(-1);
1624
+ if (latest?.keyQuestions?.length) {
1625
+ return {
1626
+ completed: true,
1627
+ source: 'draft',
1628
+ questions: latest.keyQuestions,
1629
+ redFlags: latest.unassessedRedFlags ?? [],
1630
+ missingCharacterization: latest.missingCharacterization ?? [],
1631
+ suggestCall: latest.suggestCall ?? null,
1632
+ };
1633
+ }
1634
+
1635
+ const generated = await generateKeyQuestions({
1636
+ code: review.patientCode,
1637
+ callLogs: review.callLogs ?? [],
1638
+ reviewId: String(review._id),
1639
+ });
1640
+ if (generated.attempted) {
1641
+ await audit(review, operator, requestId, generated.completed
1642
+ ? { action: 'key_questions_generated' }
1643
+ : { action: 'key_questions_generation_failed', reason: redactedError({ message: generated.reason }) });
1644
+ }
1645
+ if (!generated.completed) throw httpError(generated.configured === false ? 503 : 502, generated.reason);
1646
+
1647
+ const settled = await loadReview(reviewId);
1648
+ if (!DOCUMENTING_STATUSES.includes(settled.status)) throw httpError(409, STATUS_CONFLICT);
1649
+
1650
+ return generated;
1651
+ }
1652
+
1653
+ async function addDraft({ id, doctorText, patientMessage, writtenBy, requestId = null } = {}) {
1654
+ const reviewId = reviewIdOf(id);
1655
+ const operator = requiredText(writtenBy, 'writtenBy');
1656
+ const draft = {
1657
+ doctorText: requiredText(doctorText, 'doctorText'),
1658
+ patientMessage: requiredText(patientMessage, 'patientMessage'),
1659
+ writtenBy: operator,
1660
+ };
1661
+
1662
+ const review = await updateReview(reviewId, DOCUMENTING_STATUSES, { $push: { drafts: draft }, $set: { status: 'draft_ready' } });
1663
+ await audit(review, operator, requestId, { action: 'draft_saved', draftNumber: review.drafts.length });
1664
+ return review;
1665
+ }
1666
+
1667
+ async function soleApprover() {
1668
+ const approvers = await listEscalationApprovers();
1669
+ if (!approvers.length) {
1670
+ throw httpError(409, 'No escalation review approver is configured: tick aprueba_vaiven on a physician with a WhatsApp number');
1671
+ }
1672
+ if (approvers.length > 1) {
1673
+ throw httpError(409, `More than one physician approves escalation reviews; name one of: ${approvers.map((approver) => approver.email).join(', ')}`);
1674
+ }
1675
+ return approvers[0];
1676
+ }
1677
+
1678
+ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, note = null, requestId = null } = {}) {
1679
+ const reviewId = reviewIdOf(id);
1680
+ const operator = requiredText(sentBy, 'sentBy');
1681
+ if (!HANDOFF_MODES.includes(mode)) throw httpError(400, `mode must be one of: ${HANDOFF_MODES.join(', ')}`);
1682
+
1683
+ const review = await loadReview(reviewId);
1684
+ if (!HANDOFF_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
1685
+ const draftNumber = review.drafts.length;
1686
+ if (!draftNumber) throw httpError(409, 'The escalation review has no draft yet');
1687
+ const draft = review.drafts[draftNumber - 1];
1688
+ let approver = null;
1689
+ if (mode === 'sent_whatsapp') {
1690
+ approver = physicianEmail ? await getEscalationApprover(physicianEmail) : await soleApprover();
1691
+ if (!approver) throw httpError(403, 'The physician is not an escalation review approver');
1692
+ }
1693
+
1694
+ const draftedAt = draftTimeOf(draft) ? new Date(draftTimeOf(draft)).getTime() : null;
1695
+ if (draftedAt && (review.alarms ?? []).some((alarm) => new Date(alarm.raisedAt).getTime() > draftedAt)) {
1696
+ throw httpError(409, 'A new alarm arrived after this draft was written; review it and save a new draft before sending it to the doctor');
1697
+ }
1698
+ if (draftedAt && (review.updates ?? []).some((entry) => new Date(entry.at).getTime() > draftedAt)) {
1699
+ throw httpError(409, 'The agent characterized the case after this draft was written; review it and save a new draft before sending it to the doctor');
1700
+ }
1701
+ const identity = await readDoctorIdentity(review);
1702
+ if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
1703
+ const link = doctorLink(review);
1704
+ const message = {
1705
+ body: [note, renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link })].filter(Boolean).join('\n\n'),
1706
+ template: { 1: identity.patientName, 2: identity.treatingDoctor, 3: [templateSummary(review), note].filter(Boolean).join(' · '), 4: link },
1707
+ };
1708
+
1709
+ const patientCaseRecordIds = await reviewCaseIds(review);
1710
+
1711
+ const claim = newOperationClaim();
1712
+ await updateReview(
1713
+ reviewId,
1714
+ [review.status],
1715
+ { $set: { status: 'handing_off', operationClaim: claim } },
1716
+ { drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length }, updatedAt: review.updatedAt },
1717
+ );
1718
+ let delivery = {};
1719
+ let updated;
1720
+ try {
1721
+ if (approver) delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator })) };
1722
+ const sent = delivery.transport === 'template' ? Object.values(message.template).join('\n') : message.body;
1723
+ const handoff = {
1724
+ $push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, alarmCount: (review.alarms ?? []).length, sentBy: operator } },
1725
+ $addToSet: { patientCaseRecordIds: { $each: patientCaseRecordIds } },
1726
+ $unset: { identityBlock: '' },
1727
+ };
1728
+ // With the case Task live, the case's operations status comes from the Task; the clinical status stays clinical.
1729
+ const recordUpdate = caseTaskLive() ? handoff : withCaseMirror({ ...review, patientCaseRecordIds }, handoff, { status: 'en revision_medica' });
1730
+ updated = await completeOperation(reviewId, claim, 'handing_off', recordUpdate, 'awaiting_doctor', handoff);
1731
+ } catch (error) {
1732
+ await releaseReview(reviewId, 'handing_off', review.status, claim);
1733
+ throw error;
1734
+ }
1735
+ await audit(updated, operator, requestId, {
1736
+ action: mode === 'copied' ? 'copied_for_doctor' : 'sent_to_doctor',
1737
+ draftNumber,
1738
+ transport: delivery.transport ?? null,
1739
+ });
1740
+ return syncCase(updated, operator, requestId);
1741
+ }
1742
+
1743
+ async function recordDoctorDecision({
1744
+ id,
1745
+ source,
1746
+ decision,
1747
+ finalText = null,
1748
+ comment = null,
1749
+ doctorName = null,
1750
+ doctorReply = null,
1751
+ reason = null,
1752
+ draftNumber: seenDraftNumber = null,
1753
+ closingCaseIds = null,
1754
+ recordedBy,
1755
+ requestId = null,
1756
+ } = {}) {
1757
+ const reviewId = reviewIdOf(id);
1758
+ const operator = requiredText(recordedBy, 'recordedBy');
1759
+ const closingIds = closingCaseIdsOf(closingCaseIds);
1760
+ const sources = DECISION_SOURCES.filter((entry) => entry !== 'chat');
1761
+ const decisions = DOCTOR_DECISIONS.filter((entry) => entry !== 'direct_chat');
1762
+ if (!sources.includes(source)) throw httpError(400, `source must be one of: ${sources.join(', ')}`);
1763
+ if (!decisions.includes(decision)) throw httpError(400, `decision must be one of: ${decisions.join(', ')}`);
1764
+
1765
+ let decidedBy = operator;
1766
+ let reply = null;
1767
+ if (source === 'registered_by_navigator') {
1768
+ decidedBy = requiredText(doctorName, 'doctorName');
1769
+ reply = requiredText(doctorReply, 'doctorReply');
1770
+ }
1771
+ let returnReason = null;
1772
+ if (decision === 'returned') {
1773
+ if (!RETURN_REASONS.includes(reason)) throw httpError(400, `reason must be one of: ${RETURN_REASONS.join(', ')}`);
1774
+ returnReason = reason;
1775
+ }
1776
+
1777
+ const review = await loadReview(reviewId);
1778
+ const isDraftless = DRAFTLESS_DECISIONS.includes(decision);
1779
+ const allowedStatuses = isDraftless ? [...new Set([...DOCUMENTING_STATUSES, ...DECIDABLE_STATUSES])] : DECIDABLE_STATUSES;
1780
+ if (!allowedStatuses.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
1781
+ const handoff = review.status === 'awaiting_doctor' ? review.doctorHandoffs.at(-1) : null;
1782
+ // The panel shows the latest draft, so a doctor deciding on a bot update not sent yet decides on that one.
1783
+ const onUnsentUpdate = handoff?.sentBy === AUTO_HANDOFF_OPERATOR && Number(seenDraftNumber) === review.drafts.length
1784
+ && review.drafts.at(-1)?.writtenBy === DRAFT_OPERATOR;
1785
+ const draftNumber = onUnsentUpdate ? review.drafts.length : handoff?.draftNumber ?? review.drafts.length;
1786
+ const draft = review.drafts[draftNumber - 1];
1787
+ if (!draft && !isDraftless) throw httpError(409, STATUS_CONFLICT);
1788
+ if (seenDraftNumber !== null && Number(seenDraftNumber) !== draftNumber) throw httpError(409, DRAFT_CHANGED);
1789
+
1790
+ let approvedText = null;
1791
+ if (decision === 'approved') approvedText = draft.patientMessage;
1792
+ if (decision === 'edited_approved') approvedText = requiredText(finalText, 'finalText');
1793
+ // Truthiness, not != null: an empty textarea is a decline with nothing to say.
1794
+ if (decision === 'needs_intervention' && finalText) approvedText = requiredText(finalText, 'finalText');
1795
+
1796
+ if (APPROVALS.includes(decision) && arrivedAfter(review, draftTimeOf(draft))) {
1797
+ if (review.status === 'awaiting_doctor') {
1798
+ const redraft = draft.writtenBy === DRAFT_OPERATOR ? { draftDueAt: new Date(), draftAttempts: 0 } : {};
1799
+ const returned = await updateReview(reviewId, ['awaiting_doctor'], { $set: { status: 'documenting', ...redraft } }, {
1800
+ doctorHandoffs: { $size: review.doctorHandoffs.length },
1801
+ drafts: { $size: review.drafts.length },
1802
+ });
1803
+ await audit(returned, operator, requestId, {
1804
+ action: 'handoff_overtaken', decision, source, draftNumber, ...(reply && { decidedBy, doctorReply: reply }),
1805
+ });
1806
+ throw httpError(409, STALE_HANDOFF);
1807
+ }
1808
+ throw httpError(409, STALE_DRAFT);
1809
+ }
1810
+ const warnings = decision === 'edited_approved' ? draftlessDrugWarnings(approvedText, draft) : [];
1811
+
1812
+ const updated = await updateReview(reviewId, allowedStatuses, {
1813
+ $push: {
1814
+ decisions: {
1815
+ decision,
1816
+ source,
1817
+ draftNumber,
1818
+ finalText: approvedText,
1819
+ comment: optionalText(comment),
1820
+ doctorReply: reply,
1821
+ ...(returnReason && { returnReason }),
1822
+ ...(warnings.length && { warnings }),
1823
+ decidedBy,
1824
+ recordedBy: operator,
1825
+ },
1826
+ },
1827
+ $set: returnReason === 'no_requiere'
1828
+ ? { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: `no_requiere${comment ? `: ${comment}` : ''}`, ...(closingIds && { closingCaseIds: closingIds }) }
1829
+ : { status: statusAfter(decision) },
1830
+ }, { drafts: { $size: review.drafts.length }, alarms: { $size: (review.alarms ?? []).length }, ...latestUpdateGuard(review) });
1831
+ await audit(updated, operator, requestId, {
1832
+ action: 'doctor_decision', decision, source, draftNumber, ...(returnReason && { returnReason }),
1833
+ });
1834
+ if (returnReason === 'no_requiere') {
1835
+ await audit(updated, operator, requestId, { action: 'cancelled', reason: updated.cancellationReason });
1836
+ const { review: cancelled } = await syncCase(await resumeAssistant(updated, operator, requestId), operator, requestId);
1837
+ return cancelled;
1838
+ }
1839
+ return updated;
1840
+ }
1841
+
1842
+ const casesAsRead = (review) => (Array.isArray(review.patientCaseRecordIds)
1843
+ ? { patientCaseRecordIds: review.patientCaseRecordIds }
1844
+ : { patientCaseRecordIds: { $exists: false }, patientCaseRecordId: review.patientCaseRecordId ?? null });
1845
+
1846
+ async function recordDirectIndication({ code, triggeredBy, body, messageId = null, status = null, deferred = false } = {}) {
1847
+ try {
1848
+ const text = String(body ?? '').trim();
1849
+ const operator = String(triggeredBy ?? '').trim();
1850
+ if (!text || !operator) return null;
1851
+ const patientCode = patientCodeOf(code);
1852
+ const EscalationReview = getEscalationReview();
1853
+ const openReview = (only = {}) => EscalationReview
1854
+ .findOne({ patientCode, closedAt: null, status: { $in: DIRECT_CHAT_STATUSES }, ...only })
1855
+ .lean();
1856
+ let review = await openReview();
1857
+ if (!review) return null;
1858
+ if (!await getEscalationApprover(operator)) return null;
1859
+
1860
+ for (let attempt = 1; review && attempt <= DIRECT_CHAT_ATTEMPTS; attempt += 1) {
1861
+ const decisionNumber = (review.decisions ?? []).length + 1;
1862
+ const updated = await EscalationReview.findOneAndUpdate(
1863
+ { _id: review._id, status: review.status, closedAt: null, ...casesAsRead(review) },
1864
+ withCaseMirror(review, {
1865
+ $push: {
1866
+ decisions: {
1867
+ decision: 'direct_chat',
1868
+ source: 'chat',
1869
+ draftNumber: (review.drafts ?? []).length,
1870
+ finalText: text,
1871
+ decidedBy: operator,
1872
+ recordedBy: operator,
1873
+ },
1874
+ },
1875
+ $set: {
1876
+ status: deferred ? 'indications_queued' : 'indications_sent',
1877
+ patientDelivery: {
1878
+ decisionNumber,
1879
+ messageId,
1880
+ status: optionalText(status),
1881
+ transport: deferred ? 'template_recovery' : 'text',
1882
+ deferred: Boolean(deferred),
1883
+ sentBy: operator,
1884
+ },
1885
+ },
1886
+ }, { recommendation: text.slice(0, MAX_NOTE_LENGTH) }),
1887
+ { new: true },
1888
+ ).lean();
1889
+ if (updated) {
1890
+ await audit(updated, operator, null, { action: 'direct_chat_resolved', decisionNumber, statusFrom: review.status });
1891
+ const { review: synced } = await syncCase(updated, operator, null);
1892
+ return synced;
1893
+ }
1894
+ if (attempt < DIRECT_CHAT_ATTEMPTS) review = await openReview({ _id: review._id });
1895
+ }
1896
+ return null;
1897
+ } catch (error) {
1898
+ logger.error('[EscalationReview] An approver message could not resolve the open review', {
1899
+ error: redactedError(error), stack: redactedStack(error),
1900
+ });
1901
+ return null;
1902
+ }
1903
+ }
1904
+
1905
+ const latestUpdateGuard = (review) => {
1906
+ const updates = review.updates ?? [];
1907
+ if (!updates.length) return { 'updates.0': { $exists: false } };
1908
+ return { updates: { $size: updates.length }, [`updates.${updates.length - 1}.turnId`]: updates.at(-1).turnId };
1909
+ };
1910
+
1911
+ const draftTimeOf = (draft) => draft.snapshotAt ?? draft.createdAt;
1912
+
1913
+ const arrivedAfter = (review, since) => Boolean(since) && [
1914
+ ...(review.alarms ?? []).map((alarm) => alarm.raisedAt),
1915
+ ...(review.updates ?? []).map((update) => update.at),
1916
+ ].some((at) => at && new Date(at) > new Date(since));
1917
+
1918
+ const draftlessDrugWarnings = (text, draft) => {
1919
+ const drafted = new Set(drugsNamedIn(`${draft.doctorText} ${draft.patientMessage}`));
1920
+ return drugsNamedIn(text).filter((drug) => !drafted.has(drug)).map((drug) => `el texto editado menciona ${drug}, que no estaba en el borrador`);
1921
+ };
1922
+
1923
+ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy, requestId = null } = {}) {
1924
+ const reviewId = reviewIdOf(id);
1925
+ const operator = requiredText(sentBy, 'sentBy');
1926
+ if (outsideWindowRoute !== null && !OUTSIDE_WINDOW_ROUTES.includes(outsideWindowRoute)) {
1927
+ throw httpError(400, `outsideWindowRoute must be one of: ${OUTSIDE_WINDOW_ROUTES.join(', ')}`);
1928
+ }
1929
+
1930
+ const claim = newOperationClaim();
1931
+ const claimed = await updateReview(reviewId, SENDABLE_STATUSES, { $set: { status: 'sending', operationClaim: claim } });
1932
+ const decisionNumber = claimed.decisions.length;
1933
+ const { finalText, decision } = claimed.decisions[decisionNumber - 1];
1934
+ const claimedFrom = statusAfter(decision);
1935
+
1936
+ if (!finalText) {
1937
+ await releaseReview(reviewId, 'sending', claimedFrom, claim).catch((releaseError) => {
1938
+ logger.error('[EscalationReview] The claim was not released after a decision with no text', {
1939
+ escalationReviewId: String(claimed._id), error: releaseError.message,
1940
+ });
1941
+ });
1942
+ throw httpError(409, 'This decision carries no approved text to send to the patient');
1943
+ }
1944
+
1945
+ const decidedAt = claimed.decisions[decisionNumber - 1].createdAt;
1946
+ if (decidedAt && (claimed.updates ?? []).some((entry) => new Date(entry.at) > new Date(decidedAt))) {
1947
+ await releaseReview(reviewId, 'sending', 'documenting', claim).catch((releaseError) => {
1948
+ logger.error('[EscalationReview] The claim was not released after a decision new information overtook', {
1949
+ escalationReviewId: String(claimed._id), error: releaseError.message,
1950
+ });
1951
+ });
1952
+ throw httpError(409, 'The agent characterized the case after this decision; it went back to documenting for a new draft and decision');
1953
+ }
1954
+
1955
+ // Built outside the try: composing reads Mongo and Airtable, and failing there never sent.
1956
+ let message;
1957
+ try {
1958
+ message = await patientIndicationsMessage({ review: claimed, finalText, outsideWindowRoute, operator });
1959
+ } catch (error) {
1960
+ await releaseReview(reviewId, 'sending', claimedFrom, claim).catch((releaseError) => {
1961
+ logger.error('[EscalationReview] The claim was not released after a send that never started', {
1962
+ escalationReviewId: String(claimed._id), error: releaseError.message,
1963
+ });
1964
+ });
1965
+ throw error;
1966
+ }
1967
+
1968
+ let result;
1969
+ try {
1970
+ result = await getMessaging().sendMessage(message);
1971
+ const alreadyDelivered = result?.status === 'duplicate_suppressed' && result?.completed === true;
1972
+ if (!result?.success && !alreadyDelivered) {
1973
+ throw httpError(502, 'The indications could not be sent to the patient');
1974
+ }
1975
+ } catch (error) {
1976
+ if (!sendDidNotHappen(error)) {
1977
+ logger.error('[EscalationReview] Patient send outcome is unknown; leaving the review in sending', {
1978
+ escalationReviewId: String(claimed._id),
1979
+ error: redactedError(error),
1980
+ });
1981
+ throw httpError(502, 'The patient send could not be confirmed; check the chat before sending again');
1982
+ }
1983
+ await releaseReview(reviewId, 'sending', claimedFrom, claim).catch((releaseError) => {
1984
+ logger.error('[EscalationReview] The claim was not released after a confirmed non-send', {
1985
+ escalationReviewId: String(claimed._id), error: releaseError.message,
1986
+ });
1987
+ });
1988
+ throw error;
1989
+ }
1990
+
1991
+ const deferred = result.deferred === true;
1992
+ const delivery = {
1993
+ decisionNumber,
1994
+ messageId: result.messageId || null,
1995
+ status: result.status || null,
1996
+ transport: deliveryTransport(message, result),
1997
+ deferred,
1998
+ sentBy: operator,
1999
+ };
2000
+ const status = deferred ? 'indications_queued' : 'indications_sent';
2001
+ const recordUpdate = withCaseMirror(claimed, {
2002
+ $set: { patientDelivery: delivery },
2003
+ }, { recommendation: finalText });
2004
+ const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status);
2005
+ await audit(review, operator, requestId, { action: status, decisionNumber, transport: delivery.transport });
2006
+ return syncCase(review, operator, requestId);
2007
+ }
2008
+
2009
+ const EPISODE_TRUST = 0.7;
2010
+ const EPISODE_VARIABLE = 'intercurrent_events_summary';
2011
+ const EPISODE_SOURCE = 'doctor';
2012
+
2013
+ const DECISION_WORDS = {
2014
+ approved: 'el médico aprobó las indicaciones',
2015
+ edited_approved: 'el médico aprobó las indicaciones con cambios',
2016
+ needs_intervention: 'el médico pidió valoración presencial',
2017
+ returned: 'el médico devolvió el caso a navegación',
2018
+ };
2019
+
2020
+ function episodeFact(review, now) {
2021
+ const alarm = review.alarms?.[review.alarms.length - 1];
2022
+ const named = inlineOf(alarm?.suspectedCondition) || inlineOf(alarm?.symptom);
2023
+ if (!named) return null;
2024
+
2025
+ const raisedAt = new Date(alarm?.raisedAt ?? review.createdAt ?? now);
2026
+ // The record files list-like variables by concept, so the day keeps two episodes apart.
2027
+ const concept = `${named} (${isoDay(raisedAt.toISOString())})`;
2028
+
2029
+ const handedOffAt = review.doctorHandoffs?.[review.doctorHandoffs.length - 1]?.createdAt ?? null;
2030
+ const decided = handedOffAt && raisedAt.getTime() <= new Date(handedOffAt).getTime()
2031
+ ? review.decisions?.[review.decisions.length - 1]
2032
+ : null;
2033
+
2034
+ const delivery = decided ? review.patientDelivery : null;
2035
+ const said = [
2036
+ inlineOf(alarm?.symptom) || named,
2037
+ DECISION_WORDS[decided?.decision],
2038
+ delivery?.confirmedAt || delivery?.deferred === false ? 'se le enviaron indicaciones' : null,
2039
+ ].filter(Boolean);
2040
+
2041
+ return {
2042
+ patientId: review.patientCode,
2043
+ variableId: EPISODE_VARIABLE,
2044
+ concept,
2045
+ value: said.join('. '),
2046
+ source: EPISODE_SOURCE,
2047
+ trust: EPISODE_TRUST,
2048
+ validTime: raisedAt.toISOString(),
2049
+ recordTime: new Date(now).toISOString(),
2050
+ };
2051
+ }
2052
+
2053
+ async function recordEpisode(review, now = new Date()) {
2054
+ try {
2055
+ const assertion = episodeFact(review, now);
2056
+ if (!assertion) return;
2057
+ await storeContextFacts({ patientId: review.patientCode, assertions: [assertion] });
2058
+ } catch (error) {
2059
+ logger.error('[EscalationReview] The episode did not reach the clinical record', {
2060
+ escalationReviewId: String(review._id), error: error.message, stack: redactedStack(error),
2061
+ });
2062
+ }
2063
+ }
2064
+
2065
+ async function closeEscalationReview({
2066
+ id, closedBy, deliveryConfirmed = false, interruptionNotes = null, closingCaseIds = null, requestId = null, expectedAlarmCount = null, expectedUpdatedAt = null,
2067
+ } = {}) {
2068
+ const reviewId = reviewIdOf(id);
2069
+ const operator = requiredText(closedBy, 'closedBy');
2070
+ const closingIds = closingCaseIdsOf(closingCaseIds);
2071
+
2072
+ const current = await loadReview(reviewId);
2073
+ const queued = current.status === 'indications_queued';
2074
+ if (queued && deliveryConfirmed !== true) {
2075
+ throw httpError(409, 'The indications are still queued; confirm the patient received them before closing');
2076
+ }
2077
+ const interrupted = INTERRUPTED_STATUSES.includes(current.status);
2078
+ const notes = String(interruptionNotes ?? '').trim();
2079
+ if (interrupted) {
2080
+ if (!notes) throw httpError(409, INTERRUPTION_CONFLICT);
2081
+ const sinceStatusChanged = Date.now() - new Date(current.updatedAt ?? current.createdAt ?? 0).getTime();
2082
+ if (sinceStatusChanged < INTERRUPTION_GRACE_MS) throw httpError(409, INTERRUPTION_TOO_SOON);
2083
+ }
2084
+
2085
+ const closure = { status: 'closed', closedBy: operator, closedAt: new Date(), ...(closingIds && { closingCaseIds: closingIds }) };
2086
+ if (queued) Object.assign(closure, { 'patientDelivery.confirmedBy': operator, 'patientDelivery.confirmedAt': new Date() });
2087
+ if (interrupted) closure.interruptionResolution = { fromStatus: current.status, notes };
2088
+
2089
+ const review = await updateReview(
2090
+ reviewId,
2091
+ interrupted ? [current.status] : CLOSABLE_STATUSES,
2092
+ { $set: closure },
2093
+ {
2094
+ ...(interrupted ? { operationClaim: current.operationClaim ?? null } : {}),
2095
+ ...(expectedAlarmCount === null ? {} : { alarms: { $size: expectedAlarmCount } }),
2096
+ ...(expectedUpdatedAt === null ? {} : { updatedAt: expectedUpdatedAt }),
2097
+ },
2098
+ );
2099
+ const closeChanges = { action: interrupted ? 'closed_from_interruption' : 'closed' };
2100
+ if (interrupted) closeChanges.fromStatus = current.status;
2101
+ if (queued) closeChanges.deliveryConfirmed = true;
2102
+ try {
2103
+ await audit(review, operator, requestId, closeChanges);
2104
+ } catch (error) {
2105
+ logger.error('[EscalationReview] The review closed but its audit entry was not written', {
2106
+ escalationReviewId: String(review._id), error: redactedError(error), stack: redactedStack(error),
2107
+ });
2108
+ }
2109
+ await recordEpisode(review);
2110
+ return syncCase(await resumeAssistant(review, operator, requestId), operator, requestId);
2111
+ }
2112
+
2113
+ async function reclassifyUrgency({ id, urgencyLevel, reason, reclassifiedBy, requestId = null } = {}) {
2114
+ const reviewId = reviewIdOf(id);
2115
+ const operator = requiredText(reclassifiedBy, 'reclassifiedBy');
2116
+ if (!URGENCY_LEVELS.includes(urgencyLevel)) throw httpError(400, `urgencyLevel must be one of: ${URGENCY_LEVELS.join(', ')}`);
2117
+ const why = requiredText(reason, 'reason');
2118
+
2119
+ const current = await loadReview(reviewId);
2120
+ const fromLevel = effectiveUrgencyOf(current)?.urgency;
2121
+ if (!fromLevel) throw httpError(409, STATUS_CONFLICT);
2122
+ if (fromLevel === urgencyLevel) throw httpError(409, SAME_URGENCY);
2123
+
2124
+ const entry = { fromLevel, toLevel: urgencyLevel, reason: why, reclassifiedBy: operator, at: new Date() };
2125
+ let review;
2126
+ try {
2127
+ review = await updateReview(reviewId, RECLASSIFIABLE_STATUSES, { $push: { urgencyReclassifications: entry } }, {
2128
+ alarms: { $size: (current.alarms ?? []).length },
2129
+ urgencyReclassifications: { $size: (current.urgencyReclassifications ?? []).length },
2130
+ });
2131
+ } catch (error) {
2132
+ if (error?.statusCode === 409 && RECLASSIFIABLE_STATUSES.includes(current.status)) throw httpError(409, RECLASSIFY_CHANGED);
2133
+ throw error;
2134
+ }
2135
+ await audit(review, operator, requestId, { action: 'urgency_reclassified', fromLevel, toLevel: urgencyLevel, reason: why });
2136
+ return { review, responseDeadline: responseDeadlineOf(review, responseDeadlinePolicy()) };
2137
+ }
2138
+
2139
+ async function cancelEscalationReview({ id, cancelledBy, reason = null, closingCaseIds = null, requestId = null } = {}) {
2140
+ const reviewId = reviewIdOf(id);
2141
+ const operator = requiredText(cancelledBy, 'cancelledBy');
2142
+ const closingIds = closingCaseIdsOf(closingCaseIds);
2143
+ if (reason != null && typeof reason !== 'string') throw httpError(400, 'reason must be text');
2144
+ const notes = String(reason ?? '').trim() || null;
2145
+
2146
+ const allowed = notes
2147
+ ? CANCELLABLE_STATUSES
2148
+ : CANCELLABLE_STATUSES.filter((status) => !CANCELLABLE_AFTER_HANDOFF_STATUSES.includes(status));
2149
+
2150
+ let review;
2151
+ try {
2152
+ review = await updateReview(reviewId, allowed, {
2153
+ $set: { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: notes, ...(closingIds && { closingCaseIds: closingIds }) },
2154
+ }, notes ? {} : { 'doctorHandoffs.0': { $exists: false }, 'decisions.0': { $exists: false } });
2155
+ } catch (error) {
2156
+ if (error?.statusCode !== 409 || notes) throw error;
2157
+ const current = await loadReview(reviewId);
2158
+ const doctorInvolved = Boolean(current.doctorHandoffs?.length || current.decisions?.length);
2159
+ if (doctorInvolved || CANCELLABLE_AFTER_HANDOFF_STATUSES.includes(current.status)) throw httpError(409, CANCEL_NEEDS_REASON);
2160
+ throw error;
2161
+ }
2162
+
2163
+ await audit(review, operator, requestId, { action: 'cancelled', reason: notes });
2164
+ return syncCase(await resumeAssistant(review, operator, requestId), operator, requestId);
2165
+ }
2166
+
2167
+ async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {}) {
2168
+ const reviewId = reviewIdOf(id);
2169
+ const operator = requiredText(syncedBy, 'syncedBy');
2170
+ if (caseTaskLive()) await scheduleCaseSync(reviewId);
2171
+ return syncCase(await loadReview(reviewId), operator, requestId);
2172
+ }
2173
+
2174
+ module.exports = {
2175
+ BOOKKEEPING,
2176
+ AUTO_HANDOFF_OPERATOR,
2177
+ DOCUMENTING_STATUSES,
2178
+ DRAFT_OPERATOR,
2179
+ MAX_DOCTOR_UPDATES,
2180
+ FEVER_CATEGORY,
2181
+ appliedLevelOf,
2182
+ MAX_ALERT_ATTEMPTS,
2183
+ PRE_DECISION_STATUSES,
2184
+ _resetEscalationReviewIndexes,
2185
+ addCallLog,
2186
+ caseTakenReason,
2187
+ currentAlarms,
2188
+ teamAlertIdentity,
2189
+ addDraft,
2190
+ alertWithoutEmergencyRow,
2191
+ attachEmergencyRow,
2192
+ cancelEscalationReview,
2193
+ closeEscalationReview,
2194
+ escalationAnchorOf,
2195
+ generateBotDraft,
2196
+ getEscalationReviewById,
2197
+ getReviewTimeline,
2198
+ handOffToDoctor,
2199
+ listEscalationReviews,
2200
+ openEscalationReview,
2201
+ reclassifyUrgency,
2202
+ recordEscalationAlarm,
2203
+ recordDirectIndication,
2204
+ recordDoctorDecision,
2205
+ sendScheduledDoctorAlert,
2206
+ recordReviewUpdate,
2207
+ requestBotDraft,
2208
+ sendApprovedIndications,
2209
+ setReviewCases,
2210
+ suggestDraft,
2211
+ suggestKeyQuestions,
2212
+ confirmNoteFacts,
2213
+ syncEscalationReviewCase,
2214
+ };