# melgarafael/deskcommcrm architecture

> Architecture diagram of the GitHub repository melgarafael/deskcommcrm, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-08-03). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/melgarafael/deskcommcrm
- Repository: https://github.com/melgarafael/deskcommcrm

## Overview

#### Purpose and entry points
DeskcommCRM is a self-hostable, multi-tenant sales CRM centered on WhatsApp operations, with human attendants and AI agents sharing inbox, pipeline, and automation workflows. The Next.js App Router serves public auth, authenticated tenant UI, platform-admin UI, REST APIs, webhooks, cron endpoints, and MCP endpoints. Primary roots: `app/layout.tsx`, `app/app/layout.tsx`, `app/api/v1/`, `app/admin/(protected)/`.

#### Tenant security and persistence boundary
Supabase provides Postgres, Auth, Storage, Realtime, pgvector, and the tenant-isolation boundary through RLS. Server/browser/admin clients are separated in `lib/supabase/server.ts`, `lib/supabase/browser.ts`, and `lib/supabase/admin.ts`. The installable schema baseline is `supabase/baseline.sql`; incremental domain changes live in `supabase/migrations/`, including AI agents and follow-up flows. Authorization helpers enforce role and platform-admin boundaries in `lib/auth/require-role.ts` and `lib/auth/requirePlatformAdmin.ts`.

#### CRM and live-attendance core
The tenant application exposes Inbox, Contacts, Kanban/pipelines, team management, metrics, audit, settings, and LGPD operations under `app/app/`. Canonical business APIs are route handlers under `app/api/v1/conversations/`, `app/api/v1/leads/`, and `app/api/v1/contacts/`. Inbox operations include sending messages, assignment/claim/release/transfer, notes, snoozing, media, and retention; React clients use realtime-oriented hooks such as `hooks/inbox/useConversationsRealtime.ts` and `hooks/inbox/useMessagesRealtime.ts`.

#### Channels and message lifecycle
Channel adapters normalize WAHA and Meta Cloud WhatsApp behind `lib/channels/index.ts`, with implementations in `lib/channels/adapters/waha.ts` and `lib/channels/adapters/meta-cloud.ts`. Inbound provider webhooks enter through `app/api/v1/webhooks/waha/[token]/route.ts` or `app/api/v1/webhooks/meta/[token]/route.ts`, are validated/ingested, persisted as CRM conversations/messages, and become realtime-visible. Outbound messaging is mediated by messaging APIs and channel capability/pacing controls; media derives, persistence, transcription, and cleanup are handled by `workers/media-persist-worker.ts`, `workers/media-derive-worker.ts`, and `workers/storage-cleanup-worker.ts`.

#### AI-agent runtime and knowledge
The AI module configures versioned agents, credentials, providers, budgets, skills, routers, cases, memory, and RAG through `app/api/v1/ai/` and the operator UI in `app/app/ai/`. The execution engine is centered in `lib/agent-engine/agent/inbound-turn.ts`, `lib/agent-engine/agent/resolve-turn-agent.ts`, and `workers/agent-worker/main.ts`: an inbound turn resolves an eligible agent, gathers CRM/knowledge context, invokes an LLM/provider, applies guardrails, and dispatches actions or a human handoff. RAG ingestion and embedding reside in `lib/ai/rag/` and `workers/rag-indexer.ts`; model calls use Vercel AI SDK-compatible provider logic in `lib/agent-engine/edge/llm/run-model-call.ts`.

#### Automation, follow-ups, and asynchronous control flow
Domain events are recorded and drained rather than causing direct database-triggered HTTP calls. `lib/event-log/drain.ts` and `app/api/v1/cron/event-log-drain/route.ts` feed the automation engine in `lib/automation/engine.ts`. Public tenant capture webhooks enter at `app/api/v1/webhooks/in/[token]/route.ts`; rules can mutate CRM state, send WhatsApp, or invoke outbound webhooks. Follow-up graphs are authored in `app/app/ai/followups/[id]/`, validated/published by `lib/followup/publish.ts`, and executed by `lib/followup/engine.ts` via `app/api/v1/cron/followup-flow-worker/route.ts`. Routing, snooze, risk, LGPD, and agent dispatch have comparable cron/worker boundaries under `app/api/v1/cron/` and `workers/`.

#### Governance, integrations, and deployment
Guardrails constrain AI sends, disclosure, LGPD basis, messaging windows, and promises in `lib/agent-engine/guardrails/`; auditing is centralized in `lib/audit/index.ts`. MCP exposes governed CRM tools through `app/api/mcp/route.ts` and `lib/mcp/server.ts`. Nuvemshop OAuth/webhooks are isolated in `lib/nuvemshop/` and `app/api/v1/webhooks/nuvemshop/`. Runtime is Node 22, Next.js 16/React 19, TypeScript, and Docker; `Dockerfile` runs the application while `Dockerfile.worker` supports worker execution. Deployment options include Vercel plus a WhatsApp VPS, or the self-host stack orchestrated by `docker-compose.yml` and `hostgator-setup-kit/install.sh`. External services include Supabase, WAHA, AI providers/AI Gateway, Upstash Redis, Resend, Sentry, and Nuvemshop.

Main entry points: [`lib/channels/index.ts`](https://github.com/melgarafael/deskcommcrm/blob/main/lib/channels/index.ts) (Channel gateway), [`lib/agent-engine/agent/inbound-turn.ts`](https://github.com/melgarafael/deskcommcrm/blob/main/lib/agent-engine/agent/inbound-turn.ts) (Agent turn engine), [`lib/automation/engine.ts`](https://github.com/melgarafael/deskcommcrm/blob/main/lib/automation/engine.ts) (Automation engine), [`lib/supabase/server.ts`](https://github.com/melgarafael/deskcommcrm/blob/main/lib/supabase/server.ts) (Supabase clients)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_next["Next.js application"]
  node_tenant_ui["Tenant CRM UI<br/>Next.js routes"]
  node_admin_ui["Platform admin UI<br/>Next.js routes"]
  node_crm_apis["CRM APIs<br/>route handlers"]
  node_inbox_realtime["Inbox realtime hooks<br/>React hooks"]
  node_provider_webhooks["WhatsApp webhooks<br/>route handlers<br/>[route.ts]"]
  node_ai_api_ui["AI management<br/>API and UI"]
  node_capture_webhook["Capture webhook<br/>route handler<br/>[route.ts]"]
  node_mcp_endpoint["MCP endpoint<br/>route handler<br/>[route.ts]"]
end

subgraph group_core["Domain services"]
  node_supabase_clients["Supabase clients<br/>data access<br/>[server.ts]"]
  node_authz["Authorization<br/>access control<br/>[require-role.ts]"]
  node_channel_gateway["Channel gateway<br/>adapter registry<br/>[index.ts]"]
  node_agent_turn{{"Agent turn engine<br/>AI orchestration<br/>[inbound-turn.ts]"}}
  node_llm_runner["LLM runner<br/>provider runtime<br/>[run-model-call.ts]"]
  node_guardrails["AI guardrails<br/>policy enforcement"]
  node_audit["Audit log<br/>governance service<br/>[index.ts]"]
end

subgraph group_async["Workers and automation"]
  node_automation_engine{{"Automation engine<br/>event rules<br/>[engine.ts]"}}
  node_event_drain["Event-log drain<br/>scheduled worker<br/>[drain.ts]"]
  node_followup_engine{{"Follow-up engine<br/>flow executor<br/>[engine.ts]"}}
  node_media_workers["Media workers<br/>background workers"]
  node_rag_indexer["RAG indexer<br/>background worker<br/>[rag-indexer.ts]"]
  node_agent_worker["Agent worker<br/>background worker<br/>[main.ts]"]
end

subgraph group_external["External platform"]
  node_supabase[("Supabase<br/>Postgres/Auth/Storage/Realtime<br/>[baseline.sql]")]
  node_whatsapp_providers["WAHA and Meta Cloud<br/>WhatsApp providers"]
  node_ai_providers["AI providers<br/>LLM services"]
end

node_tenant_ui -->|"CRM operations"| node_crm_apis
node_tenant_ui -->|"subscribes"| node_inbox_realtime
node_inbox_realtime -->|"Realtime"| node_supabase
node_admin_ui -->|"admin access"| node_authz
node_crm_apis -->|"authorizes"| node_authz
node_crm_apis -->|"persists"| node_supabase_clients
node_supabase_clients -->|"uses"| node_supabase
node_provider_webhooks -->|"normalizes inbound"| node_channel_gateway
node_whatsapp_providers -->|"webhook delivery"| node_provider_webhooks
node_channel_gateway -->|"stores messages"| node_supabase_clients
node_crm_apis -->|"outbound messages"| node_channel_gateway
node_channel_gateway -->|"provider calls"| node_whatsapp_providers
node_provider_webhooks -.->|"inbound turn"| node_agent_worker
node_agent_worker -->|"executes"| node_agent_turn
node_agent_turn -->|"model call"| node_llm_runner
node_llm_runner -->|"inference"| node_ai_providers
node_agent_turn -->|"checks actions"| node_guardrails
node_agent_turn -->|"send or handoff"| node_channel_gateway
node_agent_turn -->|"records decisions"| node_audit
node_ai_api_ui -->|"configures agents"| node_supabase_clients
node_rag_indexer -->|"writes embeddings"| node_supabase
node_event_drain -->|"drained events"| node_automation_engine
node_capture_webhook -->|"capture event"| node_automation_engine
node_automation_engine -->|"CRM actions"| node_crm_apis
node_automation_engine -->|"message actions"| node_channel_gateway
node_followup_engine -->|"flow actions"| node_crm_apis
node_followup_engine -->|"follow-up sends"| node_channel_gateway
node_media_workers -->|"media storage"| node_supabase
node_mcp_endpoint -->|"governed tools"| node_crm_apis
node_mcp_endpoint -->|"audits tool use"| node_audit

click node_inbox_realtime "https://github.com/melgarafael/deskcommcrm/blob/main/hooks/inbox/useConversationsRealtime.ts"
click node_provider_webhooks "https://github.com/melgarafael/deskcommcrm/blob/main/app/api/v1/webhooks/waha/%5Btoken%5D/route.ts"
click node_capture_webhook "https://github.com/melgarafael/deskcommcrm/blob/main/app/api/v1/webhooks/in/%5Btoken%5D/route.ts"
click node_mcp_endpoint "https://github.com/melgarafael/deskcommcrm/blob/main/app/api/mcp/route.ts"
click node_supabase_clients "https://github.com/melgarafael/deskcommcrm/blob/main/lib/supabase/server.ts"
click node_authz "https://github.com/melgarafael/deskcommcrm/blob/main/lib/auth/require-role.ts"
click node_channel_gateway "https://github.com/melgarafael/deskcommcrm/blob/main/lib/channels/index.ts"
click node_agent_turn "https://github.com/melgarafael/deskcommcrm/blob/main/lib/agent-engine/agent/inbound-turn.ts"
click node_llm_runner "https://github.com/melgarafael/deskcommcrm/blob/main/lib/agent-engine/edge/llm/run-model-call.ts"
click node_audit "https://github.com/melgarafael/deskcommcrm/blob/main/lib/audit/index.ts"
click node_automation_engine "https://github.com/melgarafael/deskcommcrm/blob/main/lib/automation/engine.ts"
click node_event_drain "https://github.com/melgarafael/deskcommcrm/blob/main/lib/event-log/drain.ts"
click node_followup_engine "https://github.com/melgarafael/deskcommcrm/blob/main/lib/followup/engine.ts"
click node_media_workers "https://github.com/melgarafael/deskcommcrm/blob/main/workers/media-persist-worker.ts"
click node_rag_indexer "https://github.com/melgarafael/deskcommcrm/blob/main/workers/rag-indexer.ts"
click node_agent_worker "https://github.com/melgarafael/deskcommcrm/blob/main/workers/agent-worker/main.ts"
click node_supabase "https://github.com/melgarafael/deskcommcrm/blob/main/supabase/baseline.sql"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_tenant_ui,node_admin_ui,node_crm_apis,node_inbox_realtime,node_provider_webhooks,node_ai_api_ui,node_capture_webhook,node_mcp_endpoint toneBlue
class node_supabase_clients,node_authz,node_channel_gateway,node_agent_turn,node_llm_runner,node_guardrails,node_audit toneAmber
class node_automation_engine,node_event_drain,node_followup_engine,node_media_workers,node_rag_indexer,node_agent_worker toneMint
class node_supabase,node_whatsapp_providers,node_ai_providers toneRose
```

## Components

### Next.js application

Tenant, admin, API, webhook, cron, and MCP surfaces.

- **Tenant CRM UI**: Next.js routes · Inbox, contacts, pipelines, teams, metrics, and settings.
- **Platform admin UI**: Next.js routes
- **CRM APIs**: route handlers · Canonical conversation, lead, and contact operations.
- [Inbox realtime hooks](https://github.com/melgarafael/deskcommcrm/blob/main/hooks/inbox/useConversationsRealtime.ts): React hooks · `hooks/inbox/useConversationsRealtime.ts`
- [WhatsApp webhooks](https://github.com/melgarafael/deskcommcrm/blob/main/app/api/v1/webhooks/waha/%5Btoken%5D/route.ts): route handlers · Provider ingress for WAHA and Meta Cloud. · `app/api/v1/webhooks/waha/[token]/route.ts`
- **AI management**: API and UI · Agent configuration and operator workflows.
- [Capture webhook](https://github.com/melgarafael/deskcommcrm/blob/main/app/api/v1/webhooks/in/%5Btoken%5D/route.ts): route handler · Public tenant event ingress. · `app/api/v1/webhooks/in/[token]/route.ts`
- [MCP endpoint](https://github.com/melgarafael/deskcommcrm/blob/main/app/api/mcp/route.ts): route handler · `app/api/mcp/route.ts`

### Domain services

Shared CRM, channel, AI, and governance logic.

- [Supabase clients](https://github.com/melgarafael/deskcommcrm/blob/main/lib/supabase/server.ts): data access · Separate server, browser, and privileged clients. · `lib/supabase/server.ts`
- [Authorization](https://github.com/melgarafael/deskcommcrm/blob/main/lib/auth/require-role.ts): access control · Tenant role and platform-admin enforcement. · `lib/auth/require-role.ts`
- [Channel gateway](https://github.com/melgarafael/deskcommcrm/blob/main/lib/channels/index.ts): adapter registry · Normalizes WhatsApp providers and capabilities. · `lib/channels/index.ts`
- [Agent turn engine](https://github.com/melgarafael/deskcommcrm/blob/main/lib/agent-engine/agent/inbound-turn.ts): AI orchestration · Resolves an eligible agent and executes inbound turns. · `lib/agent-engine/agent/inbound-turn.ts`
- [LLM runner](https://github.com/melgarafael/deskcommcrm/blob/main/lib/agent-engine/edge/llm/run-model-call.ts): provider runtime · `lib/agent-engine/edge/llm/run-model-call.ts`
- **AI guardrails**: policy enforcement · Controls sends, disclosure, LGPD, windows, and promises.
- [Audit log](https://github.com/melgarafael/deskcommcrm/blob/main/lib/audit/index.ts): governance service · `lib/audit/index.ts`

### Workers and automation

Deferred processing and scheduled control flows.

- [Automation engine](https://github.com/melgarafael/deskcommcrm/blob/main/lib/automation/engine.ts): event rules · Mutates CRM, sends messages, or invokes webhooks. · `lib/automation/engine.ts`
- [Event-log drain](https://github.com/melgarafael/deskcommcrm/blob/main/lib/event-log/drain.ts): scheduled worker · Drains recorded domain events into automation. · `lib/event-log/drain.ts`
- [Follow-up engine](https://github.com/melgarafael/deskcommcrm/blob/main/lib/followup/engine.ts): flow executor · Executes published follow-up graphs. · `lib/followup/engine.ts`
- [Media workers](https://github.com/melgarafael/deskcommcrm/blob/main/workers/media-persist-worker.ts): background workers · Persist, derive, transcribe, and clean media. · `workers/media-persist-worker.ts`
- [RAG indexer](https://github.com/melgarafael/deskcommcrm/blob/main/workers/rag-indexer.ts): background worker · Ingests knowledge and creates embeddings. · `workers/rag-indexer.ts`
- [Agent worker](https://github.com/melgarafael/deskcommcrm/blob/main/workers/agent-worker/main.ts): background worker · `workers/agent-worker/main.ts`

### External platform

Persistence and provider dependencies.

- [Supabase](https://github.com/melgarafael/deskcommcrm/blob/main/supabase/baseline.sql): Postgres/Auth/Storage/Realtime · RLS-backed tenant isolation and vector storage. · `supabase/baseline.sql`
- **WAHA and Meta Cloud**: WhatsApp providers
- **AI providers**: LLM services · AI Gateway-compatible model providers.

## Connections

- Tenant CRM UI → CRM APIs: CRM operations
- Tenant CRM UI → Inbox realtime hooks: subscribes
- Inbox realtime hooks → Supabase: Realtime
- Platform admin UI → Authorization: admin access
- CRM APIs → Authorization: authorizes
- CRM APIs → Supabase clients: persists
- Supabase clients → Supabase: uses
- WhatsApp webhooks → Channel gateway: normalizes inbound
- WAHA and Meta Cloud → WhatsApp webhooks: webhook delivery
- Channel gateway → Supabase clients: stores messages
- CRM APIs → Channel gateway: outbound messages
- Channel gateway → WAHA and Meta Cloud: provider calls
- WhatsApp webhooks → Agent worker: inbound turn
- Agent worker → Agent turn engine: executes
- Agent turn engine → LLM runner: model call
- LLM runner → AI providers: inference
- Agent turn engine → AI guardrails: checks actions
- Agent turn engine → Channel gateway: send or handoff
- Agent turn engine → Audit log: records decisions
- AI management → Supabase clients: configures agents
- RAG indexer → Supabase: writes embeddings
- Event-log drain → Automation engine: drained events
- Capture webhook → Automation engine: capture event
- Automation engine → CRM APIs: CRM actions
- Automation engine → Channel gateway: message actions
- Follow-up engine → CRM APIs: flow actions
- Follow-up engine → Channel gateway: follow-up sends
- Media workers → Supabase: media storage
- MCP endpoint → CRM APIs: governed tools
- MCP endpoint → Audit log: audits tool use
