# Chatwoot Public — Clean-Room MIT Helpdesk + Enterprise Overlay + AI Bot + Migration Suite — Complete AI & LLM Reference Corpus (`llms-full.txt`)
- Repository: https://github.com/mohan-n-swamy/chatwoot-public
- Web Discovery URL: https://mohan-n-swamy.github.io/repos/chatwoot-public/
- License: MIT
- Keywords: chatwoot, self-hosted, customer-support, helpdesk, sla-management, rbac, audit-log, saml-sso, whatsapp, omnichannel, ruby-on-rails, open-source
---
## File: `AI-README.md` — AI-README.md
---
repo: "mohan-n-swamy/chatwoot-public"
title: "Chatwoot Public — Clean-Room MIT Helpdesk + Enterprise Overlay + AI Bot + Migration Suite"
license: "MIT"
keywords: [chatwoot, self-hosted, customer-support, helpdesk, sla-management, rbac, audit-log, saml-sso, whatsapp, omnichannel, ruby-on-rails, open-source]
capabilities:
- "**Track A — Configuration Audit Log (`Overlay::AuditLogsController`):** Immutable JSONB before/after audit trail across 13 models excluding password/token fields."
- "**Track B — 31-Permission Custom RBAC (`Overlay::CustomRole` & `Overlay::RolePermissions`):** PostgreSQL array permissions with 5 seed roles (`admin`, `agent`, `escalation_lead`, `billing_only`, `auditor`)."
- "**Track C — Business-Hours SLA Engine (`Overlay::Sla::*`):** `AsyncDispatcher`-wired `SlaListener` + Sidekiq cron batch breach evaluator (`frt_due_at`, `nrt_due_at`, `rt_due_at`) + outbound webhooks."
- "**Track D — Hardened SAML 2.0 SSO (`Overlay::SamlSessionsController`):** Okta, Entra ID, and Google Workspace SSO via MIT `omniauth-saml` with `reset_session`, RelayState tenant guard, and Nokogiri `nonet` XXE defense."
- "**Track E & F — Agent Capacity Routing & Scheduled Rules:** Per-agent/per-inbox `max_open_conversations` caps and cron-evaluated `Overlay::ScheduledRule` automations."
- "**Bundled Native Chatwoot AI Bot (`chatwoot-bot/`):** Production FastAPI AgentBot with HMAC verification, Redis `SETNX` locks, PII `AUTH_GATE`, and 161 unit/integration tests."
- "**Complete Migration Ops & Portable Rebase Kit (`migration-toolkit/`, `portable-overlay/`, `infra/self-host/`, `tools/ci/`):** Legacy ticket/config exporters, idempotent importer, standalone overlay patch tree, and 10 track specs."
when_to_use:
- "A unified, 100% MIT-licensed self-hosted Chatwoot Community Edition platform combining: (1) Chatwoot CE with the 6-track clean-room `Overlay::` governance pack (Audit Logs, 31-Permission Custom RBAC, Business-Hours SLA Engine, Hardened SAML 2.0 SSO, Agent Capacity Routing, Scheduled Rules), (2) a native FastAPI `chatwoot-bot/` AI AgentBot, (3) a full Helpdesk Migration Toolkit (`freshworks-export` + `chatwoot-import`), and (4) a standalone `portable-overlay/` rebase kit and self-host Nginx/Docker stack."
- "Organizations outgrowing per-seat SaaS helpdesks (Freshchat, Freshdesk, Zendesk, Intercom) want to self-host Chatwoot under the MIT license, but need SAML SSO, custom roles, business-hours SLAs, agent capacity caps, audit logs, legacy ticket/config migration scripts, and a production AI webhook bot — with strict legal verification that zero proprietary `enterprise/` code exists in their image."
inputs_required:
- "FRONTEND_URL: Public base URL of your self-hosted Chatwoot instance"
- "POSTGRES_HOST: PostgreSQL 16+ host"
- "REDIS_URL: Redis URL for Sidekiq queues, ActionCable, and bot locks"
- "SECRET_KEY_BASE: Rails secret key base for session and token signing"
- "OVERLAY_AUDIT_MAX_AUDITS_PER_RECORD: Maximum retained audit snapshots per configuration record"
- "OVERLAY_SLA_CRON_MINUTES: Evaluation interval for Sidekiq batch SLA breach detection"
- "OVERLAY_DEFAULT_AGENT_MAX_OPEN_CONVERSATIONS: Default per-agent open conversation cap for capacity auto-assignment"
quickstart:
- "docker compose -f docker-compose.production.yaml build # builds locally from clean-room MIT tree (zero enterprise/)"
- "docker compose -f docker-compose.production.yaml up -d"
- "docker compose -f docker-compose.production.yaml exec rails bundle exec rails db:chatwoot_prepare"
- "docker compose -f docker-compose.production.yaml exec rails bundle exec rake overlay:seed_roles"
- "pytest -q tests_overlay/ migration-toolkit/freshworks-export/tests/ && PYTHONPATH=chatwoot-bot pytest -q chatwoot-bot/tests/"
---
# Chatwoot Public — Clean-Room MIT Helpdesk + Enterprise Overlay + AI Bot + Migration Suite — Machine-Readable Agent Guide
A unified, 100% MIT-licensed self-hosted Chatwoot Community Edition platform combining: (1) Chatwoot CE with the 6-track clean-room `Overlay::` governance pack (Audit Logs, 31-Permission Custom RBAC, Business-Hours SLA Engine, Hardened SAML 2.0 SSO, Agent Capacity Routing, Scheduled Rules), (2) a native FastAPI `chatwoot-bot/` AI AgentBot, (3) a full Helpdesk Migration Toolkit (`freshworks-export` + `chatwoot-import`), and (4) a standalone `portable-overlay/` rebase kit and self-host Nginx/Docker stack.
Organizations outgrowing per-seat SaaS helpdesks (Freshchat, Freshdesk, Zendesk, Intercom) want to self-host Chatwoot under the MIT license, but need SAML SSO, custom roles, business-hours SLAs, agent capacity caps, audit logs, legacy ticket/config migration scripts, and a production AI webhook bot — with strict legal verification that zero proprietary `enterprise/` code exists in their image.
Key modules and entry points in this repository:
- `OVERLAY.md & portable-overlay/`: Complete ADRs plus standalone portable `Overlay::` patch kit and `setup-upstream-fork.sh`
- `app/controllers/api/v1/accounts/overlay/`: REST controllers for `audit_logs`, `custom_roles`, `sla_policies`, `business_hours_configs`, `saml_settings`, `capacity`, and `scheduled_rules`
- `app/controllers/overlay/ & app/services/overlay/`: Hardened SAML 2.0 controllers, SLA `BusinessTimeCalculator`, `SlaListener`, capacity selector, and role manager
- `spec/overlay/`: 160+ RSpec model, controller, policy, security, and `sla_dispatch_spec.rb` integration specs
- `chatwoot-bot/`: Native FastAPI Chatwoot AgentBot (`src/webhook`, `src/chatwoot_client`, `src/domain`, `deploy/`, 161 pytests)
- `migration-toolkit/freshworks-export/ & chatwoot-import/`: Ticket/contact/macro/rule exporters, E.164 transformers, and idempotent Chatwoot importer
- `infra/self-host/ & tools/ci/`: Self-host Docker Compose + Nginx config and 10 feature-track specification & verification loops
- `docs/migration-and-specs/`: Upstream rebase playbook, helpdesk migration playbook, clean-room licensing guide, and rollout specs
Every organization-specific value enters through `.env` (copied from `.env.example`) or external adapter files. No source edit is needed to change organization names, endpoints, database URLs, webhook secrets, or thresholds.
When a human asks an AI coding agent to deploy or adapt `chatwoot-public` into their stack:
1. Copy `.env.example` to `.env`, set `FRONTEND_URL`, `SECRET_KEY_BASE`, `POSTGRES_*`, and `REDIS_URL`, and build locally with `docker compose -f docker-compose.production.yaml build`.
2. Run `rails db:chatwoot_prepare` and `rake overlay:seed_roles` to initialize the 14 `overlay_*` tables and 5 RBAC role presets.
3. Deploy `chatwoot-bot/` via `chatwoot-bot/deploy/docker-compose.yml` and register its `/webhook` URL as an AgentBot in Chatwoot.
4. If migrating from Freshdesk/Freshchat, populate `migration-toolkit/freshworks-export/.env` and `chatwoot-import/.env` and follow `docs/HELPDESK-MIGRATION-PLAYBOOK.md`.
- Product Requirements: `docs/PRD.md`
- Working-Backwards PR-FAQ: `docs/PR-FAQ.md`
- High-Level Architecture: `docs/HLD.md`
- Low-Level Interfaces & Runbook: `docs/LLD.md`
- Coding Agent Rules: `AGENTS.md`
---
## File: `.env.example` — Environment Contract (.env.example)
```ini
# Learn about the various environment variables at
# https://www.chatwoot.com/docs/self-hosted/configuration/environment-variables/#rails-production-variables
# Used to verify the integrity of signed cookies. so ensure a secure value is set
# SECRET_KEY_BASE should be alphanumeric. Avoid special characters or symbols.
# Use `rake secret` to generate this variable
SECRET_KEY_BASE=replace_with_lengthy_secure_hex
# Active Record Encryption keys (required for MFA/2FA functionality)
# Generate these keys by running: rails db:encryption:init
# IMPORTANT: Use different keys for each environment (development, staging, production)
# ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY=
# ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY=
# ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT=
# Replace with the URL you are planning to use for your app
FRONTEND_URL=http://0.0.0.0:3000
# To use a dedicated URL for help center pages
# HELPCENTER_URL=http://0.0.0.0:3000
# If the variable is set, all non-authenticated pages would fallback to the default locale.
# Whenever a new account is created, the default language will be DEFAULT_LOCALE instead of en
# DEFAULT_LOCALE=en
# If you plan to use CDN for your assets, set Asset CDN Host
ASSET_CDN_HOST=
# Force all access to the app over SSL, default is set to false
FORCE_SSL=false
# This lets you control new sign ups on your chatwoot installation
# true : default option, allows sign ups
# false : disables all the end points related to sign ups
# api_only: disables the UI for signup, but you can create sign ups via the account apis
ENABLE_ACCOUNT_SIGNUP=false
# Redis config
# specify the configs via single URL or individual variables
# ref: https://www.iana.org/assignments/uri-schemes/prov/redis
# You can also use the following format for the URL: redis://:password@host:port/db_number
REDIS_URL=redis://redis:6379
# If you are using docker-compose, set this variable's value to be any string,
# which will be the password for the redis service running inside the docker-compose
# to make it secure
REDIS_PASSWORD=
# Redis Sentinel can be used by passing list of sentinel host and ports e,g. sentinel_host1:port1,sentinel_host2:port2
REDIS_SENTINELS=
# Redis sentinel master name is required when using sentinel, default value is "mymaster".
# You can find list of master using "SENTINEL masters" command
REDIS_SENTINEL_MASTER_NAME=
# By default Chatwoot will pass REDIS_PASSWORD as the password value for sentinels
# Use the following environment variable to customize passwords for sentinels.
# Use empty string if sentinels are configured with out passwords
# REDIS_SENTINEL_PASSWORD=
# Redis premium breakage in heroku fix
# enable the following configuration
# ref: https://github.com/chatwoot/chatwoot/issues/2420
# REDIS_OPENSSL_VERIFY_MODE=none
# Postgres Database config variables
# You can leave POSTGRES_DATABASE blank. The default name of
# the database in the production environment is chatwoot_production
# POSTGRES_DATABASE=
POSTGRES_HOST=postgres
POSTGRES_USERNAME=postgres
POSTGRES_PASSWORD=
RAILS_ENV=development
# Changes the Postgres query timeout limit. The default is 14 seconds. Modify only when required.
# POSTGRES_STATEMENT_TIMEOUT=14s
RAILS_MAX_THREADS=5
# The email from which all outgoing emails are sent
# could user either `email@yourdomain.com` or `BrandName `
MAILER_SENDER_EMAIL=Chatwoot
#SMTP domain key is set up for HELO checking
SMTP_DOMAIN=chatwoot.com
# Set the value to "mailhog" if using docker-compose for development environments,
# Set the value as "localhost" or your SMTP address in other environments
# If SMTP_ADDRESS is empty, Chatwoot would try to use sendmail(postfix)
SMTP_ADDRESS=
SMTP_PORT=1025
SMTP_USERNAME=
SMTP_PASSWORD=
# plain,login,cram_md5
SMTP_AUTHENTICATION=
SMTP_ENABLE_STARTTLS_AUTO=true
# Can be: 'none', 'peer', 'client_once', 'fail_if_no_peer_cert', see http://api.rubyonrails.org/classes/ActionMailer/Base.html
SMTP_OPENSSL_VERIFY_MODE=peer
# Comment out the following environment variables if required by your SMTP server
# SMTP_TLS=
# SMTP_SSL=
# SMTP_OPEN_TIMEOUT
# SMTP_READ_TIMEOUT
# Mail Incoming
# This is the domain set for the reply emails when conversation continuity is enabled
MAILER_INBOUND_EMAIL_DOMAIN=
# Maximum time in seconds to process a single IMAP email
# EMAIL_PROCESSING_TIMEOUT_SECONDS=60
# Set this to the appropriate ingress channel with regards to incoming emails
# Possible values are :
# relay for Exim, Postfix, Qmail
# mailgun for Mailgun
# mandrill for Mandrill
# postmark for Postmark
# sendgrid for Sendgrid
# ses for Amazon SES
RAILS_INBOUND_EMAIL_SERVICE=
# Use one of the following based on the email ingress service
# Ref: https://edgeguides.rubyonrails.org/action_mailbox_basics.html
# Set this to a password of your choice and use it in the Inbound webhook
RAILS_INBOUND_EMAIL_PASSWORD=
MAILGUN_INGRESS_SIGNING_KEY=
MANDRILL_INGRESS_API_KEY=
# SNS topic ARN for ActionMailbox (format: arn:aws:sns:region:account-id:topic-name)
# Configure only if the rails_inbound_email_service = ses
ACTION_MAILBOX_SES_SNS_TOPIC=
# Creating Your Inbound Webhook Instructions for Postmark and Sendgrid:
# Inbound webhook URL format:
# https://actionmailbox:[YOUR_RAILS_INBOUND_EMAIL_PASSWORD]@[YOUR_CHATWOOT_DOMAIN.COM]/rails/action_mailbox/[RAILS_INBOUND_EMAIL_SERVICE]/inbound_emails
# Note: Replace the values inside the brackets; do not include the brackets themselves.
# Example: https://actionmailbox:mYRandomPassword3@chatwoot.example.com/rails/action_mailbox/postmark/inbound_emails
# For Postmark
# Ensure the 'Include raw email content in JSON payload' checkbox is selected in the inbound webhook section.
# Storage
ACTIVE_STORAGE_SERVICE=local
# Amazon S3
# documentation: https://www.chatwoot.com/docs/configuring-s3-bucket-as-cloud-storage
S3_BUCKET_NAME=
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_REGION=
# Log settings
# Disable if you want to write logs to a file
RAILS_LOG_TO_STDOUT=true
LOG_LEVEL=info
LOG_SIZE=500
# Configure this environment variable if you want to use lograge instead of rails logger
#LOGRAGE_ENABLED=true
### This environment variables are only required if you are setting up social media channels
# Facebook
# documentation: https://www.chatwoot.com/docs/facebook-setup
FB_VERIFY_TOKEN=
FB_APP_SECRET=
FB_APP_ID=
# https://developers.facebook.com/docs/messenger-platform/instagram/get-started#app-dashboard
IG_VERIFY_TOKEN=
# WhatsApp (Meta)
# Used for webhook signature verification; required if using WhatsApp Cloud API
# WHATSAPP_APP_SECRET=
# Twitter
# documentation: https://www.chatwoot.com/docs/twitter-app-setup
TWITTER_APP_ID=
TWITTER_CONSUMER_KEY=
TWITTER_CONSUMER_SECRET=
TWITTER_ENVIRONMENT=
#slack integration
SLACK_CLIENT_ID=
SLACK_CLIENT_SECRET=
# Google OAuth
GOOGLE_OAUTH_CLIENT_ID=
GOOGLE_OAUTH_CLIENT_SECRET=
GOOGLE_OAUTH_CALLBACK_URL=
### Change this env variable only if you are using a custom build mobile app
## Mobile app env variables
IOS_APP_ID=L7YLMN4634.com.chatwoot.app
ANDROID_BUNDLE_ID=com.chatwoot.app
# https://developers.google.com/android/guides/client-auth (use keytool to print the fingerprint in the first section)
ANDROID_SHA256_CERT_FINGERPRINT=AC:73:8E:DE:EB:56:EA:CC:10:87:02:A7:65:37:7B:38:D4:5D:D4:53:F8:3B:FB:D3:C6:28:64:1D:AA:08:1E:D8
### Smart App Banner
# https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/PromotingAppswithAppBanners/PromotingAppswithAppBanners.html
# You can find your app-id in https://itunesconnect.apple.com
#IOS_APP_IDENTIFIER=1495796682
## Push Notification
## generate a new key value here : https://d3v.one/vapid-key-generator/
# VAPID_PUBLIC_KEY=
# VAPID_PRIVATE_KEY=
#
# for mobile apps
# FCM_SERVER_KEY=
### APM and Error Monitoring configurations
## Elastic APM
## https://www.elastic.co/guide/en/apm/agent/ruby/current/getting-started-rails.html
# ELASTIC_APM_SERVER_URL=
# ELASTIC_APM_SECRET_TOKEN=
## Sentry
# SENTRY_DSN=
## Scout
## https://scoutapm.com/docs/ruby/configuration
# SCOUT_KEY=YOURKEY
# SCOUT_NAME=YOURAPPNAME (Production)
# SCOUT_MONITOR=true
## NewRelic
# https://docs.newrelic.com/docs/agents/ruby-agent/configuration/ruby-agent-configuration/
# NEW_RELIC_LICENSE_KEY=
# Set this to true to allow newrelic apm to send logs.
# This is turned off by default.
# NEW_RELIC_APPLICATION_LOGGING_ENABLED=
## Datadog
## https://github.com/DataDog/dd-trace-rb/blob/master/docs/GettingStarted.md#environment-variables
# DD_TRACE_AGENT_URL=
# MaxMindDB API key to download GeoLite2 City database
# IP_LOOKUP_API_KEY=
## Rack Attack configuration
## To prevent and throttle abusive requests
# ENABLE_RACK_ATTACK=true
# RACK_ATTACK_LIMIT=300
# ENABLE_RACK_ATTACK_WIDGET_API=true
# Comma-separated list of trusted IPs that bypass Rack Attack throttling rules
# RACK_ATTACK_ALLOWED_IPS=127.0.0.1,::1,192.168.0.10
## SafeFetch private network access
## Keep disabled by default. Self-hosted installations can enable this to allow SafeFetch requests to private network URLs.
# SAFE_FETCH_ALLOW_PRIVATE_NETWORK=false
## Running chatwoot as an API only server
## setting this value to true will disable the frontend dashboard endpoints
# CW_API_ONLY_SERVER=false
## Development Only Config
# if you want to use letter_opener for local emails
# LETTER_OPENER=true
# meant to be used in github codespaces
# WEBPACKER_DEV_SERVER_PUBLIC=
# If you want to use official mobile app,
# the notifications would be relayed via a Chatwoot server
ENABLE_PUSH_RELAY_SERVER=true
# Stripe API key
STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=
# Set to true if you want to upload files to cloud storage using the signed url
# Make sure to follow https://edgeguides.rubyonrails.org/active_storage_overview.html#cross-origin-resource-sharing-cors-configuration on the cloud storage after setting this to true.
DIRECT_UPLOADS_ENABLED=
#MS OAUTH creds
AZURE_APP_ID=
AZURE_APP_SECRET=
## Advanced configurations
## Change these values to fine tune performance
# control the concurrency setting of sidekiq
# SIDEKIQ_CONCURRENCY=10
# Enable verbose logging each time a job is dequeued in Sidekiq
# ENABLE_SIDEKIQ_DEQUEUE_LOGGER=false
# AI powered features
## OpenAI key
# OPENAI_API_KEY=
# Housekeeping/Performance related configurations
# Set to true if you want to remove stale contact inboxes
# contact_inboxes with no conversation older than 90 days will be removed
# REMOVE_STALE_CONTACT_INBOX_JOB_STATUS=false
# REDIS_ALFRED_SIZE=10
# REDIS_VELMA_SIZE=10
# === Community Enterprise Overlay Configuration ===
FRONTEND_URL=http://localhost:3000
DEFAULT_LOCALE=en
FORCE_SSL=false
ENABLE_ACCOUNT_SIGNUP=false
REDIS_URL=redis://localhost:6379
POSTGRES_HOST=localhost
POSTGRES_USERNAME=postgres
POSTGRES_PASSWORD=postgres_dev_password
SECRET_KEY_BASE=replace_with_openssl_rand_hex_64_in_production
OVERLAY_AUDIT_MAX_AUDITS_PER_RECORD=50
OVERLAY_SLA_CRON_MINUTES=5
OVERLAY_DEFAULT_AGENT_MAX_OPEN_CONVERSATIONS=25
```
---
## File: `AGENTS.md` — AGENTS.md
# AGENTS.md — Chatwoot Public — Clean-Room MIT Helpdesk + Enterprise Overlay + AI Bot + Migration Suite
Read this file first before modifying `chatwoot-public`.
## Purpose
A unified, 100% MIT-licensed self-hosted Chatwoot Community Edition platform combining: (1) Chatwoot CE with the 6-track clean-room `Overlay::` governance pack (Audit Logs, 31-Permission Custom RBAC, Business-Hours SLA Engine, Hardened SAML 2.0 SSO, Agent Capacity Routing, Scheduled Rules), (2) a native FastAPI `chatwoot-bot/` AI AgentBot, (3) a full Helpdesk Migration Toolkit (`freshworks-export` + `chatwoot-import`), and (4) a standalone `portable-overlay/` rebase kit and self-host Nginx/Docker stack.
## Commands
```bash
docker compose -f docker-compose.production.yaml build # builds locally from clean-room MIT tree (zero enterprise/)
docker compose -f docker-compose.production.yaml up -d
docker compose -f docker-compose.production.yaml exec rails bundle exec rails db:chatwoot_prepare
docker compose -f docker-compose.production.yaml exec rails bundle exec rake overlay:seed_roles
pytest -q tests_overlay/ migration-toolkit/freshworks-export/tests/ && PYTHONPATH=chatwoot-bot pytest -q chatwoot-bot/tests/
```
## Module Map
- `OVERLAY.md & portable-overlay/`: Complete ADRs plus standalone portable `Overlay::` patch kit and `setup-upstream-fork.sh`
- `app/controllers/api/v1/accounts/overlay/`: REST controllers for `audit_logs`, `custom_roles`, `sla_policies`, `business_hours_configs`, `saml_settings`, `capacity`, and `scheduled_rules`
- `app/controllers/overlay/ & app/services/overlay/`: Hardened SAML 2.0 controllers, SLA `BusinessTimeCalculator`, `SlaListener`, capacity selector, and role manager
- `spec/overlay/`: 160+ RSpec model, controller, policy, security, and `sla_dispatch_spec.rb` integration specs
- `chatwoot-bot/`: Native FastAPI Chatwoot AgentBot (`src/webhook`, `src/chatwoot_client`, `src/domain`, `deploy/`, 161 pytests)
- `migration-toolkit/freshworks-export/ & chatwoot-import/`: Ticket/contact/macro/rule exporters, E.164 transformers, and idempotent Chatwoot importer
- `infra/self-host/ & tools/ci/`: Self-host Docker Compose + Nginx config and 10 feature-track specification & verification loops
- `docs/migration-and-specs/`: Upstream rebase playbook, helpdesk migration playbook, clean-room licensing guide, and rollout specs
## Invariants
1. Keep all organization names, credentials, domains, and thresholds in `.env` or external config files. Never hardcode company names, host IPs, or secrets in source files.
2. Deterministic business logic belongs in code and lookup tables, not inside LLM prompts.
3. Update `docs/HLD.md`, `docs/LLD.md`, and `.env.example` in the same commit whenever an interface or environment variable changes.
4. Run the repository smoke check and secret scan before opening a pull request.
---
## File: `docs/PRD.md` — Product Requirements Document (docs/PRD.md)
# Product Requirements Document — Chatwoot Public — Clean-Room MIT Helpdesk + Enterprise Overlay + AI Bot + Migration Suite
A unified, 100% MIT-licensed self-hosted Chatwoot Community Edition platform combining: (1) Chatwoot CE with the 6-track clean-room `Overlay::` governance pack (Audit Logs, 31-Permission Custom RBAC, Business-Hours SLA Engine, Hardened SAML 2.0 SSO, Agent Capacity Routing, Scheduled Rules), (2) a native FastAPI `chatwoot-bot/` AI AgentBot, (3) a full Helpdesk Migration Toolkit (`freshworks-export` + `chatwoot-import`), and (4) a standalone `portable-overlay/` rebase kit and self-host Nginx/Docker stack.
## 1. Problem
Organizations outgrowing per-seat SaaS helpdesks (Freshchat, Freshdesk, Zendesk, Intercom) want to self-host Chatwoot under the MIT license, but need SAML SSO, custom roles, business-hours SLAs, agent capacity caps, audit logs, legacy ticket/config migration scripts, and a production AI webhook bot — with strict legal verification that zero proprietary `enterprise/` code exists in their image.
## 2. Users and Jobs-to-be-Done
| Persona | Job-to-be-Done |
|---|---|
| VP Engineering / Support Ops Lead | Replace $50K-$250K/yr per-seat SaaS helpdesk spend with a complete self-hosted omnichannel inbox, AI triage bot, SAML SSO, SLAs, custom RBAC, and audit logs. |
| Security & Legal Compliance Reviewer | Verify deterministically that `enterprise/` is absent and every governance module (`Overlay::*`) uses MIT gems (`audited`, `omniauth-saml`) hardened against XXE and session fixation. |
| Migration & Platform Engineer | Export tickets, contacts, groups, macros, and rules from Freshworks, import idempotently into Chatwoot, deploy via `infra/self-host/`, and rebase cleanly on future upstream releases using `portable-overlay/`. |
## 3. Core Capabilities
- **Track A — Configuration Audit Log (`Overlay::AuditLogsController`):** Immutable JSONB before/after audit trail across 13 models excluding password/token fields.
- **Track B — 31-Permission Custom RBAC (`Overlay::CustomRole` & `Overlay::RolePermissions`):** PostgreSQL array permissions with 5 seed roles (`admin`, `agent`, `escalation_lead`, `billing_only`, `auditor`).
- **Track C — Business-Hours SLA Engine (`Overlay::Sla::*`):** `AsyncDispatcher`-wired `SlaListener` + Sidekiq cron batch breach evaluator (`frt_due_at`, `nrt_due_at`, `rt_due_at`) + outbound webhooks.
- **Track D — Hardened SAML 2.0 SSO (`Overlay::SamlSessionsController`):** Okta, Entra ID, and Google Workspace SSO via MIT `omniauth-saml` with `reset_session`, RelayState tenant guard, and Nokogiri `nonet` XXE defense.
- **Track E & F — Agent Capacity Routing & Scheduled Rules:** Per-agent/per-inbox `max_open_conversations` caps and cron-evaluated `Overlay::ScheduledRule` automations.
- **Bundled Native Chatwoot AI Bot (`chatwoot-bot/`):** Production FastAPI AgentBot with HMAC verification, Redis `SETNX` locks, PII `AUTH_GATE`, and 161 unit/integration tests.
- **Complete Migration Ops & Portable Rebase Kit (`migration-toolkit/`, `portable-overlay/`, `infra/self-host/`, `tools/ci/`):** Legacy ticket/config exporters, idempotent importer, standalone overlay patch tree, and 10 track specs.
## 4. Configurable Inputs
Adopters configure the system for their own organization without editing core application logic:
| Variable | Default / Example | Purpose |
|---|---|---|
| `FRONTEND_URL` | `https://support.example.org` | Public base URL of your self-hosted Chatwoot instance |
| `POSTGRES_HOST` | `postgres` | PostgreSQL 16+ host |
| `REDIS_URL` | `redis://redis:6379` | Redis URL for Sidekiq queues, ActionCable, and bot locks |
| `SECRET_KEY_BASE` | `openssl_rand_hex_64` | Rails secret key base for session and token signing |
| `OVERLAY_AUDIT_MAX_AUDITS_PER_RECORD` | `50` | Maximum retained audit snapshots per configuration record |
| `OVERLAY_SLA_CRON_MINUTES` | `5` | Evaluation interval for Sidekiq batch SLA breach detection |
| `OVERLAY_DEFAULT_AGENT_MAX_OPEN_CONVERSATIONS` | `25` | Default per-agent open conversation cap for capacity auto-assignment |
## 5. Phasing and Stability Exit Criteria
1. **Phase 1 (Local Synthetic Run):** Clone the repository, copy `.env.example` to `.env`, and run the quickstart commands against synthetic seed data. Exit criterion: smoke checks pass with zero external credentials.
2. **Phase 2 (Read-Only Shadow Wiring):** Connect read-only credentials or webhook listeners in shadow/dry-run mode. Exit criterion: 100 consecutive events or queries reconcile cleanly against source records.
3. **Phase 3 (Production Cutover):** Enable live writes, alerts, or routing behind bounded retry and idempotency guards.
## 6. Non-Goals
- Shipping organization-specific business rules hardcoded in application source.
- Storing credentials, personal customer records, or tenant URLs inside version control.
- Replacing deterministic validation or arithmetic with unconstrained model prompts.
---
## File: `docs/PR-FAQ.md` — Working-Backwards PR-FAQ (docs/PR-FAQ.md)
# Working-Backwards PR-FAQ — Chatwoot Public — Clean-Room MIT Helpdesk + Enterprise Overlay + AI Bot + Migration Suite
**Release Summary:** `chatwoot-public` gives engineering and operations teams a self-hosted, open-source implementation of Chatwoot Public — Clean-Room MIT Helpdesk + Enterprise Overlay + AI Bot + Migration Suite that configures via `.env` and runs on standard infrastructure in minutes.
## Press Release
Operations and engineering teams often rebuild the same internal workflows behind closed doors or pay per-seat SaaS markups for rigid tools that cannot match their field reality. `chatwoot-public` open-sources a battle-tested implementation of Chatwoot Public — Clean-Room MIT Helpdesk + Enterprise Overlay + AI Bot + Migration Suite, stripped of all single-company assumptions and packaged with clear adapter boundaries, synthetic demo data, and machine-readable agent documentation.
Any team can fork `chatwoot-public`, supply their own `.env` inputs and taxonomy config, and deploy locally or in production with Docker, Python, or Node. AI coding assistants such as Claude Code, Codex, and Cursor can read `AI-README.md` and `llms.txt` to wire custom ERP, CRM, or warehouse adapters in a single session.
## External Adopter FAQ
**Q1: How long does it take to run locally after cloning?**
Under five minutes. Copy `.env.example` to `.env` and run the quickstart commands in `README.md`. Synthetic fixtures let you inspect the workflow before connecting live credentials.
**Q2: Do I need to rewrite source files to use my own company name, channels, or rules?**
No. Organization names, endpoints, thresholds, and credentials sit in `.env` and declarative config files. External system specifics live behind narrow adapter modules documented in `docs/LLD.md`.
**Q3: What license governs this repository?**
MIT License. You can fork, modify, self-host, and use it commercially without restriction.
## Internal Engineering & Security FAQ
**Q4: How do we prevent tenant or employer data from ever entering a public fork?**
The repository starts from a clean git history, excludes raw exports and binary dumps, validates every commit through `gitleaks`, and ships only synthetic fixtures.
**Q5: What happens when an upstream API or model provider is slow or unavailable?**
Inbound webhooks persist raw payloads before processing, outbound writes carry idempotency keys with bounded exponential backoff, and model-backed paths fail open to deterministic rules or explicit human queues.
---
## File: `docs/HLD.md` — High-Level Design (docs/HLD.md)
# High-Level Design (HLD) — Chatwoot Public — Clean-Room MIT Helpdesk + Enterprise Overlay + AI Bot + Migration Suite
A unified, 100% MIT-licensed self-hosted Chatwoot Community Edition platform combining: (1) Chatwoot CE with the 6-track clean-room `Overlay::` governance pack (Audit Logs, 31-Permission Custom RBAC, Business-Hours SLA Engine, Hardened SAML 2.0 SSO, Agent Capacity Routing, Scheduled Rules), (2) a native FastAPI `chatwoot-bot/` AI AgentBot, (3) a full Helpdesk Migration Toolkit (`freshworks-export` + `chatwoot-import`), and (4) a standalone `portable-overlay/` rebase kit and self-host Nginx/Docker stack.
## 1. System Topology
```mermaid
flowchart TB
Channels["WhatsApp · Email · Web Widget · API"] --> Rails["Chatwoot CE Rails Core (MIT)"]
IdP["Okta / Entra / Google SAML 2.0"] --> Saml["Hardened Overlay::SamlCallbacksController"]
Saml --> Rails
Rails --> RBAC["Overlay::RolePermissions (31 Perms)"]
Rails --> Audit["Audited::Audit (13 Config Models)"]
Rails --> Cap["Overlay::CapacityAwareHandler"]
Rails <-->|"AgentBot HMAC Webhook"| Bot["chatwoot-bot/ (FastAPI 7-Stage AI Bot)"]
Sidekiq["Sidekiq Cron"] --> SLA["Overlay::Sla::EvaluateAppliedSlasJob"]
Sidekiq --> Rules["Overlay::ScheduledRules::EvaluateService"]
Migration["migration-toolkit/ (Export + Import)"] -->|"REST Upsert"| Rails
```
## 2. Architectural Decisions and Rejected Alternatives
| Decision | Why It Holds | Rejected Alternative |
|---|---|---|
| Combine app fork + migration-ops + AI bot + portable overlay into one repo | Gives self-hosters every piece needed to migrate, govern, automate, and rebase Chatwoot in one coherent codebase. | Splitting app, migration scripts, and bot across disconnected repos |
| Strip `enterprise/` at repository level instead of runtime flags | Guarantees `ChatwootApp.enterprise?` is structurally `false` and eliminates any legal ambiguity during Docker builds. | Pulling upstream `chatwoot/chatwoot` image and relying on feature flags |
| Isolate all custom code under `Overlay::` + keep `portable-overlay/` synced | Keeps upstream core modifications to <15 concern/listener lines so upstream security rebases stay fast. | Editing upstream controllers and models inline |
| Pre-computed SLA due timestamps + `AsyncDispatcher` listener registration | Ensures conversation/message events attach and pause SLAs in real time and Sidekiq batch sweeps detect breaches via indexed SQL. | Unwired unit-only SLA services or lazy UI checks |
## 3. Data Flow and Failure Boundaries
1. **Configuration Boundary:** Startup validates `.env` variables and declarative config schemas before accepting traffic or running scheduled jobs.
2. **Adapter Boundary:** External services (databases, chat channels, HRMS, warehouses, or LLM providers) sit behind explicit adapter modules so failures stay isolated and testable with local mocks.
3. **Observability and Audit:** State transitions and job executions emit structured logs and deterministic status records rather than mutating state silently.
## 4. Scaling Notes
- **1x to 10x load:** Single-node Docker Compose or process supervisor handles standard team workloads with indexed database queries and bounded worker concurrency.
- **First bottleneck at 10x+:** High-frequency webhook or batch ingestion queues; mitigate by separating the stateless HTTP receiver from background worker processes sharing Redis or PostgreSQL locks.
---
## File: `docs/LLD.md` — Low-Level Design & Runbook (docs/LLD.md)
# Low-Level Design (LLD) & Operations Runbook — Chatwoot Public — Clean-Room MIT Helpdesk + Enterprise Overlay + AI Bot + Migration Suite
This document defines the module responsibilities, environment contract, and operational procedures for `chatwoot-public`.
## 1. Module and File Inventory
| Path | Responsibility |
|---|---|
| `OVERLAY.md & portable-overlay/` | Complete ADRs plus standalone portable `Overlay::` patch kit and `setup-upstream-fork.sh` |
| `app/controllers/api/v1/accounts/overlay/` | REST controllers for `audit_logs`, `custom_roles`, `sla_policies`, `business_hours_configs`, `saml_settings`, `capacity`, and `scheduled_rules` |
| `app/controllers/overlay/ & app/services/overlay/` | Hardened SAML 2.0 controllers, SLA `BusinessTimeCalculator`, `SlaListener`, capacity selector, and role manager |
| `spec/overlay/` | 160+ RSpec model, controller, policy, security, and `sla_dispatch_spec.rb` integration specs |
| `chatwoot-bot/` | Native FastAPI Chatwoot AgentBot (`src/webhook`, `src/chatwoot_client`, `src/domain`, `deploy/`, 161 pytests) |
| `migration-toolkit/freshworks-export/ & chatwoot-import/` | Ticket/contact/macro/rule exporters, E.164 transformers, and idempotent Chatwoot importer |
| `infra/self-host/ & tools/ci/` | Self-host Docker Compose + Nginx config and 10 feature-track specification & verification loops |
| `docs/migration-and-specs/` | Upstream rebase playbook, helpdesk migration playbook, clean-room licensing guide, and rollout specs |
## 2. Environment Variable Contract
| Variable | Default / Example | Required | Description |
|---|---|---|---|
| `FRONTEND_URL` | `https://support.example.org` | Yes | Public base URL of your self-hosted Chatwoot instance |
| `POSTGRES_HOST` | `postgres` | Yes | PostgreSQL 16+ host |
| `REDIS_URL` | `redis://redis:6379` | Yes | Redis URL for Sidekiq queues, ActionCable, and bot locks |
| `SECRET_KEY_BASE` | `openssl_rand_hex_64` | Yes | Rails secret key base for session and token signing |
| `OVERLAY_AUDIT_MAX_AUDITS_PER_RECORD` | `50` | Yes | Maximum retained audit snapshots per configuration record |
| `OVERLAY_SLA_CRON_MINUTES` | `5` | Yes | Evaluation interval for Sidekiq batch SLA breach detection |
| `OVERLAY_DEFAULT_AGENT_MAX_OPEN_CONVERSATIONS` | `25` | Yes | Default per-agent open conversation cap for capacity auto-assignment |
## 3. Extension Recipe
1. Copy `.env.example` to `.env`, set `FRONTEND_URL`, `SECRET_KEY_BASE`, `POSTGRES_*`, and `REDIS_URL`, and build locally with `docker compose -f docker-compose.production.yaml build`.
2. Run `rails db:chatwoot_prepare` and `rake overlay:seed_roles` to initialize the 14 `overlay_*` tables and 5 RBAC role presets.
3. Deploy `chatwoot-bot/` via `chatwoot-bot/deploy/docker-compose.yml` and register its `/webhook` URL as an AgentBot in Chatwoot.
4. If migrating from Freshdesk/Freshchat, populate `migration-toolkit/freshworks-export/.env` and `chatwoot-import/.env` and follow `docs/HELPDESK-MIGRATION-PLAYBOOK.md`.
## 4. Operations Runbook
### 1. Verify clean-room invariants, migration transforms, and all 161 chatwoot-bot tests
```bash
pytest -q tests_overlay/ migration-toolkit/freshworks-export/tests/ && PYTHONPATH=chatwoot-bot pytest -q chatwoot-bot/tests/
```
### 2. Seed the 5 default custom RBAC roles on a new account
```bash
bundle exec rake overlay:seed_roles
```
### 3. Run the full overlay RSpec suite inside Docker/Rails
```bash
bundle exec rspec spec/overlay
```
### 4. Export legacy helpdesk tickets/config & import into Chatwoot
```bash
python3 migration-toolkit/freshworks-export/run_full_export.py && python3 migration-toolkit/chatwoot-import/run_full_import.py
```
---
## File: `docs/RESEARCH-2026.md` — 2026 Research & Landscape Notes (docs/RESEARCH-2026.md)
# 2026 Self-Hosted Helpdesk & Clean-Room Chatwoot Research
## 1. The Self-Hosted Chatwoot Edition Boundary in 2026
Standard upstream Chatwoot ships a dual-directory repository (`app/` under MIT + `enterprise/` under proprietary Enterprise licensing) inside the official `chatwoot/chatwoot` Docker image. Self-hosting teams routinely hit three pain points:
1. **Governance Feature Gap in Pure CE:** Pure Community Edition omits Audit Logs, Custom Roles (beyond binary Admin/Agent), SLA breach tracking, capacity-capped assignment, and SAML 2.0 SSO.
2. **The Docker Image License Trap:** Pulling the default upstream Docker image deploys `enterprise/` files onto disk where flipping feature flags can inadvertently invoke proprietary code paths.
3. **Missing Migration & AI Bot Tooling:** Moving off Freshdesk/Freshchat/Zendesk requires paginated exporters, schema transformers, and an HMAC-verified AI AgentBot — usually scattered across throwaway scripts.
## 2. How Unified `chatwoot-public` Solves All Three
| Capability | Upstream CE | Upstream EE (Proprietary) | `chatwoot-public` (Unified MIT Clean-Room Suite) |
|---|---|---|---|
| `enterprise/` directory | Stripped only if custom-built | Present & license-gated | **Absent from repository and Dockerfile (`ChatwootApp.enterprise? == false`)** |
| Config Audit Trail | Absent | `Enterprise::AuditLog` | **`audited` gem (`Audited::Audit`) across 13 config models (`Overlay::AuditLogsController`)** |
| Granular RBAC | 2 fixed roles | Custom roles | **31-permission PostgreSQL array (`Overlay::CustomRole` + 3-tier `RolePermissions`)** |
| Business-Hours SLAs | Absent | Lazy single-record check | **`AsyncDispatcher`-wired `Overlay::SlaListener` + Sidekiq cron batch evaluator + webhooks** |
| SAML 2.0 SSO | Absent | EE SAML | **MIT `omniauth-saml` hardened against XXE (`nonet`), RelayState injection & session fixation** |
| Capacity Auto-Assign | Unbounded round-robin | EE capacity | **`Overlay::AutoAssignment::CapacityAwareHandler` (`max_open_conversations` per inbox/agent)** |
| Native AI Support Bot | Webhook stub only | Paid add-on | **Bundled `chatwoot-bot/` FastAPI 7-stage AgentBot (161 unit & integration tests)** |
| SaaS Migration & Rebase | Manual | Paid onboarding | **Bundled `migration-toolkit/`, `portable-overlay/`, `infra/self-host/`, and 10 CI track specs** |