refactor(worker): move integration, chat and ai-agent handler data access into business - #1099
Open
realcodesiman wants to merge 1 commit into
Open
refactor(worker): move integration, chat and ai-agent handler data access into business#1099realcodesiman wants to merge 1 commit into
realcodesiman wants to merge 1 commit into
Conversation
…cess into business
Removes direct db usage from apps/worker/src/{integration,chat,ai-agent,
services,lib} per .agents/rules/data-access.md. Hot-path bodies are
moved verbatim; every isNull TOCTOU guard, sql increment, untargeted
onConflictDoNothing, sql.identifier and withBlockedOwnerGuard call site
is preserved.
- coexist: claimRunForSync/incrementProgress/findInitState/... on the
coexist-sync-run repository, staging repository methods, and a new
coexistImportService holding the historical-import transaction
- contact/tag/sequence flow steps, inbox labels, templates, message
status and received-message activity tracking routed through
contactService, tagService, contactSequenceService,
conversationService, inboxService and the integration services
- sequenceDispatchUtils gains findRunning/markCompleted/markCanceled/
markFailed; new ai-embedding, integration-lookup and import
repositories; lib/db.ts keeps its exported names and signatures
Deliberate behavior changes (recorded in the PR): stepBlockContact now
goes through contactService.block (emits + invalidates), setFlowFlags
invalidates the contact cache, process-ai-file enqueues only the ids it
inserted, send-flow-direct and update-avatar add workspace scoping, and
the inbound/outbound activity conversation updates add workspaceId to
their WHERE.
6 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
db.*call fromapps/worker/src/{integration,chat,ai-agent,services,lib}(inbound message ingestion, flow steps, template sends, coexist import) per.agents/rules/data-access.md. Bodies are moved verbatim; everyisNullTOCTOU guard,sql\col + N`increment, untargetedonConflictDoNothing(),sql.identifier()andwithBlockedOwnerGuardcall site is preserved (git diff main | grep withBlockedOwnerGuard` is empty).main, append-only barrel edits. ThedeleteContacthandler is left on itsmainform because feat(contacts): cover full public API for MCP, move logic into business services #1093 already migrates it; expect a keep-both merge inhandlers/contact.ts,contact/service.ts,tag/service.tsand the two barrels.Changes
coexistSyncRunRepository.{claimRunForSync,incrementProgress,findInitState,findLastSyncedAt,findTerminalCounters,findNewestLiveRunId,findFlushResumeState},whatsappCoexistStagingRepository.{stagePayload,listUnprocessed,markProcessed,hasUnprocessed}, newcoexistImportServiceholding the historical-import transaction andcontactRepository.enrichIfNull(COALESCE SQL verbatim).claimRunForSyncdeliberately does not filterstatus IN ('init','running')and takestouchUpdatedAtto preserve the two callers' differing SET clauses.contactService.{setFlowFlags,subscribeBroadcastIfUnsubscribed,unsubscribeBroadcast,setAvatarIfEmpty},contactNoteService.createFromFlow,tagService.{attachByNamesToContact,listIdsByNames,detachTagIdsFromContact,detachTagFromContacts,linkTagToContactsReturningNew,ensureTagByName,ensureTagChannel,...},contactSequenceService.{isEnrolled,findFirstActiveStep,findSequenceName},sequenceDispatchUtils.{findRunning,markCompleted,markCanceled,markFailed}.conversationService.{recordInboundActivity,recordOutboundFlowStep,recordOutboundMessageActivity,findByIdWithContact},inboxService.findWithIntegration{Messenger,Whatsapp}ById, approved-template lookups on the integration services,contactInboxRepository.{findWithContact,findWithConversationAndContact,...}.flowService.{findActiveById,findAnyActive},flowVersionService.findByIdForWorkspace, newai-embedding,integration-lookupandimportrepositories;lib/db.tskeeps its exported names and signatures.+ Nincrement and the AI-file enqueue.Deliberate behavior changes
stepBlockContactnow goes throughcontactService.block(addsfindByIdOrFail, contact-info-change events and cache invalidation the raw write lacked).setFlowFlagsnow invalidates the contact cache (the rawdb.updatenever did).process-ai-fileenqueues only the embedding ids it just inserted (bulkCreatePending(...).returning), instead of re-reading all rows for the file, which double-enqueued prior runs' embeddings on retry.send-flow-directandupdate-avatarnow scope byworkspaceId(viacontactInboxService.listByContactId/contactService.findById/setAvatarIfEmpty); safe by construction, data is already workspace-scoped upstream.workspaceIdto their WHERE viaupdateFlowStepState.coexist-importis a business service rather than a database repository; approved-template lookups live on the integration services rather thantemplateService.Test plan
pnpm --filter @chatbotx.io/database check-types && testpnpm --filter @chatbotx.io/business check-types && test(only the pre-existingads-conversion-rule.service.test.tsfailures remain, also red onmain)pnpm --filter worker check-types && test(only the pre-existingflow-import-handler.test.tsfailures remain, also red onmain)pnpm --filter worker buildpnpm lint