Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

feat: add Meta Ads referral (CTWA) support and replace AGENTS.md with CLAUDE.md

Aldino Kemalfe7d2c78634b
diff --git a/AGENTS.md b/AGENTS.md
deleted file mode 100644
index 604f0563..00000000
--- a/AGENTS.md
+++ /dev/null
@@ -1,109 +0,0 @@
-# PROJECT KNOWLEDGE BASE
-
-**Generated:** 2026-04-02
-**Commit:** 0e0af10
-**Branch:** main
-
-## OVERVIEW
-
-Go-based WhatsApp Web API server supporting REST API and MCP (Model Context Protocol) modes. Multi-device management via whatsmeow library.
-
-## STRUCTURE
-```
-go-whatsapp-web-multidevice/
-├── src/ # All source code
-│ ├── cmd/ # Cobra CLI commands (rest, mcp)
-│ ├── domains/ # Business domain contracts (interfaces + DTOs)
-│ ├── infrastructure/ # External integrations
-│ │ ├── whatsapp/ # WhatsApp protocol (whatsmeow) — 24 Go files
-│ │ ├── chatstorage/ # SQLite/PostgreSQL chat+message persistence
-│ │ └── chatwoot/ # Chatwoot CRM integration (sync + client)
-│ ├── ui/ # Transport layers (REST, MCP, WebSocket)
-│ ├── usecase/ # Application logic (bridges domain ↔ infra)
-│ ├── validations/ # ozzo-validation input checks + tests (19 test files total)
-│ ├── views/ # Vue.js 3 components (Semantic UI) — 49 components
-│ ├── pkg/ # Shared utilities (utils/ + error/)
-│ ├── config/ # Viper config binding (settings.go)
-│ └── storages/ # Runtime DB files (SQLite)
-├── docs/ # OpenAPI spec (openapi.yaml)
-└── gallery/ # Screenshot examples
-```
-
-## WHERE TO LOOK
-
-| Task | Location | Notes |
-|------|----------|-------|
-| Add new message type | `domains/send/`, `usecase/send.go`, `validations/send_validation.go` | 3-file pattern |
-| Add new API endpoint | `ui/rest/`, `usecase/`, `domains/` | Handler → usecase → domain |
-| Add MCP tool | `ui/mcp/` | Mirrors REST; includes `query.go` for read ops |
-| Handle WhatsApp event | `infrastructure/whatsapp/event_*.go` | Register in `event_handler.go` switch |
-| Add DB migration | `infrastructure/chatstorage/sqlite_repository.go` → `getMigrations()` | Append only — currently 15 migrations |
-| Add Vue component | `views/components/` | Plain JS, no .vue SFC |
-| Device management | `infrastructure/whatsapp/device_manager.go` | 615-line central orchestrator |
-| Chatwoot integration | `infrastructure/chatwoot/` | `client.go` (API) + `sync.go` (bidirectional sync) |
-
-## COMMANDS
-```bash
-cd src && go run . rest # Run REST API mode
-cd src && go run . mcp # Run MCP server mode
-cd src && go build -o whatsapp # Build binary
-cd src && go test ./... # Run all tests (19 test files)
-cd src && go vet ./... # Static analysis
-cd src && go fmt ./... # Format code
-go mod tidy # Update dependencies
-```
-
-## CRITICAL: Device ID vs JID
-
-Two distinct identifiers — confusing them causes silent data bugs:
-
-- **Device ID** (`instance.ID()`): User alias or UUID (e.g., `"my-device"`)
-- **JID** (`instance.JID()`): WhatsApp JID (e.g., `"[email protected]"`)
-
-**The `chats`/`messages` tables store device_id as the JID** (without device number). For DB queries:
-```go
-deviceID := client.Store.ID.ToNonAD().String() // ✅ "[email protected]"
-// NOT instance.ID() // ❌ may return "6289605618749:[email protected]" or alias
-```
-
-## CONVENTIONS
-
-- **Clean Architecture**: `domains/` → `usecase/` → `ui/` (never reverse)
-- **1:1 mapping**: Each domain has matching usecase, validation, and UI handler files
-- **Device scoping**: All chat/message queries must include `device_id`
-- **LID normalization**: WhatsApp sends `@lid` JIDs — always call `NormalizeJIDFromLID()` before DB ops
-- **Optional booleans**: Use `*bool` for optional filter params (nil = not set)
-- **Config priority**: CLI flags > env vars > `.env` file
-
-## ANTI-PATTERNS
-
-- **Never** query chats/messages without device_id scoping
-- **Never** use raw event JIDs for DB lookups without `NormalizeJIDFromLID`
-- **Never** add `IChatStorageRepository` methods without updating both wrapper files (`chatstorage_wrapper.go` + `device_repository.go`)
-- **Never** insert migrations in the middle — always append to `getMigrations()`
-- **Never** put business logic in domain packages — they define contracts only
-
-## KEY DEPENDENCIES
-
-| Package | Role |
-|---------|------|
-| `go.mau.fi/whatsmeow` | WhatsApp Web protocol |
-| `github.com/gofiber/fiber/v2` | REST web framework |
-| `github.com/mark3labs/mcp-go` | MCP server (v0.45.0) |
-| `github.com/spf13/cobra` | CLI framework |
-| `github.com/spf13/viper` | Config management |
-| `github.com/go-ozzo/ozzo-validation/v4` | Input validation |
-| `github.com/sirupsen/logrus` | Structured logging |
-| `github.com/mattn/go-sqlite3` | SQLite driver |
-| `github.com/lib/pq` | PostgreSQL driver |
-
-## NOTES
-
-- **Go 1.25.0+** required (see `src/go.mod`)
-- REST and MCP modes cannot run simultaneously (whatsmeow limitation)
-- Media files stored in `src/statics/media/`
-- FFmpeg required for media processing
-- HTML/JS assets embedded in binary via Go's `embed`
-- Database: SQLite default, PostgreSQL supported via `DB_URI`
-- Docker: `docker-compose.yml` with volume mounts for `storages/` and `statics/`
-- CI: GoReleaser builds for Linux/Windows, GitHub Actions for release + Docker image
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 00000000..b4a69498
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,119 @@
+# Go WhatsApp Web Multi-Device
+
+Go-based WhatsApp Web API server with REST and MCP modes. Multi-device management via whatsmeow.
+
+## Structure
+
+```
+src/
+├── main.go # Entry point; embeds views/ via go:embed
+├── cmd/ # Cobra CLI: rest, mcp subcommands + root config (407 lines)
+├── config/settings.go # All config vars (Viper-bound)
+├── domains/ # Contracts only: interfaces + DTOs (10 packages)
+├── infrastructure/
+│ ├── whatsapp/ # WhatsApp protocol layer (29 files, 4845 lines)
+│ ├── chatstorage/ # SQLite/PostgreSQL persistence (1263-line repo)
+│ └── chatwoot/ # Chatwoot CRM bidirectional sync
+├── usecase/ # Business logic (1:1 with domains)
+├── validations/ # ozzo-validation input checks + tests
+├── ui/
+│ ├── rest/ # Fiber HTTP handlers + middleware
+│ └── mcp/ # MCP server handlers
+├── views/ # Vue.js 3 components (Semantic UI, plain JS)
+├── pkg/
+│ ├── utils/ # Shared helpers: JID, media, phone formatting
+│ └── error/ # 4 error types: app, generic, validation, whatsapp
+├── statics/ # Runtime media + QR codes
+└── storages/ # Runtime SQLite DBs
+```
+
+## Commands
+
+```bash
+cd src && go run . rest # Run REST API (port 3000)
+cd src && go run . mcp # Run MCP server (port 8080)
+cd src && go build -o whatsapp # Build binary
+cd src && go test ./... # Run all tests
+cd src && go vet ./... # Static analysis
+go mod tidy # Update dependencies (run from src/)
+```
+
+## Where to Look
+
+| Task | Location | Notes |
+|------|----------|-------|
+| Add message type | `domains/send/`, `usecase/send.go`, `validations/send_validation.go` | 3-file pattern |
+| Add API endpoint | `ui/rest/`, `usecase/`, `domains/` | Handler → usecase → domain |
+| Add MCP tool | `ui/mcp/` | Mirrors REST; `query.go` for read ops |
+| Handle WA event | `infrastructure/whatsapp/event_*.go` | Register in `event_handler.go` switch |
+| Add DB migration | `infrastructure/chatstorage/sqlite_repository.go` → `getMigrations()` | Append only — 15 migrations |
+| Add Vue component | `views/components/` | Plain JS, no .vue SFC |
+| Device management | `infrastructure/whatsapp/device_manager.go` | 615-line central orchestrator |
+| Chatwoot integration | `infrastructure/chatwoot/` | `client.go` (API) + `sync.go` (sync) |
+| CLI flags / config | `cmd/root.go` | Viper+Cobra, `.env` loading |
+| Shared helpers | `pkg/utils/whatsapp.go`, `general.go` | JID, media, phone formatting |
+
+## Critical: Device ID vs JID
+
+Two distinct identifiers — confusing them causes silent data bugs:
+
+- **Device ID** (`instance.ID()`): User alias or UUID (e.g., `"my-device"`)
+- **JID** (`instance.JID()`): WhatsApp JID (e.g., `"[email protected]"`)
+
+The `chats`/`messages` tables store device_id as the **JID without device number**:
+```go
+deviceID := client.Store.ID.ToNonAD().String() // ✅ "[email protected]"
+// NOT instance.ID() // ❌ may return alias or "6289605618749:[email protected]"
+```
+
+## Conventions
+
+- **Clean Architecture**: `domains/` → `usecase/` → `ui/` (never reverse)
+- **1:1 mapping**: Each domain has matching usecase, validation, and UI handler
+- **Device scoping**: All chat/message DB queries must include `device_id`
+- **LID normalization**: WhatsApp sends `@lid` JIDs — call `NormalizeJIDFromLID()` before DB ops
+- **Optional booleans**: Use `*bool` for optional filter params (nil = not set)
+- **Config priority**: CLI flags > env vars > `.env` file
+- **Wrapper pattern**: `IChatStorageRepository` has two wrappers that inject device_id:
+ - `infrastructure/whatsapp/chatstorage_wrapper.go` (for event handlers)
+ - `infrastructure/chatstorage/device_repository.go` (for usecase layer)
+
+## Anti-Patterns
+
+- **Never** query chats/messages without device_id scoping
+- **Never** use raw event JIDs for DB lookups without `NormalizeJIDFromLID`
+- **Never** add `IChatStorageRepository` methods without updating both wrapper files
+- **Never** insert migrations in the middle — always append to `getMigrations()`
+- **Never** put business logic in domain packages — they define contracts only
+- **Never** remove the Device == 0 check in receipt forwarding (prevents duplicate webhooks)
+
+## Testing
+
+- Standard Go testing + `testify/assert` + `testify/suite`
+- Table-driven tests throughout
+- `httptest` for HTTP testing, `fiber.Test()` for middleware
+- Tests colocated with source: `*_test.go` next to implementation
+- Run: `cd src && go test ./...`
+
+## Key Dependencies
+
+| Package | Role |
+|---------|------|
+| `go.mau.fi/whatsmeow` | WhatsApp Web protocol |
+| `github.com/gofiber/fiber/v2` | REST framework |
+| `github.com/mark3labs/mcp-go` | MCP server (v0.45.0) |
+| `github.com/spf13/cobra` + `viper` | CLI + config |
+| `github.com/go-ozzo/ozzo-validation/v4` | Input validation |
+| `github.com/mattn/go-sqlite3` / `github.com/lib/pq` | SQLite / PostgreSQL |
+
+## Notes
+
+- **Go 1.25.0+** required (`src/go.mod`)
+- REST and MCP modes cannot run simultaneously (whatsmeow limitation)
+- FFmpeg required for media processing (`ConvertToJPEG`, `ConvertToMP4`)
+- HTML/JS assets embedded in binary via `go:embed`
+- Database: SQLite default, PostgreSQL via `DB_URI` env var
+- Docker: multi-stage alpine build, non-root user `gowauser` (uid 20001)
+- CI: GitHub Actions → GoReleaser (Linux/Windows/macOS) + multi-arch Docker (GHCR + Docker Hub)
+- Hot reload: `.air.toml` configured (excludes `statics/`, `storages/`)
+- `status@broadcast` chat always returns name "Status" regardless of other naming
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.md
index 437d5ad7..7d37777c 100644
--- a/docs/webhook-payload.md
+++ b/docs/webhook-payload.md
@@ -1052,6 +1052,68 @@ When a message is edited, the webhook includes the original message ID to track
}
```
+### Meta Ads Referral (Click-to-WhatsApp)
+
+When a conversation starts from a Meta Click-to-WhatsApp ad, the first inbound message includes ad attribution metadata in the `referral` field. This is extracted from the WhatsApp protocol's `contextInfo.externalAdReply`.
+
+```json
+{
+ "event": "message",
+ "device_id": "[email protected]",
+ "payload": {
+ "id": "3EB0C127D7BACC83D6B4",
+ "chat_id": "[email protected]",
+ "from": "[email protected]",
+ "from_name": "Jane Customer",
+ "timestamp": "2023-10-15T12:00:00Z",
+ "is_from_me": false,
+ "body": "Hello! I would like more information about the property.",
+ "referral": {
+ "ctwa_clid": "FAKE_CLID_abc123xyz",
+ "source_url": "https://fb.me/fake-ad-link",
+ "source_id": "123456789012345",
+ "ref": "landing_page_01",
+ "source_app": "facebook",
+ "media_type": "IMAGE",
+ "ad_title": "Your Dream Farm",
+ "ad_body": "Discover exclusive rural properties in the countryside.",
+ "thumbnail_url": "https://example.com/ad-thumbnail.jpg",
+ "original_image_url": "https://example.com/ad-image.jpg",
+ "show_ad_attribution": true,
+ "click_to_whatsapp_call": false,
+ "contains_auto_reply": false,
+ "automated_greeting_message_shown": true,
+ "greeting_message_body": "Hello! I want to know more about this ad.",
+ "source_type": "ad",
+ "ad_type": "CTWA"
+ }
+ }
+}
+```
+
+**Referral fields** (all optional, only present when the message originated from a Meta ad):
+
+| **Field** | **Type** | **Description** |
+|------------------------------------|----------|--------------------------------------------------------------------|
+| `ctwa_clid` | string | Meta Click-to-WhatsApp click ID for ad attribution |
+| `source_url` | string | Landing page / ad destination URL |
+| `source_id` | string | Meta ad creative or ad set ID |
+| `ref` | string | The `ref` parameter set on the WhatsApp button in the ad |
+| `source_app` | string | Origin platform: `"facebook"` or `"instagram"` |
+| `media_type` | string | Ad creative media type: `"NONE"`, `"IMAGE"`, or `"VIDEO"` |
+| `ad_title` | string | Ad creative title |
+| `ad_body` | string | Ad creative description/body text |
+| `thumbnail_url` | string | URL of the ad thumbnail image |
+| `original_image_url` | string | URL of the original ad image |
+| `media_url` | string | URL of the ad media |
+| `show_ad_attribution` | boolean | Whether to show the ad attribution badge |
+| `contains_auto_reply` | boolean | Whether the ad has a pre-filled auto-reply message |
+| `automated_greeting_message_shown` | boolean | Whether the automated greeting was shown to the user |
+| `greeting_message_body` | string | Body text of the automated greeting message |
+| `click_to_whatsapp_call` | boolean | Whether this is a Click-to-WhatsApp Call ad (vs chat) |
+| `source_type` | string | Source type (e.g., `"ad"`) |
+| `ad_type` | string | Ad type: `"CTWA"` (Click-to-WhatsApp) or `"CAWC"` (Click-to-Call) |
+
## Integration Guide
### Setting Up Webhook Endpoint
diff --git a/src/domains/AGENTS.md b/src/domains/AGENTS.md
deleted file mode 100644
index b0555479..00000000
--- a/src/domains/AGENTS.md
+++ /dev/null
@@ -1,29 +0,0 @@
-# domains
-
-Business domain layer. Each subdomain has `interfaces.go` (usecase interface) + request/response structs. 10 domain packages.
-
-## STRUCTURE
-```
-domains/
-├── app/ # App lifecycle (login, logout, reconnect)
-├── chat/ # Chat operations (list, messages, archive, pin, label)
-├── chatstorage/ # Chat/message storage entities + IChatStorageRepository interface
-├── device/ # Multi-device management
-├── group/ # Group CRUD + participants
-├── message/ # Message operations (react, delete, revoke, star)
-├── newsletter/ # Newsletter/channel operations
-├── send/ # Message sending (text, image, video, document, etc.) — 15 request files
-├── settings/ # Application settings
-└── user/ # User info, avatar, privacy, contacts
-```
-
-## CONVENTIONS
-- Each domain package exports: `interfaces.go` (usecase interface), request/response structs
-- Use `*bool` for optional boolean filters (e.g., `Archived *bool` in `ListChatsRequest`)
-- Request structs validate via `ozzo-validation` in `validations/` package
-- `chatstorage/` is the only domain with a repository interface — others use whatsmeow directly
-- `send/` has the most request files (one per message type)
-
-## ANTI-PATTERNS
-- Never put business logic in domain packages — they define contracts only
-- Never import infrastructure packages from domains
diff --git a/src/domains/chatstorage/chatstorage.go b/src/domains/chatstorage/chatstorage.go
index 36db70e1..c4865784 100644
--- a/src/domains/chatstorage/chatstorage.go
+++ b/src/domains/chatstorage/chatstorage.go
@@ -16,23 +16,24 @@ type Chat struct {
// Message represents a WhatsApp message
type Message struct {
- ID string `db:"id"`
- ChatJID string `db:"chat_jid"`
- DeviceID string `db:"device_id"`
- Sender string `db:"sender"`
- Content string `db:"content"`
- Timestamp time.Time `db:"timestamp"`
- IsFromMe bool `db:"is_from_me"`
- MediaType string `db:"media_type"`
- CallMetadata string `db:"call_metadata"` // JSON metadata when media_type is "call"
- Filename string `db:"filename"`
- URL string `db:"url"`
- MediaKey []byte `db:"media_key"`
- FileSHA256 []byte `db:"file_sha256"`
- FileEncSHA256 []byte `db:"file_enc_sha256"`
- FileLength uint64 `db:"file_length"`
- CreatedAt time.Time `db:"created_at"`
- UpdatedAt time.Time `db:"updated_at"`
+ ID string `db:"id"`
+ ChatJID string `db:"chat_jid"`
+ DeviceID string `db:"device_id"`
+ Sender string `db:"sender"`
+ Content string `db:"content"`
+ Timestamp time.Time `db:"timestamp"`
+ IsFromMe bool `db:"is_from_me"`
+ MediaType string `db:"media_type"`
+ CallMetadata string `db:"call_metadata"`
+ Filename string `db:"filename"`
+ URL string `db:"url"`
+ MediaKey []byte `db:"media_key"`
+ FileSHA256 []byte `db:"file_sha256"`
+ FileEncSHA256 []byte `db:"file_enc_sha256"`
+ FileLength uint64 `db:"file_length"`
+ ReferralMetadata string `db:"referral_metadata"`
+ CreatedAt time.Time `db:"created_at"`
+ UpdatedAt time.Time `db:"updated_at"`
}
// MediaInfo represents downloadable media information
diff --git a/src/infrastructure/chatstorage/AGENTS.md b/src/infrastructure/chatstorage/AGENTS.md
deleted file mode 100644
index 07fd2d18..00000000
--- a/src/infrastructure/chatstorage/AGENTS.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# infrastructure/chatstorage
-
-SQLite/PostgreSQL chat and message persistence. Single implementation file with sequential migration system.
-
-## KEY FILES
-- `sqlite_repository.go` (1263 lines) — Full `IChatStorageRepository` implementation (39 methods)
-- `device_repository.go` — Wrapper that injects device_id into all calls (mirrors `chatstorage_wrapper.go` in `whatsapp/`)
-
-## MIGRATION SYSTEM
-Migrations are sequential string slices returned by `getMigrations()`. Each runs in a transaction with version tracking in `schema_info` table.
-
-Current: **15 migrations** (latest: `call_metadata TEXT` column on messages table).
-
-Tables: `chats` (PK: jid+device_id), `messages` (PK: id+chat_jid+device_id), `devices` (PK: device_id), `schema_info`.
-
-## KEY METHODS
-- `CreateMessage(ctx, evt)` — Full message ingestion: resolve device → normalize JIDs → upsert chat → store message
-- `StoreSentMessageWithContext(ctx, ...)` — Outbound messages with context cancellation support
-- `CreateIncomingCallRecord(ctx, evt, autoRejected)` — Synthetic call rows (media_type="call")
-- `GetChatNameWithPushNameByDevice(...)` — Name resolution: existing > pushName > sender > JID
-- `GetFilteredChatCount(filter)` — Use this for pagination totals, NOT `GetTotalChatCount()`
-
-## CONVENTIONS
-- All chat queries must be device-scoped (use `device_id` column)
-- Filter methods must mirror `GetChats` filter logic exactly via `buildChatFilterQuery`
-- New interface methods → add to `device_repository.go` AND `whatsapp/chatstorage_wrapper.go`
-- Cross-DB compatible SQL: avoid SQLite-specific or PostgreSQL-specific syntax in migrations
-
-## ANTI-PATTERNS
-- Never add a migration in the middle — always append
-- Never query chats without device_id scoping in multi-device context
diff --git a/src/infrastructure/chatstorage/sqlite_repository.go b/src/infrastructure/chatstorage/sqlite_repository.go
index fa42e90d..1a452a0c 100644
--- a/src/infrastructure/chatstorage/sqlite_repository.go
+++ b/src/infrastructure/chatstorage/sqlite_repository.go
@@ -89,7 +89,7 @@ func (r *SQLiteRepository) GetMessageByID(id string) (*domainChatStorage.Message
query := `
SELECT id, chat_jid, device_id, sender, content, timestamp, is_from_me,
media_type, call_metadata, filename, url, media_key, file_sha256,
- file_enc_sha256, file_length, created_at, updated_at
+ file_enc_sha256, file_length, referral_metadata, created_at, updated_at
FROM messages
WHERE id = ?
LIMIT 1
@@ -242,11 +242,11 @@ func (r *SQLiteRepository) StoreMessage(message *domainChatStorage.Message) erro
result, err := r.db.Exec(`
UPDATE messages SET sender = ?, content = ?, timestamp = ?, is_from_me = ?,
media_type = ?, call_metadata = ?, filename = ?, url = ?, media_key = ?, file_sha256 = ?,
- file_enc_sha256 = ?, file_length = ?, updated_at = ?
+ file_enc_sha256 = ?, file_length = ?, referral_metadata = ?, updated_at = ?
WHERE id = ? AND chat_jid = ? AND device_id = ?
`, message.Sender, message.Content, message.Timestamp, message.IsFromMe,
message.MediaType, message.CallMetadata, message.Filename, message.URL, message.MediaKey, message.FileSHA256,
- message.FileEncSHA256, message.FileLength, message.UpdatedAt,
+ message.FileEncSHA256, message.FileLength, message.ReferralMetadata, message.UpdatedAt,
message.ID, message.ChatJID, message.DeviceID)
if err != nil {
return err
@@ -258,12 +258,12 @@ func (r *SQLiteRepository) StoreMessage(message *domainChatStorage.Message) erro
INSERT INTO messages (
id, chat_jid, device_id, sender, content, timestamp, is_from_me,
media_type, call_metadata, filename, url, media_key, file_sha256,
- file_enc_sha256, file_length, created_at, updated_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ file_enc_sha256, file_length, referral_metadata, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`, message.ID, message.ChatJID, message.DeviceID, message.Sender, message.Content,
message.Timestamp, message.IsFromMe, message.MediaType, message.CallMetadata, message.Filename,
message.URL, message.MediaKey, message.FileSHA256, message.FileEncSHA256,
- message.FileLength, message.CreatedAt, message.UpdatedAt)
+ message.FileLength, message.ReferralMetadata, message.CreatedAt, message.UpdatedAt)
}
return err
}
@@ -284,7 +284,7 @@ func (r *SQLiteRepository) StoreMessagesBatch(messages []*domainChatStorage.Mess
updateStmt, err := tx.Prepare(`
UPDATE messages SET sender = ?, content = ?, timestamp = ?, is_from_me = ?,
media_type = ?, call_metadata = ?, filename = ?, url = ?, media_key = ?, file_sha256 = ?,
- file_enc_sha256 = ?, file_length = ?, updated_at = ?
+ file_enc_sha256 = ?, file_length = ?, referral_metadata = ?, updated_at = ?
WHERE id = ? AND chat_jid = ? AND device_id = ?
`)
if err != nil {
@@ -296,8 +296,8 @@ func (r *SQLiteRepository) StoreMessagesBatch(messages []*domainChatStorage.Mess
INSERT INTO messages (
id, chat_jid, device_id, sender, content, timestamp, is_from_me,
media_type, call_metadata, filename, url, media_key, file_sha256,
- file_enc_sha256, file_length, created_at, updated_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ file_enc_sha256, file_length, referral_metadata, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`)
if err != nil {
return fmt.Errorf("failed to prepare insert statement: %w", err)
@@ -316,7 +316,7 @@ func (r *SQLiteRepository) StoreMessagesBatch(messages []*domainChatStorage.Mess
result, err := updateStmt.Exec(
message.Sender, message.Content, message.Timestamp, message.IsFromMe,
message.MediaType, message.CallMetadata, message.Filename, message.URL, message.MediaKey, message.FileSHA256,
- message.FileEncSHA256, message.FileLength, message.UpdatedAt,
+ message.FileEncSHA256, message.FileLength, message.ReferralMetadata, message.UpdatedAt,
message.ID, message.ChatJID, message.DeviceID,
)
if err != nil {
@@ -329,7 +329,7 @@ func (r *SQLiteRepository) StoreMessagesBatch(messages []*domainChatStorage.Mess
message.ID, message.ChatJID, message.DeviceID, message.Sender, message.Content,
message.Timestamp, message.IsFromMe, message.MediaType, message.CallMetadata, message.Filename,
message.URL, message.MediaKey, message.FileSHA256, message.FileEncSHA256,
- message.FileLength, message.CreatedAt, message.UpdatedAt,
+ message.FileLength, message.ReferralMetadata, message.CreatedAt, message.UpdatedAt,
)
if err != nil {
return fmt.Errorf("failed to insert message %s: %w", message.ID, err)
@@ -379,7 +379,7 @@ func (r *SQLiteRepository) GetMessages(filter *domainChatStorage.MessageFilter)
query := `
SELECT id, chat_jid, device_id, sender, content, timestamp, is_from_me,
media_type, call_metadata, filename, url, media_key, file_sha256,
- file_enc_sha256, file_length, created_at, updated_at
+ file_enc_sha256, file_length, referral_metadata, created_at, updated_at
FROM messages
WHERE ` + strings.Join(conditions, " AND ") + `
ORDER BY timestamp DESC
@@ -444,7 +444,7 @@ func (r *SQLiteRepository) SearchMessages(deviceID, chatJID, searchText string,
query := `
SELECT id, chat_jid, device_id, sender, content, timestamp, is_from_me,
media_type, call_metadata, filename, url, media_key, file_sha256,
- file_enc_sha256, file_length, created_at, updated_at
+ file_enc_sha256, file_length, referral_metadata, created_at, updated_at
FROM messages
WHERE ` + strings.Join(conditions, " AND ") + `
ORDER BY timestamp DESC
@@ -507,7 +507,7 @@ func (r *SQLiteRepository) scanMessage(scanner interface{ Scan(...any) error })
&message.ID, &message.ChatJID, &message.DeviceID, &message.Sender, &message.Content,
&message.Timestamp, &message.IsFromMe, &message.MediaType, &message.CallMetadata, &message.Filename,
&message.URL, &message.MediaKey, &message.FileSHA256, &message.FileEncSHA256,
- &message.FileLength, &message.CreatedAt, &message.UpdatedAt,
+ &message.FileLength, &message.ReferralMetadata, &message.CreatedAt, &message.UpdatedAt,
)
return message, err
}
@@ -846,22 +846,29 @@ func (r *SQLiteRepository) CreateMessage(ctx context.Context, evt *events.Messag
return nil
}
- // Create message object
+ var referralMetadata string
+ if referral := utils.ExtractExternalAdReply(evt.Message); referral != nil {
+ if jsonBytes, err := json.Marshal(referral); err == nil {
+ referralMetadata = string(jsonBytes)
+ }
+ }
+
message := &domainChatStorage.Message{
- ID: evt.Info.ID,
- ChatJID: chatJID,
- DeviceID: deviceID,
- Sender: sender,
- Content: content,
- Timestamp: evt.Info.Timestamp,
- IsFromMe: evt.Info.IsFromMe,
- MediaType: mediaType,
- Filename: filename,
- URL: url,
- MediaKey: mediaKey,
- FileSHA256: fileSHA256,
- FileEncSHA256: fileEncSHA256,
- FileLength: fileLength,
+ ID: evt.Info.ID,
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ Sender: sender,
+ Content: content,
+ Timestamp: evt.Info.Timestamp,
+ IsFromMe: evt.Info.IsFromMe,
+ MediaType: mediaType,
+ Filename: filename,
+ URL: url,
+ MediaKey: mediaKey,
+ FileSHA256: fileSHA256,
+ FileEncSHA256: fileEncSHA256,
+ FileLength: fileLength,
+ ReferralMetadata: referralMetadata,
}
// Store the message
@@ -1259,5 +1266,8 @@ func (r *SQLiteRepository) getMigrations() []string {
// Migration 15: JSON metadata for synthetic call rows (media_type = call)
`ALTER TABLE messages ADD COLUMN call_metadata TEXT DEFAULT ''`,
+
+ // Migration 16: JSON metadata for Meta Ads referral/attribution (CTWA)
+ `ALTER TABLE messages ADD COLUMN referral_metadata TEXT DEFAULT ''`,
}
}
diff --git a/src/infrastructure/whatsapp/AGENTS.md b/src/infrastructure/whatsapp/AGENTS.md
deleted file mode 100644
index c9be9e91..00000000
--- a/src/infrastructure/whatsapp/AGENTS.md
+++ /dev/null
@@ -1,61 +0,0 @@
-# infrastructure/whatsapp
-
-WhatsApp protocol integration layer using whatsmeow. Handles device management, event processing, chat storage wrappers, and webhook forwarding.
-
-## STRUCTURE
-```
-whatsapp/
-├── device_manager.go # DeviceManager: multi-device lifecycle (615 lines)
-├── device_instance.go # DeviceInstance: ID()/JID() + client wrapper
-├── event_handler.go # Central event dispatcher (switch on event type)
-├── event_message.go # Message event → storage + webhook
-├── event_message_handler.go # Message handler helpers
-├── event_archive.go # Archive event → local DB update
-├── event_receipt.go # Read receipts (primary device only)
-├── event_call.go # Call events → synthetic message rows
-├── event_chat_presence.go # Chat presence (typing, online) events
-├── event_delete.go # Message deletion events
-├── event_group.go # Group info changes
-├── event_newsletter.go # Newsletter events
-├── history_sync.go # WhatsApp history sync to local DB
-├── chatstorage_wrapper.go # deviceChatStorage: injects device_id into all repo calls
-├── jid_utils.go # NormalizeJIDFromLID: @lid → @s.whatsapp.net
-├── webhook.go # Webhook dispatch
-├── webhook_forward.go # Forward events to external webhooks (484 lines)
-├── client_lifecycle.go # Connect/disconnect/reconnect logic
-├── context_device.go # Context helpers for device resolution
-├── auto_reply.go # Auto-reply message handling
-├── cleanup.go # Resource cleanup
-├── database.go # DB connection setup
-├── init.go # Package initialization
-└── logger.go # Custom whatsmeow logger adapter
-```
-
-## CRITICAL PATTERNS
-
-### JID Normalization
-WhatsApp uses LID JIDs (`@lid`) internally. **Always** normalize before DB lookups:
-```go
-normalizedJID := NormalizeJIDFromLID(ctx, evt.JID, client)
-jidStr := normalizedJID.String()
-```
-
-### Device ID for DB Lookups
-DB stores device_id as JID without device number. Use `client.Store.ID.ToNonAD().String()` — **never** `instance.ID()` for chat storage queries:
-```go
-deviceID := client.Store.ID.ToNonAD().String() // "[email protected]"
-// NOT instance.ID() which returns "6289605618749:[email protected]"
-```
-
-### Event Handler Pattern
-All event handlers follow: `func handleX(ctx, evt, chatStorageRepo, client)` → normalize JIDs → lookup/update DB → forward to webhook.
-
-Receipt forwarding restricted to primary device only (`Device == 0`).
-
-### Wrapper Pattern
-`deviceChatStorage` / `DeviceRepository` wrap all `IChatStorageRepository` calls to inject device_id automatically. New interface methods must be added to BOTH wrappers.
-
-## ANTI-PATTERNS
-- **Never** use raw JID from events for DB queries without `NormalizeJIDFromLID`
-- **Never** add interface methods without updating `chatstorage_wrapper.go` and `device_repository.go`
-- **Never** use `instance.ID()` for chat storage — use `client.Store.ID.ToNonAD().String()`
diff --git a/src/infrastructure/whatsapp/event_message.go b/src/infrastructure/whatsapp/event_message.go
index e1186da4..4de91ffe 100644
--- a/src/infrastructure/whatsapp/event_message.go
+++ b/src/infrastructure/whatsapp/event_message.go
@@ -18,6 +18,8 @@ import (
"go.mau.fi/whatsmeow/types/events"
)
+var reMention = regexp.MustCompile(`\B@\w+`)
+
// Event types for webhook payload
const (
EventTypeMessage = "message"
@@ -165,7 +167,7 @@ func buildMessageBody(ctx context.Context, client *whatsmeow.Client, evt *events
// Replace LID mentions with phone numbers in text
if message.Text != "" && client != nil && client.Store != nil && client.Store.LIDs != nil {
- tags := regexp.MustCompile(`\B@\w+`).FindAllString(message.Text, -1)
+ tags := reMention.FindAllString(message.Text, -1)
tagsMap := make(map[string]bool)
for _, tag := range tags {
tagsMap[tag] = true
@@ -217,6 +219,10 @@ func buildOptionalFields(ctx context.Context, client *whatsmeow.Client, evt *eve
payload["forwarded"] = true
}
+ if referral := utils.ExtractExternalAdReply(msg); referral != nil {
+ payload["referral"] = referral
+ }
+
if err := buildMediaFields(ctx, client, msg, payload); err != nil {
return err
}
diff --git a/src/pkg/utils/whatsapp.go b/src/pkg/utils/whatsapp.go
index 3d403d8e..2883d3ef 100644
--- a/src/pkg/utils/whatsapp.go
+++ b/src/pkg/utils/whatsapp.go
@@ -312,132 +312,67 @@ func ExtractMediaInfo(msg *waE2E.Message) (mediaType string, filename string, ur
return "", "", "", nil, nil, nil, 0
}
+// ExtractContextInfo returns the ContextInfo from whichever message sub-type
+// is present. Returns nil when the message has no ContextInfo.
+func ExtractContextInfo(msg *waE2E.Message) *waE2E.ContextInfo {
+ if msg == nil {
+ return nil
+ }
+ switch {
+ case msg.GetExtendedTextMessage() != nil:
+ return msg.GetExtendedTextMessage().GetContextInfo()
+ case msg.GetImageMessage() != nil:
+ return msg.GetImageMessage().GetContextInfo()
+ case msg.GetVideoMessage() != nil:
+ return msg.GetVideoMessage().GetContextInfo()
+ case msg.GetAudioMessage() != nil:
+ return msg.GetAudioMessage().GetContextInfo()
+ case msg.GetDocumentMessage() != nil:
+ return msg.GetDocumentMessage().GetContextInfo()
+ case msg.GetStickerMessage() != nil:
+ return msg.GetStickerMessage().GetContextInfo()
+ case msg.GetContactMessage() != nil:
+ return msg.GetContactMessage().GetContextInfo()
+ case msg.GetLocationMessage() != nil:
+ return msg.GetLocationMessage().GetContextInfo()
+ case msg.GetPtvMessage() != nil:
+ return msg.GetPtvMessage().GetContextInfo()
+ case msg.GetLiveLocationMessage() != nil:
+ return msg.GetLiveLocationMessage().GetContextInfo()
+ }
+ return nil
+}
+
// ExtractEphemeralExpiration extracts ephemeral expiration from a WhatsApp message
func ExtractEphemeralExpiration(msg *waE2E.Message) uint32 {
- logrus.Debug("ExtractEphemeralExpiration: Starting extraction process")
-
if msg == nil {
- logrus.Debug("ExtractEphemeralExpiration: Message is nil, returning 0")
return 0
}
- logrus.Debug("ExtractEphemeralExpiration: Message is valid, checking message types")
-
- // Check extended text message
- logrus.Debug("ExtractEphemeralExpiration: Checking for extended text message")
- if extendedText := msg.GetExtendedTextMessage(); extendedText != nil {
- logrus.Debug("ExtractEphemeralExpiration: Extended text message found, checking context info")
- if contextInfo := extendedText.GetContextInfo(); contextInfo != nil {
- expiration := contextInfo.GetExpiration()
- logrus.WithField("expiration", expiration).Debug("ExtractEphemeralExpiration: Found expiration in extended text message")
- return expiration
- }
- logrus.Debug("ExtractEphemeralExpiration: Extended text message has no context info")
- } else {
- logrus.Debug("ExtractEphemeralExpiration: No extended text message found")
- }
-
- // Check regular conversation message
- logrus.Debug("ExtractEphemeralExpiration: Checking for regular conversation message")
- if msg.GetConversation() != "" {
- logrus.Debug("ExtractEphemeralExpiration: Regular conversation message found, but no context info available for this type")
- // Regular text messages might have context info too
- // This would need to be checked based on the actual protobuf structure
- } else {
- logrus.Debug("ExtractEphemeralExpiration: No regular conversation message found")
- }
-
- // Check image message
- logrus.Debug("ExtractEphemeralExpiration: Checking for image message")
- if img := msg.GetImageMessage(); img != nil {
- logrus.Debug("ExtractEphemeralExpiration: Image message found, checking context info")
- if contextInfo := img.GetContextInfo(); contextInfo != nil {
- expiration := contextInfo.GetExpiration()
- logrus.WithField("expiration", expiration).Debug("ExtractEphemeralExpiration: Found expiration in image message")
- return expiration
+ if ci := ExtractContextInfo(msg); ci != nil {
+ if exp := ci.GetExpiration(); exp != 0 {
+ return exp
}
- logrus.Debug("ExtractEphemeralExpiration: Image message has no context info")
- } else {
- logrus.Debug("ExtractEphemeralExpiration: No image message found")
}
- // Check video message
- logrus.Debug("ExtractEphemeralExpiration: Checking for video message")
- if vid := msg.GetVideoMessage(); vid != nil {
- logrus.Debug("ExtractEphemeralExpiration: Video message found, checking context info")
- if contextInfo := vid.GetContextInfo(); contextInfo != nil {
- expiration := contextInfo.GetExpiration()
- logrus.WithField("expiration", expiration).Debug("ExtractEphemeralExpiration: Found expiration in video message")
- return expiration
+ if pm := msg.GetProtocolMessage(); pm != nil {
+ if exp := pm.GetEphemeralExpiration(); exp != 0 {
+ return exp
}
- logrus.Debug("ExtractEphemeralExpiration: Video message has no context info")
- } else {
- logrus.Debug("ExtractEphemeralExpiration: No video message found")
}
- // Check audio message
- logrus.Debug("ExtractEphemeralExpiration: Checking for audio message")
- if aud := msg.GetAudioMessage(); aud != nil {
- logrus.Debug("ExtractEphemeralExpiration: Audio message found, checking context info")
- if contextInfo := aud.GetContextInfo(); contextInfo != nil {
- expiration := contextInfo.GetExpiration()
- logrus.WithField("expiration", expiration).Debug("ExtractEphemeralExpiration: Found expiration in audio message")
- return expiration
- }
- logrus.Debug("ExtractEphemeralExpiration: Audio message has no context info")
- } else {
- logrus.Debug("ExtractEphemeralExpiration: No audio message found")
- }
-
- // Check document message
- logrus.Debug("ExtractEphemeralExpiration: Checking for document message")
- if doc := msg.GetDocumentMessage(); doc != nil {
- logrus.Debug("ExtractEphemeralExpiration: Document message found, checking context info")
- if contextInfo := doc.GetContextInfo(); contextInfo != nil {
- expiration := contextInfo.GetExpiration()
- logrus.WithField("expiration", expiration).Debug("ExtractEphemeralExpiration: Found expiration in document message")
- return expiration
- }
- logrus.Debug("ExtractEphemeralExpiration: Document message has no context info")
- } else {
- logrus.Debug("ExtractEphemeralExpiration: No document message found")
- }
-
- // Check sticker message
- logrus.Debug("ExtractEphemeralExpiration: Checking for sticker message")
- if sticker := msg.GetStickerMessage(); sticker != nil {
- logrus.Debug("ExtractEphemeralExpiration: Sticker message found, checking context info")
- if contextInfo := sticker.GetContextInfo(); contextInfo != nil {
- expiration := contextInfo.GetExpiration()
- logrus.WithField("expiration", expiration).Debug("ExtractEphemeralExpiration: Found expiration in sticker message")
- return expiration
- }
- logrus.Debug("ExtractEphemeralExpiration: Sticker message has no context info")
- } else {
- logrus.Debug("ExtractEphemeralExpiration: No sticker message found")
- }
-
- if protocolMessage := msg.GetProtocolMessage(); protocolMessage != nil {
- if ephemeralExpiration := protocolMessage.GetEphemeralExpiration(); ephemeralExpiration != 0 {
- logrus.WithField("expiration", ephemeralExpiration).Debug("ExtractEphemeralExpiration: Found expiration in protocol message")
- return ephemeralExpiration
- }
- logrus.Debug("ExtractEphemeralExpiration: Protocol message has no expiration")
- }
-
- logrus.Debug("ExtractEphemeralExpiration: No expiration found in any message type, returning 0")
return 0
}
+var reNonAlphanumeric = regexp.MustCompile(`[^a-zA-Z0-9_\-]`)
+
// GenerateMediaFilename creates a filename for media files
func GenerateMediaFilename(mediaType, extension, caption string) string {
timestamp := time.Now().Format("20060102_150405")
name := mediaType + "_" + timestamp
if caption != "" {
- // Only keep alphanumeric, _, -
- re := regexp.MustCompile(`[^a-zA-Z0-9_\-]`)
- cleanCaption := re.ReplaceAllString(caption, "_")
+ cleanCaption := reNonAlphanumeric.ReplaceAllString(caption, "_")
if len(cleanCaption) > 30 {
cleanCaption = cleanCaption[:30]
}
@@ -450,11 +385,11 @@ func GenerateMediaFilename(mediaType, extension, caption string) string {
return name
}
+var reDigits = regexp.MustCompile(`\d+`)
+
// ExtractPhoneNumber is a helper function to extract the phone number from a JID
func ExtractPhoneNumber(jid string) string {
- regex := regexp.MustCompile(`\d+`)
- // Find all matches of the pattern in the JID
- matches := regex.FindAllString(jid, -1)
+ matches := reDigits.FindAllString(jid, -1)
// The first match should be the phone number
if len(matches) > 0 {
return matches[0]
@@ -810,18 +745,24 @@ func BuildEventMessage(evt *events.Message) (message EvtMessage) {
if extendedMessage := msg.GetExtendedTextMessage(); extendedMessage != nil {
message.Text = extendedMessage.GetText()
- message.RepliedId = extendedMessage.ContextInfo.GetStanzaID()
- message.QuotedMessage = extendedMessage.ContextInfo.GetQuotedMessage().GetConversation()
} else if protocolMessage := msg.GetProtocolMessage(); protocolMessage != nil {
if editedMessage := protocolMessage.GetEditedMessage(); editedMessage != nil {
if extendedText := editedMessage.GetExtendedTextMessage(); extendedText != nil {
message.Text = extendedText.GetText()
- message.RepliedId = extendedText.ContextInfo.GetStanzaID()
- message.QuotedMessage = extendedText.ContextInfo.GetQuotedMessage().GetConversation()
}
+ if ci := ExtractContextInfo(editedMessage); ci != nil {
+ message.RepliedId = ci.GetStanzaID()
+ message.QuotedMessage = ci.GetQuotedMessage().GetConversation()
+ }
+ return message
}
}
+ if ci := ExtractContextInfo(msg); ci != nil {
+ message.RepliedId = ci.GetStanzaID()
+ message.QuotedMessage = ci.GetQuotedMessage().GetConversation()
+ }
+
return message
}
@@ -836,14 +777,96 @@ func BuildEventReaction(evt *events.Message) (waReaction EvtReaction) {
func BuildForwarded(evt *events.Message) bool {
msg := UnwrapMessage(evt.Message)
- if extendedText := msg.GetExtendedTextMessage(); extendedText != nil {
- return extendedText.ContextInfo.GetIsForwarded()
- } else if protocolMessage := msg.GetProtocolMessage(); protocolMessage != nil {
- if editedMessage := protocolMessage.GetEditedMessage(); editedMessage != nil {
- if extendedText := editedMessage.GetExtendedTextMessage(); extendedText != nil {
- return extendedText.ContextInfo.GetIsForwarded()
+ if ci := ExtractContextInfo(msg); ci != nil {
+ return ci.GetIsForwarded()
+ }
+ if pm := msg.GetProtocolMessage(); pm != nil {
+ if edited := pm.GetEditedMessage(); edited != nil {
+ if ci := ExtractContextInfo(edited); ci != nil {
+ return ci.GetIsForwarded()
}
}
}
return false
}
+
+// ExtractExternalAdReply extracts Meta Ads referral/attribution metadata from
+// incoming Click-to-WhatsApp ad messages. Returns nil when no ad data is present.
+func ExtractExternalAdReply(msg *waE2E.Message) map[string]any {
+ if msg == nil {
+ return nil
+ }
+
+ ci := ExtractContextInfo(UnwrapMessage(msg))
+ if ci == nil {
+ return nil
+ }
+
+ ad := ci.GetExternalAdReply()
+ if ad == nil {
+ return nil
+ }
+
+ referral := make(map[string]any)
+
+ if v := ad.GetCtwaClid(); v != "" {
+ referral["ctwa_clid"] = v
+ }
+ if v := ad.GetSourceURL(); v != "" {
+ referral["source_url"] = v
+ }
+ if v := ad.GetSourceID(); v != "" {
+ referral["source_id"] = v
+ }
+ if v := ad.GetRef(); v != "" {
+ referral["ref"] = v
+ }
+ if v := ad.GetSourceApp(); v != "" {
+ referral["source_app"] = v
+ }
+ if v := ad.GetTitle(); v != "" {
+ referral["ad_title"] = v
+ }
+ if v := ad.GetBody(); v != "" {
+ referral["ad_body"] = v
+ }
+ if v := ad.GetThumbnailURL(); v != "" {
+ referral["thumbnail_url"] = v
+ }
+ if v := ad.GetOriginalImageURL(); v != "" {
+ referral["original_image_url"] = v
+ }
+ if v := ad.GetMediaURL(); v != "" {
+ referral["media_url"] = v
+ }
+ if ad.MediaType != nil {
+ referral["media_type"] = ad.GetMediaType().String()
+ }
+ if ad.ShowAdAttribution != nil {
+ referral["show_ad_attribution"] = ad.GetShowAdAttribution()
+ }
+ if ad.ContainsAutoReply != nil {
+ referral["contains_auto_reply"] = ad.GetContainsAutoReply()
+ }
+ if ad.AutomatedGreetingMessageShown != nil {
+ referral["automated_greeting_message_shown"] = ad.GetAutomatedGreetingMessageShown()
+ }
+ if v := ad.GetGreetingMessageBody(); v != "" {
+ referral["greeting_message_body"] = v
+ }
+ if ad.ClickToWhatsappCall != nil {
+ referral["click_to_whatsapp_call"] = ad.GetClickToWhatsappCall()
+ }
+ if v := ad.GetSourceType(); v != "" {
+ referral["source_type"] = v
+ }
+ if ad.AdType != nil {
+ referral["ad_type"] = ad.GetAdType().String()
+ }
+
+ if len(referral) == 0 {
+ return nil
+ }
+
+ return referral
+}
diff --git a/src/ui/AGENTS.md b/src/ui/AGENTS.md
deleted file mode 100644
index 5697cafb..00000000
--- a/src/ui/AGENTS.md
+++ /dev/null
@@ -1,41 +0,0 @@
-# ui
-
-User interface layer. Three transport modes: REST API, MCP server, WebSocket.
-
-## STRUCTURE
-```
-ui/
-├── rest/ # Fiber HTTP handlers (9 files, 1:1 with domains)
-│ ├── helpers/ # common.go: ResponseSuccess, device resolution
-│ └── middleware/ # basicauth, device, recovery, timeout (+test)
-├── mcp/ # MCP (Model Context Protocol) tools for AI agents
-│ ├── app.go # Login/logout/reconnect tools
-│ ├── group.go # Group management tools (779 lines, largest)
-│ ├── send.go # Message sending tools
-│ ├── query.go # Read-only query tools (chats, messages, devices)
-│ └── helpers/ # MCP-specific utilities
-└── websocket/ # Real-time WebSocket events
-```
-
-## REST HANDLER PATTERN
-Each handler file maps to one domain. Pattern:
-1. Parse request (query params / body)
-2. Build domain request struct
-3. Call `usecase.Method(ctx, request)`
-4. Return JSON response via `helpers.ResponseSuccess`
-
-Device resolution: `helpers.ResolveDevice(c)` extracts from `X-Device-Id` header.
-
-## MCP TOOL PATTERN
-Each MCP file registers tools via `mcp-go`. Same usecase calls as REST, different transport. `query.go` handles read-only operations (chat list, messages, device info).
-
-## CONVENTIONS
-- Query param parsing: use `c.Query("param")` for strings, `strconv` for booleans
-- Boolean query params: parse to `*bool` (nil = not provided)
-- All REST handlers are in `rest/` directory, one file per domain
-- REST has `chatwoot.go` handler for Chatwoot webhook integration
-- Middleware: `basicauth` (optional), `device` (resolve device context), `recovery`, `timeout`
-
-## ANTI-PATTERNS
-- Never put business logic in handlers — delegate to usecase layer
-- Never access infrastructure directly from UI layer
diff --git a/src/usecase/AGENTS.md b/src/usecase/AGENTS.md
deleted file mode 100644
index a52bab01..00000000
--- a/src/usecase/AGENTS.md
+++ /dev/null
@@ -1,24 +0,0 @@
-# usecase
-
-Application use cases. Each file bridges one domain to infrastructure. 1:1 mapping with domain packages.
-
-## KEY FILES
-- `send.go` (1820 lines) — Largest. Handles all message types (text, image, video, document, sticker, audio, poll, contact, location, link)
-- `chat.go` (375 lines) — Chat list, messages, archive, pin, disappearing timer, label
-- `group.go` (614 lines) — Group CRUD, participants, settings
-- `user.go` (413 lines) — User info, avatar, privacy, contacts
-- `message.go` — Message operations (react, delete, revoke, star)
-- `app.go` — Login, logout, reconnect
-- `device.go` — Multi-device management operations
-- `newsletter.go` — Newsletter/channel operations
-
-## CONVENTIONS
-- Each usecase struct: `type serviceX struct { repo, whatsmeow deps }`
-- Device context: use `deviceIDFromContext(ctx)` to get resolved device ID
-- Filter construction: build domain filter struct → pass to repository
-- Pagination: use `GetFilteredChatCount(filter)` for accurate totals (not `GetTotalChatCount`)
-- After any whatsmeow state change, update local chat storage for consistency
-
-## ANTI-PATTERNS
-- Never return stale data after a mutation — sync local DB immediately
-- Never use unscoped queries — always pass device_id via filter or context
diff --git a/src/validations/AGENTS.md b/src/validations/AGENTS.md
deleted file mode 100644
index ea97603f..00000000
--- a/src/validations/AGENTS.md
+++ /dev/null
@@ -1,32 +0,0 @@
-# validations
-
-Input validation using `ozzo-validation`. Each domain has a `*_validation.go` + `*_validation_test.go` pair (16 files total).
-
-## PATTERN
-```go
-func ValidateXxx(ctx context.Context, request *domain.XxxRequest) error {
- return validation.ValidateStruct(request,
- validation.Field(&request.Field, validation.Required, ...),
- )
-}
-```
-
-## FILE MAP
-| Domain | Validation | Test | Notes |
-|--------|-----------|------|-------|
-| send | send_validation.go (516 lines) | send_validation_test.go (1113 lines) | Largest; also `send_validation_test_sticker.go` |
-| group | group_validation.go | group_validation_test.go (708 lines) | Second largest test file |
-| chat | chat_validation.go | chat_validation_test.go | |
-| message | message_validation.go | message_validation_test.go | |
-| user | user_validation.go | user_validation_test.go | |
-| app | app_validation.go | app_validation_test.go | |
-| newsletter | newsletter_validation.go | newsletter_validation_test.go | |
-
-## CONVENTIONS
-- Validation functions are standalone (not methods) for easy testing
-- Test files use table-driven tests with `testify/assert`
-- Context parameter is required even if unused (for future device-scoped validation)
-
-## ANTI-PATTERNS
-- Never validate in usecase or handler — always in this package
-- Never skip writing tests for new validation functions
diff --git a/src/views/AGENTS.md b/src/views/AGENTS.md
deleted file mode 100644
index bc2110c9..00000000
--- a/src/views/AGENTS.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# views
-
-Vue.js 3 frontend components using Semantic UI. Served as embedded HTML via Go's `embed` package.
-
-## STRUCTURE
-```
-views/
-├── components/ # 49 Vue.js components (one per feature)
-│ ├── App*.js # Login, logout, reconnect
-│ ├── Account*.js # Avatar, profile, privacy, contacts
-│ ├── Chat*.js # ChatList, ChatMessages, ChatPinManager, ChatDisappearingManager
-│ ├── Device*.js # DeviceManager
-│ ├── Group*.js # Group operations
-│ ├── Newsletter*.js # Newsletter operations
-│ ├── Send*.js # All message types (text, image, video, etc.)
-│ └── Message*.js # Reactions, deletion, starring
-├── assets/ # CSS, vendor libs
-└── index.html # Main SPA entry (embedded)
-```
-
-## CONVENTIONS
-- Components are plain JS objects (`export default { name, data, methods, template }`)
-- API calls: `window.http.get/post(...)` (axios instance)
-- Modals: Semantic UI `$('#modalName').modal('show')`
-- Errors: `showErrorInfo(message)` global helper
-- Global component refs: `window.XxxComponent = this` in `mounted()`
-- Each component is self-contained with inline `template` string
-
-## ANTI-PATTERNS
-- Never use SFC (`.vue` files) — this project uses plain JS components
-- Never import from node_modules — all deps are loaded via CDN/vendor