@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.
- package/README.md +104 -0
- package/lib/adapters/BaileysProvider.js +8 -37
- package/lib/adapters/MessageAdapter.js +3 -1
- package/lib/adapters/MessageProvider.js +0 -11
- package/lib/adapters/TwilioProvider.js +44 -77
- package/lib/clinical/AssistantProcessor.js +414 -19
- package/lib/clinical/assistants/BaseAssistant.js +0 -15
- package/lib/clinical/config/checkInConfig.js +3 -0
- package/lib/clinical/config/cohortConfig.js +3 -3
- package/lib/clinical/config/composerConfig.js +42 -0
- package/lib/clinical/config/divergenceConfig.js +80 -50
- package/lib/clinical/config/llmConfig.js +11 -2
- package/lib/clinical/config/safetyNetConfig.js +108 -0
- package/lib/clinical/config/subAgentsConfig.js +61 -2
- package/lib/clinical/context/ToolRuntimeContext.js +121 -6
- package/lib/clinical/context/turnContext.js +50 -0
- package/lib/clinical/flags/bridgeConfig.js +31 -0
- package/lib/clinical/flags/clinicalContextFlags.js +46 -0
- package/lib/clinical/flags/composerFlags.js +14 -0
- package/lib/clinical/flags/contingencyFlags.js +19 -0
- package/lib/clinical/flags/escalationFlags.js +43 -0
- package/lib/clinical/flags/flagSnapshot.js +58 -0
- package/lib/clinical/flags/inboundRecoveryFlags.js +17 -0
- package/lib/clinical/flags/llmAuditConfig.js +7 -0
- package/lib/clinical/flags/llmMonitorConfig.js +18 -0
- package/lib/clinical/flags/patternConsultFlags.js +10 -0
- package/lib/clinical/flags/recommendationRecoveryFlags.js +9 -0
- package/lib/clinical/flags/supportLightFlags.js +7 -0
- package/lib/clinical/flags/triageRecommendationFlags.js +16 -0
- package/lib/clinical/flags/turnEfficiencyFlags.js +19 -0
- package/lib/clinical/helpers/auditReasoningHelper.js +30 -0
- package/lib/clinical/helpers/carePlanInterventionDerivation.js +76 -0
- package/lib/clinical/helpers/carePlanValidationHelper.js +62 -0
- package/lib/clinical/helpers/ceilingGapHelper.js +21 -0
- package/lib/clinical/helpers/chemoContextHelper.js +217 -0
- package/lib/clinical/helpers/clinicalContextHelper.js +162 -0
- package/lib/clinical/helpers/clinicalFactsHelper.js +45 -4
- package/lib/clinical/helpers/clinicalMentionHelper.js +16 -13
- package/lib/clinical/helpers/clinicalProfileHelper.js +60 -0
- package/lib/clinical/helpers/clinicalWorkflowGuard.js +175 -0
- package/lib/clinical/helpers/cohortHelper.js +3 -1
- package/lib/clinical/helpers/contextMirrorHelper.js +68 -0
- package/lib/clinical/helpers/dateAnchorHelper.js +18 -0
- package/lib/clinical/helpers/doctorReviewMessageHelper.js +152 -0
- package/lib/clinical/helpers/drugIdentityHelper.js +67 -0
- package/lib/clinical/helpers/encodedPairHelper.js +12 -0
- package/lib/clinical/helpers/evidenceAnchorHelper.js +70 -0
- package/lib/clinical/helpers/factAssertionHelper.js +300 -0
- package/lib/clinical/helpers/gradeEstimateHelper.js +148 -0
- package/lib/clinical/helpers/hospitalizationContextHelper.js +8 -0
- package/lib/clinical/helpers/legacyContextHelper.js +122 -0
- package/lib/clinical/helpers/legacyRecommendationFormatHelper.js +107 -0
- package/lib/clinical/helpers/llmsHelper.js +170 -87
- package/lib/clinical/helpers/managedSymptomProjectionHelper.js +23 -0
- package/lib/clinical/helpers/medicationNamingRule.js +5 -0
- package/lib/clinical/helpers/palliativeAssessmentHelper.js +62 -0
- package/lib/clinical/helpers/palliativeCarePlanHelper.js +68 -0
- package/lib/clinical/helpers/recommendationGateHelper.js +208 -0
- package/lib/clinical/helpers/recommendationPlanHelper.js +104 -0
- package/lib/clinical/helpers/resultsHelper.js +56 -0
- package/lib/clinical/helpers/reviewUpdateHelper.js +68 -0
- package/lib/clinical/helpers/shadowHelper.js +1 -13
- package/lib/clinical/helpers/skillActivationHelper.js +53 -0
- package/lib/clinical/helpers/structuredTextHelper.js +13 -0
- package/lib/clinical/helpers/toolResultHelper.js +35 -0
- package/lib/clinical/helpers/triageCaseBaseHelper.js +483 -0
- package/lib/clinical/helpers/triageResultMessageHelper.js +30 -0
- package/lib/clinical/helpers/triageRetriggerHelper.js +85 -0
- package/lib/clinical/helpers/triageSymptomsHelper.js +33 -0
- package/lib/clinical/index.js +4 -0
- package/lib/clinical/memory/DefaultMemoryManager.js +211 -39
- package/lib/clinical/memory/EnhancedMemoryManager.js +14 -8
- package/lib/clinical/models/llmCallModel.js +19 -0
- package/lib/clinical/models/llmMonitorCheckpointModel.js +20 -0
- package/lib/clinical/models/llmMonitorEvaluationModel.js +56 -0
- package/lib/clinical/models/patternConsultModel.js +37 -0
- package/lib/clinical/models/riskWarmupEventModel.js +23 -0
- package/lib/clinical/models/supportCandidateModel.js +90 -0
- package/lib/clinical/models/supportLightModel.js +95 -0
- package/lib/clinical/models/triageRecommendationEventModel.js +110 -0
- package/lib/clinical/models/turnTraceModel.js +24 -7
- package/lib/clinical/monitoring/AirtableMonitorSink.js +488 -0
- package/lib/clinical/monitoring/LlmMonitorService.js +558 -0
- package/lib/clinical/monitoring/contingencyMonitorSpec.js +601 -0
- package/lib/clinical/promptPlacement.js +5 -0
- package/lib/clinical/protocols/treatmentFormulary.js +387 -0
- package/lib/clinical/providers/AnthropicProvider.js +459 -31
- package/lib/clinical/providers/BaseLLMProvider.js +689 -52
- package/lib/clinical/providers/GatewayProvider.js +14 -4
- package/lib/clinical/providers/OpenAIResponsesProvider.js +73 -11
- package/lib/clinical/providers/OpenAIResponsesProviderTools.js +24 -9
- package/lib/clinical/providers/OpenRouterProvider.js +9 -2
- package/lib/clinical/services/assistantService.js +51 -7
- package/lib/clinical/services/bridgeService.js +93 -0
- package/lib/clinical/services/checkInDueService.js +134 -0
- package/lib/clinical/services/clinicalAirtableService.js +752 -0
- package/lib/clinical/services/clinicalContextReadService.js +47 -0
- package/lib/clinical/services/clinicalExtractionService.js +156 -23
- package/lib/clinical/services/composerService.js +78 -0
- package/lib/clinical/services/conceptVerifierService.js +127 -0
- package/lib/clinical/services/conditionCloseService.js +138 -0
- package/lib/clinical/services/contextCleanupService.js +85 -0
- package/lib/clinical/services/contextMirrorService.js +72 -0
- package/lib/clinical/services/contextSyncRunner.js +20 -0
- package/lib/clinical/services/contextSyncService.js +258 -0
- package/lib/clinical/services/contingencyDispatchService.js +496 -0
- package/lib/clinical/services/ctcaeLadderService.js +70 -0
- package/lib/clinical/services/ctcaeTermService.js +44 -0
- package/lib/clinical/services/currentRegimenService.js +60 -0
- package/lib/clinical/services/deliverySettlementService.js +39 -0
- package/lib/clinical/services/deniedSymptomBoundaryService.js +218 -0
- package/lib/clinical/services/dispatcherService.js +142 -0
- package/lib/clinical/services/escalationDraftService.js +229 -0
- package/lib/clinical/services/escalationNoteFactsService.js +131 -0
- package/lib/clinical/services/escalationQuestionsService.js +131 -0
- package/lib/clinical/services/gradeAnchorService.js +85 -0
- package/lib/clinical/services/gradeClaimService.js +73 -0
- package/lib/clinical/services/gradeSourceService.js +138 -0
- package/lib/clinical/services/impressionValidationService.js +19 -0
- package/lib/clinical/services/legacyContextSyncService.js +255 -0
- package/lib/clinical/services/llmAuditService.js +23 -0
- package/lib/clinical/services/nutritionPlanService.js +97 -0
- package/lib/clinical/services/outreachCarrierService.js +88 -0
- package/lib/clinical/services/outreachSweepRunner.js +8 -0
- package/lib/clinical/services/outreachSweepService.js +644 -0
- package/lib/clinical/services/patientHistoryService.js +203 -0
- package/lib/clinical/services/patientIdentityService.js +43 -0
- package/lib/clinical/services/patientProfileService.js +145 -0
- package/lib/clinical/services/patternConsultService.js +127 -0
- package/lib/clinical/services/pausedSafetyNetService.js +387 -0
- package/lib/clinical/services/promptComposerService.js +74 -21
- package/lib/clinical/services/radiotherapyContextService.js +40 -0
- package/lib/clinical/services/radiotherapyPhaseService.js +272 -0
- package/lib/clinical/services/recommendationRankService.js +180 -0
- package/lib/clinical/services/recommendationRecoveryService.js +241 -0
- package/lib/clinical/services/recommendationValidationService.js +206 -0
- package/lib/clinical/services/regimenCloserService.js +205 -0
- package/lib/clinical/services/reminderDispatchService.js +36 -0
- package/lib/clinical/services/riskAssessmentService.js +469 -0
- package/lib/clinical/services/riskHeadlineService.js +56 -0
- package/lib/clinical/services/safetyNetPledgeService.js +231 -0
- package/lib/clinical/services/shadowMessageService.js +30 -12
- package/lib/clinical/services/shadowService.js +8 -4
- package/lib/clinical/services/skillService.js +117 -0
- package/lib/clinical/services/supportActionService.js +122 -0
- package/lib/clinical/services/supportCandidateService.js +607 -0
- package/lib/clinical/services/supportInvitability.js +86 -0
- package/lib/clinical/services/supportLightEvaluationService.js +231 -0
- package/lib/clinical/services/supportLightService.js +277 -0
- package/lib/clinical/services/supportRoutingAgentService.js +118 -0
- package/lib/clinical/services/symptomLandscapeService.js +153 -0
- package/lib/clinical/services/treatmentProposalService.js +136 -0
- package/lib/clinical/services/triageRecommendationService.js +1226 -0
- package/lib/clinical/services/turnRiskBriefService.js +217 -0
- package/lib/clinical/services/writeClaimStore.js +126 -0
- package/lib/clinical/stores/CtcaeCatalog.js +21 -0
- package/lib/clinical/tools/analyzeSymptomPatternsTool.js +276 -0
- package/lib/clinical/tools/deliverPatientMessageTool.js +294 -0
- package/lib/clinical/tools/extractClinicalInfoTool.js +252 -37
- package/lib/clinical/tools/getActiveRecommendationsTool.js +44 -0
- package/lib/clinical/tools/getActiveSymptomLandscapeTool.js +37 -0
- package/lib/clinical/tools/getPatientHistoryTool.js +45 -0
- package/lib/clinical/tools/getPatientRiskAssessmentTool.js +66 -0
- package/lib/clinical/tools/getRouterContextBundleTool.js +136 -0
- package/lib/clinical/tools/lookupCtcaeEntryTool.js +36 -0
- package/lib/clinical/tools/openClusterHypothesisTool.js +175 -0
- package/lib/clinical/tools/openConditionTool.js +198 -0
- package/lib/clinical/tools/recordClinicalImpressionTool.js +394 -0
- package/lib/clinical/tools/recordInterventionTool.js +138 -0
- package/lib/clinical/tools/recordRecommendationOutcomeTool.js +72 -0
- package/lib/clinical/tools/registerClinicalTools.js +51 -6
- package/lib/clinical/tools/reportCrisisTool.js +193 -0
- package/lib/clinical/tools/reportMedicalEscalationTool.js +471 -0
- package/lib/clinical/tools/reportResultsReceivedTool.js +176 -0
- package/lib/clinical/tools/reportUnresolvedRequestv2Tool.js +164 -0
- package/lib/clinical/tools/requestPatternConsultTool.js +70 -0
- package/lib/clinical/tools/schedulePatientReminderTool.js +292 -0
- package/lib/clinical/tools/sendBridgeMessageTool.js +33 -0
- package/lib/clinical/tools/setContingencyPlanTool.js +332 -0
- package/lib/clinical/tools/skillTool.js +81 -0
- package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
- package/lib/clinical/tools/submitOutreachDecisionTool.js +139 -0
- package/lib/clinical/tools/submitPalliativeAssessmentTool.js +75 -0
- package/lib/clinical/tools/submitPalliativeCarePlanTool.js +101 -0
- package/lib/clinical/tools/submitRecommendationPlanTool.js +145 -0
- package/lib/clinical/tools/submitRoutingDecisionTool.js +466 -0
- package/lib/clinical/tools/submitSafetyGateTool.js +130 -0
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +149 -0
- package/lib/clinical/tools/updateClusterHypothesisTool.js +178 -0
- package/lib/clinical/tools/updateConditionStatusTool.js +192 -0
- package/lib/clinical/tools/updatePalliativeAssessmentTool.js +78 -0
- package/lib/config/airtableArchiveConfig.js +177 -0
- package/lib/config/airtableConfig.js +24 -1
- package/lib/config/instructionConfig.js +5 -0
- package/lib/config/lifecycle.js +36 -1
- package/lib/config/programConfig.js +20 -0
- package/lib/controllers/assistantController.js +67 -11
- package/lib/controllers/contextSyncController.js +30 -0
- package/lib/controllers/contingencyController.js +28 -0
- package/lib/controllers/conversationController.js +7 -7
- package/lib/controllers/dashboardController.js +7 -4
- package/lib/controllers/escalationReviewController.js +299 -0
- package/lib/controllers/healthController.js +16 -0
- package/lib/controllers/interactionController.js +1 -1
- package/lib/controllers/messageController.js +67 -19
- package/lib/controllers/officeAssistantController.js +57 -0
- package/lib/controllers/patientController.js +216 -48
- package/lib/controllers/prescriptionController.js +10 -3
- package/lib/controllers/templateController.js +8 -17
- package/lib/controllers/traceController.js +26 -0
- package/lib/controllers/triageRecommendationController.js +41 -0
- package/lib/controllers/uploadController.js +2 -2
- package/lib/core/BatchingManager.js +146 -11
- package/lib/core/DeferredWorkRunner.js +257 -0
- package/lib/core/MessageParser.js +2 -2
- package/lib/core/NexusMessaging.js +948 -146
- package/lib/core/PhiProcessor.js +198 -17
- package/lib/core/ProcessingPipeline.js +49 -4
- package/lib/core/interactiveRouteService.js +64 -0
- package/lib/core/runtimeToolPolicy.js +3 -0
- package/lib/eval/EvalProvider.js +72 -25
- package/lib/fhir/config/catalogConfig.js +9 -14
- package/lib/fhir/config/fhirConfig.js +16 -12
- package/lib/fhir/constants/escalationCaseStatus.js +31 -0
- package/lib/fhir/constants/extensionSlugs.js +195 -0
- package/lib/fhir/constants/gradeMethods.js +12 -0
- package/lib/fhir/constants/projectionSlugs.js +69 -1
- package/lib/fhir/constants/severityPriority.js +8 -0
- package/lib/fhir/constants/variableRegistry.js +60 -0
- package/lib/fhir/helpers/compositeHelper.js +65 -12
- package/lib/fhir/helpers/contextArbitrationHelper.js +41 -0
- package/lib/fhir/helpers/elementHelper.js +39 -0
- package/lib/fhir/helpers/fhirHelper.js +4 -1
- package/lib/fhir/helpers/fhirReadHelper.js +62 -0
- package/lib/fhir/helpers/recommendationIds.js +44 -0
- package/lib/fhir/helpers/resourceDisplayHelper.js +9 -0
- package/lib/fhir/helpers/resourceHelper.js +46 -0
- package/lib/fhir/helpers/symptomAliasHelper.js +56 -0
- package/lib/fhir/helpers/termMatchHelper.js +42 -0
- package/lib/fhir/helpers/terminologyHelper.js +92 -5
- package/lib/fhir/helpers/triagePayloadHelper.js +133 -0
- package/lib/fhir/helpers/variableRegistryHelper.js +21 -0
- package/lib/fhir/index.js +75 -0
- package/lib/fhir/models/envelopeModel.js +22 -0
- package/lib/fhir/projections/clinicalMentionProjection.js +208 -46
- package/lib/fhir/projections/clusterProjection.js +124 -0
- package/lib/fhir/projections/contextFactProjection.js +380 -0
- package/lib/fhir/projections/contingencyProjection.js +224 -0
- package/lib/fhir/projections/dispatchedEscalationProjection.js +63 -0
- package/lib/fhir/projections/interventionProjection.js +245 -0
- package/lib/fhir/projections/palliativeCarePlanProjection.js +183 -0
- package/lib/fhir/projections/palliativeProjection.js +175 -0
- package/lib/fhir/projections/proctcaeProjection.js +62 -15
- package/lib/fhir/projections/recommendationPlanProjection.js +557 -0
- package/lib/fhir/projections/registerProjectors.js +10 -2
- package/lib/fhir/projections/reminderProjection.js +20 -0
- package/lib/fhir/projections/riskProjection.js +16 -0
- package/lib/fhir/projections/routingProjection.js +285 -0
- package/lib/fhir/projections/safetyGateProjection.js +42 -0
- package/lib/fhir/projections/symptomCaseProjection.js +324 -0
- package/lib/fhir/resources/CommunicationRequest.js +91 -0
- package/lib/fhir/resources/Condition.js +2 -24
- package/lib/fhir/resources/Encounter.js +30 -0
- package/lib/fhir/resources/Observation.js +22 -69
- package/lib/fhir/resources/Patient.js +57 -6
- package/lib/fhir/resources/Provenance.js +48 -12
- package/lib/fhir/resources/RiskAssessment.js +184 -0
- package/lib/fhir/resources/Task.js +102 -0
- package/lib/fhir/services/clinicalContextService.js +161 -0
- package/lib/fhir/services/clinicalMentionService.js +3 -5
- package/lib/fhir/services/clusterService.js +30 -0
- package/lib/fhir/services/contingencyService.js +47 -0
- package/lib/fhir/services/encounterService.js +16 -0
- package/lib/fhir/services/escalationService.js +85 -0
- package/lib/fhir/services/fhirService.js +20 -0
- package/lib/fhir/services/interventionService.js +50 -0
- package/lib/fhir/services/palliativeService.js +74 -0
- package/lib/fhir/services/patientService.js +41 -0
- package/lib/fhir/services/recommendationService.js +336 -0
- package/lib/fhir/services/resultObservationService.js +53 -0
- package/lib/fhir/services/riskService.js +202 -0
- package/lib/fhir/services/routingService.js +86 -0
- package/lib/fhir/services/snapshotService.js +18 -3
- package/lib/fhir/services/symptomCaseService.js +33 -0
- package/lib/fhir/services/terminologyService.js +16 -21
- package/lib/fhir/services/triageService.js +8 -4
- package/lib/fhir/stores/fhirStore.js +42 -19
- package/lib/fhir/utils/normalizeUtils.js +12 -0
- package/lib/helpers/airtableArchiveHelper.js +51 -0
- package/lib/helpers/airtableFormulaHelper.js +25 -0
- package/lib/helpers/caregiverHelper.js +136 -0
- package/lib/helpers/channelErrorHelper.js +31 -0
- package/lib/helpers/channelRetryHelper.js +156 -0
- package/lib/helpers/conversationWindowHelper.js +2 -2
- package/lib/helpers/deliveryAttemptHelper.js +14 -2
- package/lib/helpers/filesHelper.js +3 -3
- package/lib/helpers/healthHelper.js +40 -0
- package/lib/helpers/messageHelper.js +16 -6
- package/lib/helpers/messageStatusHelper.js +16 -22
- package/lib/helpers/metaSignatureHelper.js +6 -6
- package/lib/helpers/nerHelper.js +24 -0
- package/lib/helpers/outboundAllowlistHelper.js +51 -0
- package/lib/helpers/patientInformationHelper.js +20 -16
- package/lib/helpers/patientMessageHelper.js +79 -0
- package/lib/helpers/patientTaskRulesHelper.js +57 -0
- package/lib/helpers/pausedThreadHelper.js +37 -0
- package/lib/helpers/processHelper.js +47 -16
- package/lib/helpers/sendClaimHelper.js +126 -0
- package/lib/helpers/staffSendHelper.js +4 -0
- package/lib/helpers/templateFlowControllerHelper.js +1 -1
- package/lib/helpers/templateRecoveryHelper.js +66 -8
- package/lib/helpers/triageRecordHelper.js +124 -0
- package/lib/helpers/twilioHelper.js +7 -79
- package/lib/helpers/twilioMediaHelper.js +1 -1
- package/lib/helpers/whatsappHelper.js +3 -1
- package/lib/index.d.ts +844 -34
- package/lib/index.js +169 -11
- package/lib/jobs/ScheduledMessageJob.js +44 -0
- package/lib/jobs/TemplateApprovalJob.js +200 -33
- package/lib/models/agendaMessageModel.js +5 -0
- package/lib/models/airtableArchiveModel.js +225 -0
- package/lib/models/contactGateDecisionModel.js +27 -0
- package/lib/models/contextSyncStateModel.js +26 -0
- package/lib/models/deferredWorkModel.js +24 -0
- package/lib/models/deliveryAttemptModel.js +5 -1
- package/lib/models/escalationReviewModel.js +341 -0
- package/lib/models/flowRoutingModel.js +1 -1
- package/lib/models/messageModel.js +21 -1
- package/lib/models/patientProfileModel.js +24 -0
- package/lib/models/safetyNetPledgeModel.js +31 -0
- package/lib/models/sendClaimModel.js +18 -0
- package/lib/models/templateModel.js +1 -2
- package/lib/models/threadModel.js +7 -0
- package/lib/models/tokenMapModel.js +2 -1
- package/lib/models/writeClaimModel.js +14 -0
- package/lib/observability/telemetry.js +7 -7
- package/lib/providers/NerClient.js +2 -2
- package/lib/queue/QueueAdapter.js +1 -0
- package/lib/queue/RedisQueueAdapter.js +104 -7
- package/lib/routes/index.js +132 -2
- package/lib/services/airtableArchivePlanService.js +197 -0
- package/lib/services/airtableArchiveReadService.js +48 -0
- package/lib/services/airtableArchiveService.js +561 -0
- package/lib/services/airtableMirrorService.js +223 -0
- package/lib/services/airtableService.js +198 -18
- package/lib/services/assistantMessageService.js +140 -0
- package/lib/services/carePlanHistoryService.js +610 -0
- package/lib/services/characterizationOutcomeService.js +294 -0
- package/lib/services/contactGateService.js +178 -0
- package/lib/services/conversationService.js +66 -20
- package/lib/services/dashboard-provider-registry.js +38 -0
- package/lib/services/dashboardService.js +31 -4
- package/lib/services/escalationCaseTaskService.js +134 -0
- package/lib/services/escalationContextService.js +92 -0
- package/lib/services/escalationReviewService.js +2214 -0
- package/lib/services/flowDataExchangeService.js +1 -1
- package/lib/services/globalEntityService.js +1 -1
- package/lib/services/gravePendingService.js +41 -0
- package/lib/services/healthService.js +252 -0
- package/lib/services/heldMessageService.js +141 -0
- package/lib/services/inboundRecoveryService.js +354 -0
- package/lib/services/instructionInFlightService.js +17 -0
- package/lib/services/officeAssistantService.js +217 -0
- package/lib/services/orbisService.js +44 -0
- package/lib/services/patientClinicalStatusService.js +189 -0
- package/lib/services/patientResourceService.js +24 -0
- package/lib/services/patientService.js +28 -16
- package/lib/services/patientTaskService.js +221 -0
- package/lib/services/patientTaskSummaryService.js +93 -0
- package/lib/services/physicianService.js +31 -0
- package/lib/services/preprocessingService.js +18 -6
- package/lib/services/queueReconciliationService.js +161 -0
- package/lib/services/recommendationCarouselService.js +398 -0
- package/lib/services/reviewAlertSweepService.js +99 -0
- package/lib/services/reviewBoardService.js +75 -0
- package/lib/services/reviewDeadlineService.js +116 -0
- package/lib/services/reviewDraftSweepService.js +85 -0
- package/lib/services/teamAlertService.js +140 -0
- package/lib/services/templateService.js +1 -2
- package/lib/{helpers/threadHelper.js → services/threadService.js} +38 -6
- package/lib/services/tokenMapService.js +119 -22
- package/lib/services/toolRegistryService.js +43 -2
- package/lib/services/triageHistoryService.js +128 -0
- package/lib/services/twilioMediaService.js +79 -0
- package/lib/services/undeliverableService.js +36 -0
- package/lib/services/untakenAlertService.js +210 -0
- package/lib/shared/dtos/ClinicalAssertion.js +21 -0
- package/lib/shared/dtos/ClinicalMention.js +4 -0
- package/lib/shared/dtos/ClusterImpression.js +16 -5
- package/lib/shared/dtos/ContingencySafetyNet.js +69 -7
- package/lib/shared/dtos/DispatchedEscalation.js +4 -8
- package/lib/shared/dtos/GradedSymptom.js +2 -0
- package/lib/shared/dtos/Intervention.js +10 -3
- package/lib/shared/dtos/ManagedSymptom.js +40 -11
- package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
- package/lib/shared/dtos/PalliativeAssessment.js +62 -0
- package/lib/shared/dtos/PalliativeCarePlan.js +47 -0
- package/lib/shared/dtos/PatientRiskAssessment.js +25 -1
- package/lib/shared/dtos/RecommendationPlan.js +102 -0
- package/lib/shared/dtos/RecommendationSafetyGate.js +64 -0
- package/lib/shared/dtos/Reminder.js +2 -2
- package/lib/shared/dtos/RoutingDecision.js +2 -1
- package/lib/shared/dtos/SupportAction.js +28 -0
- package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
- package/lib/shared/dtos/TriageCompletion.js +50 -0
- package/lib/shared/dtos/TriageResponse.js +7 -1
- package/lib/storage/MongoStorage.js +10 -1
- package/lib/templates/predefinedTemplates.js +1 -1
- package/lib/templates/templateStructure.js +15 -2
- package/lib/utils/MapCache.js +1 -1
- package/lib/utils/coercionUtils.js +11 -0
- package/lib/utils/concurrencyUtils.js +13 -0
- package/lib/utils/dateUtils.js +114 -6
- package/lib/utils/errorUtils.js +26 -1
- package/lib/utils/formatUtils.js +43 -37
- package/lib/utils/httpErrorUtils.js +9 -0
- package/lib/utils/intervalSweeper.js +75 -0
- package/lib/utils/jsonUtils.js +51 -0
- package/lib/utils/logger.js +8 -6
- package/lib/utils/paginationUtils.js +30 -0
- package/lib/utils/retryUtils.js +9 -1
- package/lib/utils/sanitizerUtils.js +87 -1
- package/lib/utils/scheduleUtils.js +70 -1
- package/lib/utils/shadowScope.js +13 -0
- package/lib/utils/statsUtils.js +21 -0
- package/lib/utils/textMatchUtils.js +76 -0
- package/lib/utils/timeoutUtils.js +16 -0
- package/lib/utils/tokenMapUtils.js +3 -3
- package/package.json +11 -11
- package/lib/clinical/helpers/divergenceHelper.js +0 -100
- package/lib/clinical/models/divergenceModel.js +0 -41
- package/lib/clinical/services/clinicalAgentService.js +0 -18
- package/lib/clinical/services/divergenceService.js +0 -90
- package/lib/core/workflowRunner.js +0 -35
- package/lib/fhir/resources/Appointment.js +0 -28
- package/lib/fhir/resources/MedicationStatement.js +0 -42
- package/lib/fhir/resources/Procedure.js +0 -30
- package/lib/services/twilioService.js +0 -13
|
@@ -0,0 +1,561 @@
|
|
|
1
|
+
const axios = require('axios');
|
|
2
|
+
const { v4: uuidv4 } = require('uuid');
|
|
3
|
+
|
|
4
|
+
const runtimeConfig = require('../config/runtimeConfig');
|
|
5
|
+
const { uploadBufferToS3 } = require('../config/awsConfig');
|
|
6
|
+
const {
|
|
7
|
+
ARCHIVE_TABLES, MIN_ARCHIVE_AGE_DAYS, ARCHIVE_BATCH_SIZE, ARCHIVE_LEASE_MS, ARCHIVE_LEASE_RENEW_MS, ATTACHMENT_DOWNLOAD_TIMEOUT_MS, PATIENT_FIELDS, PLANNER_FIELDS,
|
|
8
|
+
ARCHIVE_DELETE_MAX_GROUPS, ARCHIVE_DELETE_ORDER, ARCHIVE_DELETE_SPACING_MS, ARCHIVE_DELETE_CHUNK_SIZE, LINK_FIELD_TYPES,
|
|
9
|
+
} = require('../config/airtableArchiveConfig');
|
|
10
|
+
const { logger } = require('../utils/logger');
|
|
11
|
+
const { stableStringify } = require('../utils/jsonUtils');
|
|
12
|
+
const { daysSince } = require('../utils/dateUtils');
|
|
13
|
+
const {
|
|
14
|
+
ARCHIVE_RUN_MODES, ARCHIVE_SCHEMA_VERSION, getAirtableArchiveRun, getAirtableArchiveSchema, getAirtableTableRecords,
|
|
15
|
+
} = require('../models/airtableArchiveModel');
|
|
16
|
+
const { createdBefore, createdSince, recordIdIn } = require('../helpers/airtableFormulaHelper');
|
|
17
|
+
const { normalizeFields, hashFields, schemaSnapshotId } = require('../helpers/airtableArchiveHelper');
|
|
18
|
+
|
|
19
|
+
const { scanRecordPages, getBaseSchema, deleteRecords } = require('./airtableService');
|
|
20
|
+
const { planArchive, resolveArchiveSchema } = require('./airtableArchivePlanService');
|
|
21
|
+
|
|
22
|
+
const DUPLICATE_KEY_ERROR = 11000;
|
|
23
|
+
const WRITE_CONCERN = { w: 'majority', j: true };
|
|
24
|
+
|
|
25
|
+
const archiveError = (code) => Object.assign(new Error(code), { code });
|
|
26
|
+
|
|
27
|
+
async function readArchiveSchema(baseId) {
|
|
28
|
+
let tables;
|
|
29
|
+
try {
|
|
30
|
+
tables = await getBaseSchema(baseId);
|
|
31
|
+
} catch (error) {
|
|
32
|
+
throw Object.assign(archiveError('archive_schema_unreadable'), { cause: error });
|
|
33
|
+
}
|
|
34
|
+
const { schema, missing } = resolveArchiveSchema(tables || []);
|
|
35
|
+
if (missing.length) {
|
|
36
|
+
logger.error('[airtableArchive] Configured tables or fields are missing or changed type in the base schema', { missing });
|
|
37
|
+
throw archiveError('archive_schema_mismatch');
|
|
38
|
+
}
|
|
39
|
+
return schema;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// A deleted or retyped field during the scans would read as empty links to the planner.
|
|
43
|
+
async function assertSchemaUnchanged(baseId, schema) {
|
|
44
|
+
const current = await readArchiveSchema(baseId);
|
|
45
|
+
const changed = schema.snapshot.filter((table, i) => stableStringify(table) !== stableStringify(current.snapshot[i])).map((table) => table.id);
|
|
46
|
+
if (changed.length) {
|
|
47
|
+
logger.error('[airtableArchive] Base schema changed during the scan', { baseId, tables: changed });
|
|
48
|
+
throw archiveError('archive_schema_mismatch');
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Records are read by field id and named from the run's snapshot, so a rename mid-scan cannot change what the planner sees.
|
|
53
|
+
async function scanTable({ baseId, tableId, filterByFormula, fieldIds, schema, lease }) {
|
|
54
|
+
const names = new Map(schema.snapshot.find((table) => table.id === tableId).fields.map((field) => [field.id, field.name]));
|
|
55
|
+
const records = [];
|
|
56
|
+
await scanRecordPages(baseId, tableId, {
|
|
57
|
+
filterByFormula,
|
|
58
|
+
fieldIds,
|
|
59
|
+
onPage: async (page) => {
|
|
60
|
+
for (const record of page) {
|
|
61
|
+
const fields = {};
|
|
62
|
+
for (const [fieldId, value] of Object.entries(record.fields)) {
|
|
63
|
+
if (!names.has(fieldId)) {
|
|
64
|
+
logger.error('[airtableArchive] Scanned a field missing from the run schema', { baseId, tableId, fieldId });
|
|
65
|
+
throw archiveError('archive_schema_mismatch');
|
|
66
|
+
}
|
|
67
|
+
fields[names.get(fieldId)] = value;
|
|
68
|
+
}
|
|
69
|
+
records.push({ id: record.id, createdTime: record.createdTime, fields });
|
|
70
|
+
}
|
|
71
|
+
await lease.renewIfDue();
|
|
72
|
+
},
|
|
73
|
+
onRestart: () => { records.length = 0; },
|
|
74
|
+
});
|
|
75
|
+
await lease.renew();
|
|
76
|
+
return records;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function scanOldRecords(baseId, cutoff, schema, lease) {
|
|
80
|
+
const recordsByTable = {};
|
|
81
|
+
for (const [key, tableId] of Object.entries(ARCHIVE_TABLES)) {
|
|
82
|
+
recordsByTable[schema.tables[key]] = await scanTable({ baseId, tableId, filterByFormula: createdBefore(cutoff), fieldIds: PLANNER_FIELDS[tableId], schema, lease });
|
|
83
|
+
}
|
|
84
|
+
return recordsByTable;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function scanPatientsWithRecent(baseId, cutoff, schema, lease) {
|
|
88
|
+
const patientsWithRecent = {};
|
|
89
|
+
for (const key of ['QUESTIONNAIRES', 'TRIAGES']) {
|
|
90
|
+
const table = schema.tables[key];
|
|
91
|
+
const patientField = schema.patientFields[table];
|
|
92
|
+
const tableId = ARCHIVE_TABLES[key];
|
|
93
|
+
const records = await scanTable({ baseId, tableId, filterByFormula: createdSince(cutoff), fieldIds: [PATIENT_FIELDS[tableId]], schema, lease });
|
|
94
|
+
patientsWithRecent[table] = new Set(records.flatMap((r) => r.fields[patientField] || []));
|
|
95
|
+
}
|
|
96
|
+
return patientsWithRecent;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function storeSchemaSnapshot(baseId, snapshot, now) {
|
|
100
|
+
const _id = schemaSnapshotId(baseId, snapshot);
|
|
101
|
+
await getAirtableArchiveSchema().updateOne(
|
|
102
|
+
{ _id },
|
|
103
|
+
{ $setOnInsert: { baseId, tables: snapshot, capturedAt: now } },
|
|
104
|
+
{ upsert: true, writeConcern: WRITE_CONCERN },
|
|
105
|
+
);
|
|
106
|
+
return _id;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
let runIndexesReady = null;
|
|
110
|
+
|
|
111
|
+
// The single-flight guarantee is the partial unique index, so no run starts before it exists.
|
|
112
|
+
function ensureRunIndexes() {
|
|
113
|
+
if (!runIndexesReady) {
|
|
114
|
+
runIndexesReady = getAirtableArchiveRun().createIndexes().catch((error) => {
|
|
115
|
+
runIndexesReady = null;
|
|
116
|
+
throw error;
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
return runIndexesReady;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function acquireRun({ baseId, mode, cutoff, now, groupIds }) {
|
|
123
|
+
await ensureRunIndexes();
|
|
124
|
+
const Run = getAirtableArchiveRun();
|
|
125
|
+
await Run.updateMany(
|
|
126
|
+
{ baseId, status: 'running', leaseExpiresAt: { $lt: now } },
|
|
127
|
+
{ $set: { status: 'failed', errorCode: 'lease_expired', finishedAt: now } },
|
|
128
|
+
);
|
|
129
|
+
try {
|
|
130
|
+
return await Run.create({
|
|
131
|
+
runId: uuidv4(), baseId, mode, cutoff, status: 'running', startedAt: now, leaseExpiresAt: new Date(now.getTime() + ARCHIVE_LEASE_MS), requestedGroupIds: groupIds,
|
|
132
|
+
});
|
|
133
|
+
} catch (error) {
|
|
134
|
+
if (error?.code === DUPLICATE_KEY_ERROR) throw archiveError('archive_run_in_progress');
|
|
135
|
+
throw error;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// A run whose lease was taken over must stop: another run now owns the base.
|
|
140
|
+
async function renewLease(runId) {
|
|
141
|
+
const result = await getAirtableArchiveRun().updateOne(
|
|
142
|
+
{ runId, status: 'running' },
|
|
143
|
+
{ $set: { leaseExpiresAt: new Date(Date.now() + ARCHIVE_LEASE_MS) } },
|
|
144
|
+
);
|
|
145
|
+
if (!result?.matchedCount) throw archiveError('archive_lease_lost');
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Renews at most once per interval, so a scan of hundreds of pages costs a handful of writes.
|
|
149
|
+
function leaseFor(runId) {
|
|
150
|
+
let renewedAt = Date.now();
|
|
151
|
+
const renew = async () => {
|
|
152
|
+
await renewLease(runId);
|
|
153
|
+
renewedAt = Date.now();
|
|
154
|
+
};
|
|
155
|
+
return {
|
|
156
|
+
renew,
|
|
157
|
+
renewIfDue: async () => {
|
|
158
|
+
if (Date.now() - renewedAt >= ARCHIVE_LEASE_RENEW_MS) await renew();
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function rehostAttachments({ baseId, tableId, recordId, attachments, alreadyHosted }) {
|
|
164
|
+
if (!attachments.length) return [];
|
|
165
|
+
const bucket = runtimeConfig.get('AIRTABLE_ARCHIVE_BUCKET');
|
|
166
|
+
if (!bucket) throw archiveError('archive_bucket_missing');
|
|
167
|
+
const hosted = [];
|
|
168
|
+
for (const { field, item } of attachments) {
|
|
169
|
+
const previous = alreadyHosted.get(item.id);
|
|
170
|
+
if (previous) {
|
|
171
|
+
hosted.push(previous);
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
const s3Key = `airtable-archive/${baseId}/${tableId}/${recordId}/${item.id}`;
|
|
175
|
+
const response = await axios.get(item.url, { responseType: 'arraybuffer', timeout: ATTACHMENT_DOWNLOAD_TIMEOUT_MS });
|
|
176
|
+
const bytes = response.data?.byteLength;
|
|
177
|
+
if (typeof item.size === 'number' ? bytes !== item.size : !bytes) throw archiveError('attachment_size_mismatch');
|
|
178
|
+
await uploadBufferToS3(Buffer.from(response.data), bucket, s3Key, item.type || 'application/octet-stream');
|
|
179
|
+
hosted.push({ field, id: item.id, filename: item.filename || null, type: item.type || null, size: item.size ?? null, s3Key });
|
|
180
|
+
}
|
|
181
|
+
return hosted;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async function tableModels(baseId, schema) {
|
|
185
|
+
const models = new Map();
|
|
186
|
+
for (const table of Object.values(schema.tables)) {
|
|
187
|
+
models.set(table, await getAirtableTableRecords({ baseId, tableId: schema.tableIds[table], tableName: table }));
|
|
188
|
+
}
|
|
189
|
+
return models;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const idsByTableOf = (entries) => {
|
|
193
|
+
const idsByTable = new Map();
|
|
194
|
+
entries.forEach(({ table, record }) => idsByTable.set(table, [...(idsByTable.get(table) || []), record.id]));
|
|
195
|
+
return idsByTable;
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
async function findCopies(models, entries, projection, filter = {}) {
|
|
199
|
+
const copies = new Map();
|
|
200
|
+
for (const [table, ids] of idsByTableOf(entries)) {
|
|
201
|
+
(await models.get(table).find({ _id: { $in: ids }, ...filter }, projection).lean()).forEach((doc) => copies.set(doc._id, doc));
|
|
202
|
+
}
|
|
203
|
+
return copies;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const emptyCounts = () => ({ scanned: 0, eligible: 0, copied: 0, refreshed: 0, verified: 0, failed: 0, skipped: 0, stamped: 0, deleted: 0 });
|
|
207
|
+
|
|
208
|
+
const WRITE_REJECTIONS = ['MongoBulkWriteError', 'MongooseBulkWriteError', 'MongoInvalidArgumentError'];
|
|
209
|
+
|
|
210
|
+
const writeBatch = (Records, ops) => Records.bulkWrite(ops, { ordered: false, throwOnValidationError: true, writeConcern: WRITE_CONCERN });
|
|
211
|
+
|
|
212
|
+
// A rejected batch is retried op by op, so one bad record cannot block the rest; the read-back decides each record.
|
|
213
|
+
async function writeOps(Records, ops, runId) {
|
|
214
|
+
try {
|
|
215
|
+
await writeBatch(Records, ops);
|
|
216
|
+
} catch (error) {
|
|
217
|
+
if (!WRITE_REJECTIONS.includes(error?.name)) throw error;
|
|
218
|
+
logger.error('[airtableArchive] Batch write rejected, retrying one by one', { runId, errorName: error?.name || 'UNKNOWN' });
|
|
219
|
+
for (const op of ops) {
|
|
220
|
+
await writeBatch(Records, [op])
|
|
221
|
+
.catch((opError) => logger.error('[airtableArchive] Record write rejected', { runId, _id: op.updateOne.filter._id, errorName: opError?.name || 'UNKNOWN' }));
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// Re-reads the batch whole, so copies carry every field and fresh attachment URLs.
|
|
227
|
+
async function readWholeRecords(baseId, batch, schema, lease) {
|
|
228
|
+
const wholeById = new Map();
|
|
229
|
+
const idsByTable = new Map();
|
|
230
|
+
for (const { table, record } of batch) {
|
|
231
|
+
if (!idsByTable.has(table)) idsByTable.set(table, []);
|
|
232
|
+
idsByTable.get(table).push(record.id);
|
|
233
|
+
}
|
|
234
|
+
for (const [table, ids] of idsByTable) {
|
|
235
|
+
const records = await scanTable({ baseId, tableId: schema.tableIds[table], filterByFormula: recordIdIn(ids), schema, lease });
|
|
236
|
+
records.forEach((record) => wholeById.set(record.id, record));
|
|
237
|
+
}
|
|
238
|
+
return wholeById;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// Planner inputs as the plan saw them; a group whose inputs changed since the scan is left for the next run.
|
|
242
|
+
const plannerInputs = (record, plannerNames) => stableStringify({
|
|
243
|
+
createdTime: record.createdTime,
|
|
244
|
+
fields: Object.fromEntries(plannerNames.filter((name) => name in record.fields).map((name) => [name, record.fields[name]])),
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
// Where readers find a record: a renamed table or a regrouped record is rewritten even when its fields did not change.
|
|
248
|
+
const placementOf = (tableName, groupId, patient, createdTime) => stableStringify({ tableName, groupId, patient, createdTime: new Date(createdTime).getTime() });
|
|
249
|
+
|
|
250
|
+
async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now, lease, models }) {
|
|
251
|
+
const wholeById = await readWholeRecords(baseId, batch, schema, lease);
|
|
252
|
+
const changedGroups = new Set(batch.filter(({ table, record: scanned }) => {
|
|
253
|
+
const whole = wholeById.get(scanned.id);
|
|
254
|
+
return !whole || plannerInputs(whole, schema.plannerFields[table]) !== plannerInputs(scanned, schema.plannerFields[table]);
|
|
255
|
+
}).map(({ group }) => group.groupId));
|
|
256
|
+
const existing = await findCopies(models, batch, {
|
|
257
|
+
fields: 1, fieldsHash: 1, sourceHash: 1, tableId: 1, schemaId: 1, tableName: 1, groupId: 1, patient: 1, createdTime: 1, attachments: 1, sourceDeletedAt: 1,
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
const expected = new Map();
|
|
261
|
+
const opsByTable = new Map();
|
|
262
|
+
for (const { table, record: scanned, group, patient } of batch) {
|
|
263
|
+
// A stamped copy is what readers serve once the delete finishes, so a record a stopped delete left behind keeps it.
|
|
264
|
+
if (existing.get(scanned.id)?.sourceDeletedAt) {
|
|
265
|
+
counts[table].skipped += 1;
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
if (changedGroups.has(group.groupId)) {
|
|
269
|
+
counts[table].failed += 1;
|
|
270
|
+
logger.error('[airtableArchive] Group changed or gone since the scan', { runId, table, recordId: scanned.id, groupId: group.groupId });
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
const record = wholeById.get(scanned.id);
|
|
274
|
+
const _id = record.id;
|
|
275
|
+
const { normalized, attachments } = normalizeFields(record.fields);
|
|
276
|
+
const fieldsHash = hashFields(normalized);
|
|
277
|
+
const sourceHash = hashFields(normalized, schema.computed.get(table));
|
|
278
|
+
const tableId = schema.tableIds[table];
|
|
279
|
+
const placement = placementOf(table, group.groupId, patient, record.createdTime);
|
|
280
|
+
const previous = existing.get(_id);
|
|
281
|
+
const previousIntact = previous?.tableId && previous.schemaId && hashFields(previous.fields) === previous.fieldsHash;
|
|
282
|
+
if (previousIntact && previous.sourceHash === sourceHash && placementOf(previous.tableName, previous.groupId, previous.patient, previous.createdTime) === placement) {
|
|
283
|
+
expected.set(_id, { table, recordId: record.id, fieldsHash: previous.fieldsHash, placement });
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
try {
|
|
287
|
+
const alreadyHosted = new Map((previous?.attachments || []).map((a) => [a.id, a]));
|
|
288
|
+
const hosted = await rehostAttachments({ baseId, tableId, recordId: record.id, attachments, alreadyHosted });
|
|
289
|
+
if (!opsByTable.has(table)) opsByTable.set(table, []);
|
|
290
|
+
opsByTable.get(table).push({
|
|
291
|
+
updateOne: {
|
|
292
|
+
filter: { _id },
|
|
293
|
+
update: {
|
|
294
|
+
$set: {
|
|
295
|
+
baseId, tableId, tableName: table, recordId: record.id, createdTime: new Date(record.createdTime),
|
|
296
|
+
fields: normalized, fieldsHash, sourceHash, patient, groupId: group.groupId, schemaId, attachments: hosted,
|
|
297
|
+
source: { kind: 'live', baseId }, schemaVersion: ARCHIVE_SCHEMA_VERSION,
|
|
298
|
+
},
|
|
299
|
+
$setOnInsert: { runId, archivedAt: now, sourceDeletedAt: null },
|
|
300
|
+
},
|
|
301
|
+
upsert: true,
|
|
302
|
+
},
|
|
303
|
+
});
|
|
304
|
+
expected.set(_id, { table, recordId: record.id, fieldsHash, placement });
|
|
305
|
+
counts[table][previous ? 'refreshed' : 'copied'] += 1;
|
|
306
|
+
} catch (error) {
|
|
307
|
+
counts[table].failed += 1;
|
|
308
|
+
logger.error('[airtableArchive] Record not copied', { runId, table, recordId: record.id, errorCode: error?.code || 'UNKNOWN' });
|
|
309
|
+
}
|
|
310
|
+
// Downloads can outlast the lease, so a record with attachments renews it before the next one.
|
|
311
|
+
if (attachments.length) await renewLease(runId);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
for (const [table, ops] of opsByTable) await writeOps(models.get(table), ops, runId);
|
|
315
|
+
|
|
316
|
+
const storedById = await findCopies(
|
|
317
|
+
models, [...expected.values()].map(({ table, recordId }) => ({ table, record: { id: recordId } })), { fields: 1, tableName: 1, groupId: 1, patient: 1, createdTime: 1 },
|
|
318
|
+
);
|
|
319
|
+
for (const [_id, { table, recordId, fieldsHash, placement }] of expected) {
|
|
320
|
+
const doc = storedById.get(_id);
|
|
321
|
+
if (doc && hashFields(doc.fields) === fieldsHash && placementOf(doc.tableName, doc.groupId, doc.patient, doc.createdTime) === placement) counts[table].verified += 1;
|
|
322
|
+
else {
|
|
323
|
+
counts[table].failed += 1;
|
|
324
|
+
logger.error('[airtableArchive] Copy did not verify', { runId, table, recordId });
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
330
|
+
|
|
331
|
+
const linkNamesOf = (schema, table) => schema.snapshot.find((t) => t.name === table).fields.filter((f) => LINK_FIELD_TYPES.includes(f.type)).map((f) => f.name);
|
|
332
|
+
|
|
333
|
+
// Airtable drops links to a deleted record, so a link that lost only records gone from Airtable with a stamped copy reads as before.
|
|
334
|
+
function restoreDeletedLinks(fields, reference, linkNames, goneIds) {
|
|
335
|
+
const restored = { ...fields };
|
|
336
|
+
for (const name of linkNames) {
|
|
337
|
+
const before = reference[name] || [];
|
|
338
|
+
const after = fields[name] || [];
|
|
339
|
+
const lost = before.filter((id) => !after.includes(id));
|
|
340
|
+
if (lost.length && lost.every((id) => goneIds.has(id)) && after.every((id) => before.includes(id))) restored[name] = reference[name];
|
|
341
|
+
}
|
|
342
|
+
return restored;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function deleteBlocker({ whole, scanned, doc, table, group, patient, schema, goneIds }) {
|
|
346
|
+
if (!whole) return 'gone_from_source';
|
|
347
|
+
const linkNames = linkNamesOf(schema, table);
|
|
348
|
+
const asScanned = { ...whole, fields: restoreDeletedLinks(whole.fields, scanned.fields, linkNames, goneIds) };
|
|
349
|
+
if (plannerInputs(asScanned, schema.plannerFields[table]) !== plannerInputs(scanned, schema.plannerFields[table])) return 'changed_since_scan';
|
|
350
|
+
if (!doc) return 'not_archived';
|
|
351
|
+
if (hashFields(doc.fields) !== doc.fieldsHash) return 'copy_damaged';
|
|
352
|
+
const { normalized, attachments } = normalizeFields(whole.fields);
|
|
353
|
+
if (doc.sourceHash !== hashFields(restoreDeletedLinks(normalized, doc.fields, linkNames, goneIds), schema.computed.get(table))) return 'source_edited';
|
|
354
|
+
if (placementOf(doc.tableName, doc.groupId, doc.patient, doc.createdTime) !== placementOf(table, group.groupId, patient, whole.createdTime)) return 'placement_changed';
|
|
355
|
+
const hosted = new Set((doc.attachments || []).map((a) => a.id));
|
|
356
|
+
if (attachments.some(({ item }) => !hosted.has(item.id))) return 'attachment_not_hosted';
|
|
357
|
+
return null;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// The request may have landed even when it failed, so what is still in Airtable decides.
|
|
361
|
+
async function deleteChunk({ baseId, runId, tableId, recordIds, schema, lease }) {
|
|
362
|
+
try {
|
|
363
|
+
if ((await deleteRecords(baseId, tableId, recordIds)).length === recordIds.length) return;
|
|
364
|
+
} catch (error) {
|
|
365
|
+
logger.warn('[airtableArchive] Delete request failed, re-reading what is left', { runId, tableId, statusCode: error?.statusCode || null });
|
|
366
|
+
}
|
|
367
|
+
const left = await scanTable({ baseId, tableId, filterByFormula: recordIdIn(recordIds), schema, lease });
|
|
368
|
+
if (left.length) throw archiveError('archive_delete_failed');
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
const ARCHIVED_PROJECTION = { fields: 1, fieldsHash: 1, sourceHash: 1, tableName: 1, groupId: 1, patient: 1, createdTime: 1, attachments: 1 };
|
|
372
|
+
|
|
373
|
+
// Linked records missing from Airtable whose copies were stamped deleted; only records the scan covers count, so missing means gone.
|
|
374
|
+
async function goneLinkedIds({ entries, wholeById, archived, schema, liveIds, cutoff, models }) {
|
|
375
|
+
const missing = new Set();
|
|
376
|
+
for (const { table, record: scanned } of entries) {
|
|
377
|
+
const whole = wholeById.get(scanned.id);
|
|
378
|
+
const doc = archived.get(scanned.id);
|
|
379
|
+
for (const name of linkNamesOf(schema, table)) {
|
|
380
|
+
[...(scanned.fields[name] || []), ...(doc?.fields?.[name] || [])]
|
|
381
|
+
.filter((id) => !(whole?.fields[name] || []).includes(id) && !liveIds.has(id)).forEach((id) => missing.add(id));
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
if (!missing.size) return new Set();
|
|
385
|
+
const gone = new Set();
|
|
386
|
+
for (const Records of models.values()) {
|
|
387
|
+
(await Records.find({ _id: { $in: [...missing] }, sourceDeletedAt: { $ne: null }, createdTime: { $lt: cutoff } }, { _id: 1 }).lean()).forEach((doc) => gone.add(doc._id));
|
|
388
|
+
}
|
|
389
|
+
return gone;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
async function findBlockers({ baseId, entries, schema, lease, liveIds, cutoff, models }) {
|
|
393
|
+
const wholeById = await readWholeRecords(baseId, entries, schema, lease);
|
|
394
|
+
const archived = await findCopies(models, entries, ARCHIVED_PROJECTION);
|
|
395
|
+
const goneIds = await goneLinkedIds({ entries, wholeById, archived, schema, liveIds, cutoff, models });
|
|
396
|
+
return entries.map((entry) => ({
|
|
397
|
+
entry,
|
|
398
|
+
reason: deleteBlocker({
|
|
399
|
+
whole: wholeById.get(entry.record.id), scanned: entry.record, doc: archived.get(entry.record.id), ...entry, schema, goneIds,
|
|
400
|
+
}),
|
|
401
|
+
})).filter(({ reason }) => reason);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// Every record of a verified group is stamped deleted in the archive before Airtable deletes it, so readers never miss it.
|
|
405
|
+
async function deleteBatch({ baseId, runId, batch, schema, counts, groups, lease, liveIds, cutoff, models }) {
|
|
406
|
+
const blocked = new Set();
|
|
407
|
+
for (const { entry: { table, record, group }, reason } of await findBlockers({ baseId, entries: batch, schema, lease, liveIds, cutoff, models })) {
|
|
408
|
+
blocked.add(group.groupId);
|
|
409
|
+
logger.error('[airtableArchive] Group kept in Airtable: its copy cannot stand in for the source', { runId, table, recordId: record.id, groupId: group.groupId, reason });
|
|
410
|
+
}
|
|
411
|
+
groups.unverified += blocked.size;
|
|
412
|
+
const verified = batch.filter(({ group }) => !blocked.has(group.groupId));
|
|
413
|
+
if (!verified.length) return;
|
|
414
|
+
|
|
415
|
+
const stampedAt = new Date();
|
|
416
|
+
for (const [table, ids] of idsByTableOf(verified)) {
|
|
417
|
+
await models.get(table).updateMany(
|
|
418
|
+
{ _id: { $in: ids }, sourceDeletedAt: null },
|
|
419
|
+
{ $set: { sourceDeletedAt: stampedAt, deleteRunId: runId } },
|
|
420
|
+
{ writeConcern: WRITE_CONCERN },
|
|
421
|
+
);
|
|
422
|
+
}
|
|
423
|
+
const stamped = await findCopies(models, verified, { _id: 1 }, { sourceDeletedAt: { $ne: null } });
|
|
424
|
+
if (stamped.size !== verified.length) throw archiveError('archive_stamp_failed');
|
|
425
|
+
verified.forEach(({ table }) => { counts[table].stamped += 1; });
|
|
426
|
+
|
|
427
|
+
for (const tableId of ARCHIVE_DELETE_ORDER) {
|
|
428
|
+
const entries = verified.filter(({ table }) => schema.tableIds[table] === tableId);
|
|
429
|
+
for (let i = 0; i < entries.length; i += ARCHIVE_DELETE_CHUNK_SIZE) {
|
|
430
|
+
const chunk = entries.slice(i, i + ARCHIVE_DELETE_CHUNK_SIZE);
|
|
431
|
+
// Re-checked right before its request, so an edit made while earlier chunks were deleted stops the run with its copy stamped.
|
|
432
|
+
const changed = await findBlockers({ baseId, entries: chunk, schema, lease, liveIds, cutoff, models });
|
|
433
|
+
if (changed.length) {
|
|
434
|
+
changed.forEach(({ entry: { table, record, group }, reason }) => logger.error('[airtableArchive] Record changed during the delete', { runId, table, recordId: record.id, groupId: group.groupId, reason }));
|
|
435
|
+
throw archiveError('archive_changed_during_delete');
|
|
436
|
+
}
|
|
437
|
+
await deleteChunk({ baseId, runId, tableId, recordIds: chunk.map(({ record }) => record.id), schema, lease });
|
|
438
|
+
chunk.forEach(({ table, record }) => {
|
|
439
|
+
counts[table].deleted += 1;
|
|
440
|
+
liveIds.delete(record.id);
|
|
441
|
+
});
|
|
442
|
+
await lease.renewIfDue();
|
|
443
|
+
await delay(ARCHIVE_DELETE_SPACING_MS);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
if ((await readWholeRecords(baseId, verified, schema, lease)).size) throw archiveError('archive_delete_incomplete');
|
|
447
|
+
groups.deleted += new Set(verified.map(({ group }) => group.groupId)).size;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function plannedGroup(group, patientsWithRecent) {
|
|
451
|
+
const patientRecordIds = [...new Set(group.records.map(({ patient }) => patient?.recordId).filter(Boolean))];
|
|
452
|
+
const records = {};
|
|
453
|
+
group.records.forEach(({ table }) => { records[table] = (records[table] || 0) + 1; });
|
|
454
|
+
const isInactive = (patientId) => Object.values(patientsWithRecent).every((patients) => !patients.has(patientId));
|
|
455
|
+
return { groupId: group.groupId, patientRecordIds, inactive: patientRecordIds.length > 0 && patientRecordIds.every(isInactive), records };
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// Batches never split a group, so a changed record holds back its whole group.
|
|
459
|
+
function groupBatches(groups) {
|
|
460
|
+
const batches = [];
|
|
461
|
+
let batch = [];
|
|
462
|
+
for (const group of groups) {
|
|
463
|
+
if (batch.length && batch.length + group.length > ARCHIVE_BATCH_SIZE) {
|
|
464
|
+
batches.push(batch);
|
|
465
|
+
batch = [];
|
|
466
|
+
}
|
|
467
|
+
batch.push(...group);
|
|
468
|
+
}
|
|
469
|
+
if (batch.length) batches.push(batch);
|
|
470
|
+
return batches;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function validateRequest({ baseId, cutoff, mode, now, groupIds }) {
|
|
474
|
+
if (!baseId) throw archiveError('archive_base_required');
|
|
475
|
+
if (!ARCHIVE_RUN_MODES.includes(mode) || mode === 'mirror') throw archiveError('archive_mode_invalid');
|
|
476
|
+
if (mode === 'delete') {
|
|
477
|
+
const valid = Array.isArray(groupIds) && groupIds.length > 0 && groupIds.length <= ARCHIVE_DELETE_MAX_GROUPS
|
|
478
|
+
&& groupIds.every((id) => typeof id === 'string' && id) && new Set(groupIds).size === groupIds.length;
|
|
479
|
+
if (!valid) throw archiveError('archive_delete_groups_invalid');
|
|
480
|
+
}
|
|
481
|
+
if (!(cutoff instanceof Date) || Number.isNaN(cutoff.getTime())) throw archiveError('archive_cutoff_invalid');
|
|
482
|
+
if (daysSince(cutoff, now.getTime()) < MIN_ARCHIVE_AGE_DAYS) throw archiveError('archive_cutoff_too_recent');
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// `plan` and `copy` never delete from Airtable; `delete` removes only the named groups that are still eligible and verified.
|
|
486
|
+
async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date(), groupIds = [] }) {
|
|
487
|
+
validateRequest({ baseId, cutoff, mode, now, groupIds });
|
|
488
|
+
const run = await acquireRun({ baseId, mode, cutoff, now, groupIds: mode === 'delete' ? groupIds : [] });
|
|
489
|
+
const { runId } = run;
|
|
490
|
+
let counts = {};
|
|
491
|
+
const groups = { requested: mode === 'delete' ? groupIds.length : 0, notEligible: 0, unverified: 0, deleted: 0 };
|
|
492
|
+
|
|
493
|
+
try {
|
|
494
|
+
const schema = await readArchiveSchema(baseId);
|
|
495
|
+
counts = Object.fromEntries(Object.values(schema.tables).map((table) => [table, emptyCounts()]));
|
|
496
|
+
const lease = leaseFor(runId);
|
|
497
|
+
const recordsByTable = await scanOldRecords(baseId, cutoff, schema, lease);
|
|
498
|
+
const patientsWithRecent = await scanPatientsWithRecent(baseId, cutoff, schema, lease);
|
|
499
|
+
await assertSchemaUnchanged(baseId, schema);
|
|
500
|
+
const plan = planArchive({ recordsByTable, patientsWithRecent, schema });
|
|
501
|
+
|
|
502
|
+
Object.entries(recordsByTable).forEach(([table, records]) => { counts[table].scanned = records.length; });
|
|
503
|
+
const recordsById = new Map(Object.values(recordsByTable).flat().map((record) => [record.id, record]));
|
|
504
|
+
const work = plan.eligible.map((group) => group.records.map(({ table, id, patient }) => ({ table, record: recordsById.get(id), group, patient })));
|
|
505
|
+
work.flat().forEach(({ table }) => { counts[table].eligible += 1; });
|
|
506
|
+
|
|
507
|
+
const models = mode === 'plan' ? null : await tableModels(baseId, schema);
|
|
508
|
+
if (mode === 'copy' && work.length) {
|
|
509
|
+
const schemaId = await storeSchemaSnapshot(baseId, schema.snapshot, now);
|
|
510
|
+
for (const batch of groupBatches(work)) {
|
|
511
|
+
await copyBatch({ baseId, runId, batch, schema, schemaId, counts, now, lease, models });
|
|
512
|
+
await renewLease(runId);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
if (mode === 'delete') {
|
|
517
|
+
const requested = new Set(groupIds);
|
|
518
|
+
const targets = work.filter(([{ group }]) => requested.has(group.groupId));
|
|
519
|
+
groups.notEligible = requested.size - targets.length;
|
|
520
|
+
const liveIds = new Set(recordsById.keys());
|
|
521
|
+
for (const batch of groupBatches(targets)) {
|
|
522
|
+
await deleteBatch({ baseId, runId, batch, schema, counts, groups, lease, liveIds, cutoff, models });
|
|
523
|
+
await renewLease(runId);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// Only a plan stores its groups: a copy run's list would include groups it held back, so slices are picked from plans.
|
|
528
|
+
const eligibleGroups = mode === 'plan' ? plan.eligible.map((group) => plannedGroup(group, patientsWithRecent)) : [];
|
|
529
|
+
const failed = Object.values(counts).reduce((sum, c) => sum + c.failed, 0);
|
|
530
|
+
const errorCode = (failed && 'records_failed') || ((groups.notEligible || groups.unverified) && 'groups_not_deleted') || null;
|
|
531
|
+
const summary = {
|
|
532
|
+
runId, mode, cutoff, status: errorCode ? 'failed' : 'succeeded',
|
|
533
|
+
components: { eligible: plan.eligible.length, kept: plan.keptByReason }, tables: counts, groups,
|
|
534
|
+
};
|
|
535
|
+
const finished = await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, {
|
|
536
|
+
$set: {
|
|
537
|
+
status: summary.status, finishedAt: new Date(), components: summary.components, tables: counts, eligibleGroups, groups, errorCode,
|
|
538
|
+
},
|
|
539
|
+
});
|
|
540
|
+
if (!finished?.matchedCount) throw archiveError('archive_lease_lost');
|
|
541
|
+
logger.info('[airtableArchive] Run finished', summary);
|
|
542
|
+
return summary;
|
|
543
|
+
} catch (error) {
|
|
544
|
+
const errorCode = [error?.code, error?.error].find((code) => code && typeof code === 'string') || 'UNKNOWN';
|
|
545
|
+
await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, { $set: { status: 'failed', finishedAt: new Date(), tables: counts, groups, errorCode } });
|
|
546
|
+
logger.error('[airtableArchive] Run failed', { runId, mode, errorCode });
|
|
547
|
+
throw error;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
module.exports = {
|
|
552
|
+
runArchive,
|
|
553
|
+
archiveError,
|
|
554
|
+
acquireRun,
|
|
555
|
+
leaseFor,
|
|
556
|
+
renewLease,
|
|
557
|
+
rehostAttachments,
|
|
558
|
+
writeOps,
|
|
559
|
+
storeSchemaSnapshot,
|
|
560
|
+
WRITE_CONCERN,
|
|
561
|
+
};
|