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.

refactor: streamline AGENTS documentation and improve clarity across multiple sections

Aldino Kemal9608eedacbf0
diff --git a/.agents/skills/new-release/SKILL.md b/.agents/skills/new-release/SKILL.md
index 30951730..43d9b7de 100644
--- a/.agents/skills/new-release/SKILL.md
+++ b/.agents/skills/new-release/SKILL.md
@@ -1,56 +1,76 @@
---
name: new-release
-description: Prepare and publish a stable GitHub release for this project by updating the hardcoded AppVersion, testing, committing, pushing main, creating the matching tag, and verifying the release. Use only for an explicit $new-release vX.Y.Z invocation.
+description: Publish a stable GOWA release. Use only for an explicit $new-release vX.Y.Z invocation.
---
-# New Release
+# New release
-Publish a stable release from a clean, current `main` checkout. After the sole affirmative confirmation, update only `AppVersion`, test, commit, push `main`, push the tag, and verify the GitHub release. Do not create release notes or run `gh release create`.
+Publish from a clean, current `main` checkout of
+`aldinokemal/go-whatsapp-web-multidevice`: update only `AppVersion`, validate, commit,
+push `main`, push the matching tag, and verify the release created by `release.yml`.
+Release-note editing is a separate task; do not run `gh release create`.
-## Argument contract
+## Input and boundaries
-Accept exactly one argument: a stable version matching `^v[0-9]+\.[0-9]+\.[0-9]+$` (for example, `$new-release v9.1.0`). Reject missing, extra, malformed, whitespace-padded, or prerelease/build-metadata versions. On rejection, stop before preflight and require a new invocation in the literal form `$new-release v9.1.0`; do not request an action token or a bare version. Do not normalize input.
-
-## Safety rules
-
-- Run every Git and GitHub command from the repository root returned by `git rev-parse --show-toplevel`.
-- Never force, move, overwrite, reuse, or delete a branch, tag, or release.
-- Make no mutation before the user replies exactly `yes`.
-- After confirmation, edit only `src/config/settings.go`; commit only that file.
-- Treat only the documented absence statuses as availability. Stop on every command, network, authentication, authorization, parsing, or API error.
+- Accept exactly one stable version matching `^v[0-9]+\.[0-9]+\.[0-9]+$`.
+ Reject missing/extra arguments, surrounding whitespace, prereleases, and build
+ metadata without normalizing them. Ask for a corrected `$new-release vX.Y.Z` invocation.
+- Keep the explicit release gate: no source edits, commits, or pushes before the
+ user replies exactly `yes` to the confirmation below. A confirmation already
+ received for this same checked release remains valid; do not ask again.
+- Run Git/GitHub commands from `git rev-parse --show-toplevel`; run Go from `src/`.
+ Never force, move, overwrite, reuse, or delete branches, tags, or releases.
+- Authentication, permission, network, or parsing failures do not prove absence.
+ Stop on failed checks; do not repair repository state or retry failed publishing mutations.
## Preflight
-1. Read fetch URLs with `git remote get-url --all origin` and push URLs with `git remote get-url --push --all origin`. Require each command to succeed and return exactly one nonempty URL; call them `fetch_url` and `push_url`. Normalize each with `gh repo view <url> --json nameWithOwner --jq .nameWithOwner` and require both to equal `aldinokemal/go-whatsapp-web-multidevice`. Require `gh auth status` to succeed.
-2. Run `git fetch origin main --tags --prune`. Require branch `main`, empty `git status --porcelain=v1`, and `git rev-parse HEAD` exactly equal to `git rev-parse origin/main`. Record that SHA as `base_sha` and its subject.
-3. In `src/config/settings.go`, find exactly one declaration matching `^\s*AppVersion\s*=`. Extract its quoted value as `current_version`. Require it to be a stable version and not equal the requested version. Do not edit it yet.
-4. Check exact local ref `refs/tags/<version>` with `git show-ref --verify --quiet`. Continue only on expected absent exit status; stop if present or any other error. Check exact remote ref with `git ls-remote --exit-code --refs --tags <push_url> refs/tags/<version>`; continue only on exit status `2` (absent), stop on `0` (present) or any other result.
-5. Run `gh api -i repos/aldinokemal/go-whatsapp-web-multidevice/releases/tags/<version>`. Continue only after an explicit HTTP `404` not-found response. Stop if a release is returned or any other API, network, authentication, authorization, or permission error occurs.
-6. Run `go test ./...` from `src/`, require success, then return to the repository root.
-7. Show exact repository, requested version, detected `current_version`, full `base_sha`, and subject. Output this confirmation prompt verbatim, replacing only placeholders: `Update AppVersion to <version>, commit, push main, and tag the release? [yes/no]`
-
-## Confirmation, version commit, and tag push
-
-Stop without mutation unless the user replies exactly `yes`.
-
-Immediately before mutation, repeat preflight steps 1, 2, 4, and 5. Require the freshly read `HEAD` and `origin/main` both equal `base_sha`, clean porcelain status, and unchanged tag/release absence. Re-read `AppVersion` and require it still equals `current_version`.
-
-Then perform this sequence:
-
-1. Change the single `AppVersion` declaration in `src/config/settings.go` to the requested version. Do not alter whitespace or any other file.
-2. Require `git diff --check` to succeed. Require `git diff --name-only` to output only `src/config/settings.go`, and require the diff to replace exactly the `AppVersion` quoted value from `current_version` to the requested version.
-3. Run `go test ./...` from `src/` and require success. Return to the repository root.
-4. Stage exactly `src/config/settings.go`. Require `git diff --cached --name-only` to output only that path. Create exactly one commit with `git commit -m "chore(release): <version>"`. Record `release_sha=$(git rev-parse HEAD)` and require it differs from `base_sha`.
-5. Push only the release commit to main using `git push origin HEAD:refs/heads/main`. If the push fails, stop without retrying, forcing, resetting, or cleaning up. Read `git rev-parse HEAD`, `git rev-parse origin/main`, and `git status --porcelain=v1`; report the evidence and ask for direction.
-6. Run `git fetch origin main --tags --prune`; require local `HEAD`, freshly read `origin/main`, and `release_sha` all equal. Recheck exact local and remote tag absence and exact release HTTP `404` as above.
-7. Run `git tag <version> <release_sha>` followed by `git push origin refs/tags/<version>:refs/tags/<version>`. Do not add force flags or push any other ref. If tag creation fails, stop and report it. If tag push fails, do not retry, delete, force, or clean up. Read back the exact local and remote tag refs and report each as `present`, `absent`, or `unknown` when its read-back has an operational error; then stop.
-
-## Workflow verification
-
-For no more than two minutes after the tag push, poll `gh run list --workflow release.yml --branch <version> --json databaseId,event,headSha,status,conclusion,url --limit 20`. Select only a run whose `event` is `push` and whose `headSha` equals `release_sha`; show each observed status/progress. Stop and report failure if no matching push run appears before the deadline.
-
-Run `gh run watch <run-id> --exit-status`. Require success and report terminal state and URL. Then run `gh release view <version> --json tagName,isDraft,isPrerelease,url,publishedAt,targetCommitish`; require exact `tagName`, `isDraft=false`, `isPrerelease=false`, and `targetCommitish` equal to `release_sha`; then report the published release URL. Stop and report any mismatch or lookup error.
-
-## Failure reporting
-
-On every stop, state the failed check, observed safe evidence, and whether a mutation has occurred. Before confirmation, report that no mutation was performed. After the version commit or `main` push, report local and remote SHA/status evidence and ask for direction; never repair state autonomously. After a pushed tag, report the failed workflow or release evidence and ask the user for direction.
+1. Read all `origin` fetch and push URLs with `git remote get-url --all origin` and
+ `git remote get-url --push --all origin`. Each must return exactly one nonempty URL.
+ Resolve each with `gh repo view <url> --json nameWithOwner --jq .nameWithOwner`;
+ both must equal the repository above. Require successful `gh auth status`.
+2. Fetch `origin main --tags --prune`. Require branch `main`, clean
+ `git status --porcelain=v1`, and `HEAD == origin/main`. Record the full `base_sha`
+ and subject. In `src/config/settings.go`, require exactly one `AppVersion`
+ declaration with a quoted stable `current_version` different from the requested version.
+3. Establish tag/release absence: local `git show-ref --verify --quiet refs/tags/<version>`
+ must exit `1`; remote `git ls-remote --exit-code --refs --tags <push_url> refs/tags/<version>`
+ must exit `2`; `gh api -i repos/aldinokemal/go-whatsapp-web-multidevice/releases/tags/<version>`
+ must return explicit HTTP `404`. A present ref/release or any other error stops the workflow.
+4. Show the repository, requested/current versions, full `base_sha`, and subject. Ask:
+ `Update AppVersion to <version>, commit, push main, and tag the release? [yes/no]`
+
+## Publish after confirmation
+
+Recheck preflight facts immediately before editing: URLs/repository/auth, clean
+`main`, fresh `origin/main == HEAD == base_sha`, unchanged `current_version`, and
+exact tag/release absence. If any differs, stop and report the changed fact.
+
+1. Replace only the quoted `AppVersion` value. Require `git diff --check` and verify
+ that the entire diff is that one replacement in `src/config/settings.go`.
+2. Run `go test ./...` from `src/` and require success. This validates the release
+ candidate; do not also require an unchanged baseline suite before confirmation.
+3. Stage only `src/config/settings.go`; verify the staged diff is still exactly
+ that version replacement. Commit `chore(release): <version>` and record the full
+ `release_sha`, which must differ from `base_sha`.
+4. Push `origin HEAD:refs/heads/main`, fetch `origin main --tags --prune`, and require
+ `HEAD == origin/main == release_sha`. Recheck local/remote tag and release absence.
+5. Create `git tag <version> <release_sha>` and push only
+ `origin refs/tags/<version>:refs/tags/<version>`.
+
+## Completion and failure
+
+After the tag push, allow up to two minutes for `gh run list --workflow release.yml
+--branch <version> --json databaseId,event,headSha,status,conclusion,url --limit 20`
+to show a `push` run with `headSha == release_sha`. This deadline is for run
+appearance, not build completion. Follow the matching run to a terminal result
+and require success; report its URL and any failed jobs.
+
+Read `gh release view <version> --json tagName,isDraft,isPrerelease,url,publishedAt,targetCommitish`.
+Require the exact tag, a published non-draft/non-prerelease release, and
+`targetCommitish == release_sha` before reporting the release URL as complete.
+
+On failure, report the failed check and completed mutations. After a commit/main
+push, include local and freshly read remote SHA/status evidence. After a tag-push
+failure, report exact local/remote refs as present, absent, or unknown on read errors.
+Do not retry, reset, delete, or clean up failed publishing state; ask for direction.
diff --git a/.agents/skills/update-release-note/SKILL.md b/.agents/skills/update-release-note/SKILL.md
index 0695a2d7..c9f7ff75 100644
--- a/.agents/skills/update-release-note/SKILL.md
+++ b/.agents/skills/update-release-note/SKILL.md
@@ -1,8 +1,17 @@
---
name: update-release-note
-description: Use the GitHub CLI to update a GitHub release note while preserving the style of previous release notes.
+description: Update an existing GitHub release's notes when asked, preserving the style of recent releases.
---
-# Update Release Note
+# Update release notes
-Use the GitHub CLI to update the release note description. Follow the style and formatting of previous release notes.
+Resolve the requested repository and release tag. Read its current body and the
+previous release with `gh release view <tag> --json name,body,url`; release-list
+JSON does not include `body`. Inspect commits/PRs between the relevant tags to
+support each change listed, while retaining existing accurate content and links.
+
+Match the established language, headings, and contributor/changelog format. Write
+the complete intended Markdown to a temporary file and use `gh release edit <tag>
+--notes-file <path>` for the authorized update. Read the release back to verify the
+stored body, then return its URL. Creating a release or changing version/tag metadata
+requires a separate request.
diff --git a/AGENTS.md b/AGENTS.md
index 8a42d89a..4ae38747 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,137 +1,78 @@
-# PROJECT KNOWLEDGE BASE
-
-Generated: 2026-06-06
-Commit: 8c4ea8f
-Branch: fix/chatwoot-postgres
-
-## OVERVIEW
-
-Go WhatsApp Web Multi-Device is a Go 1.26.0 WhatsApp Web API server. MCP is not a separate mode: the `rest`
-command serves it at `/mcp` (streamable HTTP) whenever `config.McpEnabled` is true.
-It uses whatsmeow sessions, Fiber, plain Vue 3 modules, and SQLite-backed chat/session storage by default.
-
-## STRUCTURE
-
-```text
-go-whatsapp-web-multidevice/
-|-- src/ # Go module root; run Go commands here
-| |-- main.go # go:embed views, then cmd.Execute
-| |-- cmd/ # Cobra root, rest (mounts MCP), global app wiring
-| |-- config/ # Mutable package globals bound from flags/env
-| |-- domains/ # Interfaces and DTOs; see child AGENTS
-| |-- usecase/ # Business orchestration; see child AGENTS
-| |-- validations/ # ozzo-validation plus table tests
-| |-- ui/ # REST, MCP, websocket adapters
-| |-- infrastructure/
-| | |-- whatsapp/ # Device manager, events, presence pulse, JID utilities
-| | |-- chatstorage/ # chat/message/device SQL repository
-| | `-- chatwoot/ # Chatwoot REST sync and direct PG import
-| | `-- pgimport/ # Direct Chatwoot Postgres importer; see child AGENTS
-| |-- views/ # Embedded Vue 3 plain JS UI
-| |-- statics/ # Runtime media, QR codes, send items
-| `-- storages/ # Runtime SQLite DBs and history dumps
-|-- docs/ # OpenAPI, webhook payload, Chatwoot docs
-|-- docker/ # Multi-stage Alpine image and entrypoint
-|-- gallery/ # Project logo assets
-`-- .github/workflows/ # Docker publish, release, latest promotion
-```
-
-## WHERE TO LOOK
-
-| Task | Location | Notes |
-|------|----------|-------|
-| Add message type | `src/domains/send/`, `src/usecase/send.go`, `src/ui/rest/send.go` | REST is primary; MCP support is selective. |
-| Add quoted reply support | `src/domains/send/`, `src/usecase/send.go`, `src/views/components/Send*.js` | Optional `reply_message_id`; use device-scoped quote lookup. |
-| Add REST endpoint | `src/ui/rest/`, `src/usecase/`, `src/domains/` | Handler parses request, usecase validates/executes, domain owns DTO/interface. |
-| Add MCP tool | `src/ui/mcp/` | Register in `Add*Tools`; resolve a device with `resolveDeviceContext` (`src/ui/mcp/device.go`). |
-| Handle WhatsApp event | `src/infrastructure/whatsapp/event_*.go` | Register the concrete event in `event_handler.go`. |
-| Presence behavior | `src/infrastructure/whatsapp/event_handler.go`, `presence_pulse.go`, `src/cmd/helpers.go` | Connect-time and scheduled pulse presence. |
-| Add chat storage method | `src/domains/chatstorage/interfaces.go`, `sqlite_repository.go`, `chatstorage_wrapper.go` | Update domain, repository, and wrapper together. |
-| Add DB migration | `src/infrastructure/chatstorage/sqlite_repository.go` `getMigrations()` | Append only. Current list has 29 migrations. |
-| Add UI component | `src/views/components/`, `src/views/index.html` | Plain JS modules, no `.vue` single-file components. |
-| Device management | `src/infrastructure/whatsapp/device_manager.go` | Central registry and purge/load/create logic. |
-| Chatwoot integration | `src/infrastructure/chatwoot/` and `src/ui/rest/chatwoot.go` | REST sync, public webhook, optional direct Postgres import. |
-| Direct Chatwoot import | `src/infrastructure/chatwoot/pgimport/` | Direct Chatwoot schema writes; see child AGENTS. |
-| Chatwoot link/retry state | `src/infrastructure/chatstorage/sqlite_repository.go`, `src/infrastructure/whatsapp/webhook_forward.go` | Message links, read/delete sync, and persistent forward retries. |
-| CLI flags / config | `src/cmd/root.go`, `src/config/settings.go`, `src/.env.example` | Flags and env mutate config package globals. |
-| Shared helpers | `src/pkg/utils/`, `src/pkg/error/`, `src/pkg/sqlite/` | Utilities, aliased package errors, and CGO/purego SQLite driver selection. |
-| Docker/release | `docker/golang.Dockerfile`, `.github/workflows/*.yaml` | Multi-arch Docker, tag/manual workflows, generated GoReleaser configs. |
-
-## CODE MAP
-
-| Symbol | Type | Location | Role |
-|--------|------|----------|------|
-| `cmd.Execute` | function | `src/cmd/root.go` | Stores embedded views and runs Cobra root command. |
-| `initApp` | function | `src/cmd/root.go` | Creates folders, DBs, WhatsApp client, device manager, repositories, and usecases. |
-| `DeviceManager` | struct | `src/infrastructure/whatsapp/device_manager.go` | Owns active device registry and persisted device records. |
-| `DeviceInstance` | struct | `src/infrastructure/whatsapp/device_instance.go` | Wraps per-device ID, JID, client, state, and storage. |
-| `IChatStorageRepository` | interface | `src/domains/chatstorage/interfaces.go` | Storage contract for chats, messages, edits, calls, stats, schema, and device records. |
-| `SQLiteRepository` | struct | `src/infrastructure/chatstorage/sqlite_repository.go` | Implements chat storage, Chatwoot link/retry state, and inline migrations. |
-| `deviceChatStorage` | wrapper | `src/infrastructure/whatsapp/chatstorage_wrapper.go` | Injects or enforces device scoping for event-side storage access. |
-| `StartPresencePulseScheduler` | function | `src/infrastructure/whatsapp/presence_pulse.go` | Periodically marks connected devices available, then unavailable. |
-| `StartChatwootForwardRetryWorker` | function | `src/infrastructure/whatsapp/webhook_forward.go` | Replays queued WhatsApp-to-Chatwoot forward failures. |
-| `NormalizeJIDFromLID` | function | `src/infrastructure/whatsapp/jid_utils.go` | Converts `@lid` JIDs to phone JIDs where whatsmeow can resolve them. |
-| `pgimport.Importer` | struct | `src/infrastructure/chatwoot/pgimport/conn.go` | Direct Chatwoot Postgres importer for historical messages. |
-| `DeviceMiddleware` | middleware | `src/ui/rest/middleware/device.go` | Resolves `X-Device-Id` or `device_id` and injects device context. |
-| `resolveDeviceContext` | helper | `src/ui/mcp/device.go` | Resolves the MCP call's device: `device_id` tool argument, else the `X-Device-Id`-derived device from `route.go`'s `HTTPContextFunc`, else error. |
-
-## CONVENTIONS
-
-- Go commands run from `src/`; the repo root is not the Go module root.
-- Local runtime paths are relative to process cwd, so direct local runs should start from `src/`.
-- Config priority is Cobra flags, then env/Viper, then `.env` loaded from `src/`.
-- MCP is not a separate process: `rest` mounts it at `/mcp` in the same app initialization, sharing one whatsmeow state.
-- Process-wide helpers in `cmd/helpers.go` guard auto-reconnect and presence-pulse startup for the shared REST+MCP process.
-- `domains/` defines DTOs and interfaces. Current contracts expose some whatsmeow and multipart types; follow existing contracts but do not add executable business logic there.
-- Usecases validate first, then obtain the device/client from context, then call whatsmeow/storage.
-- Device-scoped REST routes must pass `whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c))`.
-- MCP device resolution: `route.go`'s `HTTPContextFunc` resolves the connection's `X-Device-Id` header into context (an empty header resolves the default/only device); `resolveDeviceContext` (`src/ui/mcp/device.go`) lets a per-call `device_id` tool argument override it, else errors.
-- Optional boolean filters use `*bool` so nil means "not provided".
-- Tests are colocated as `*_test.go`, mostly table-driven with `testify/assert` and occasional `testify/suite`.
-- Tests that mutate config, package globals, or background worker state should stay serial and restore state with `defer`.
-- Chatwoot direct Postgres import is for history. Live forwarding still uses REST plus link/retry storage.
-
-## ANTI-PATTERNS
-
-- Do not query chats or messages without `device_id` scoping for user-facing/device-scoped flows.
-- Do not use `instance.ID()` as the chat/message table `device_id` after login; use `client.Store.ID.ToNonAD().String()` when deriving the WhatsApp storage identity.
-- Do not use raw `@lid` event JIDs for DB lookups; normalize with `NormalizeJIDFromLID()` first.
-- Do not add `IChatStorageRepository` methods without updating `chatstorage_wrapper.go` and the concrete repository.
-- Do not insert migrations in the middle of `getMigrations()`; append new entries only.
-- Do not remove the `evt.Sender.Device != 0` receipt check; it prevents duplicate webhook deliveries from linked devices.
-- Do not put generated/runtime media, QR codes, SQLite DBs, `.env`, or history dumps into source-oriented docs or commits unless explicitly requested.
-- Do not treat Chatwoot direct Postgres import as the live forwarding path; keep REST media handling and direct DB idempotency separate.
-
-## UNIQUE STYLES
-
-- Cobra subcommands are registered by `init()` side effects in `cmd/rest.go`; there is no separate `cmd/mcp.go` — `rest` mounts MCP itself.
-- The app uses mutable package globals for config, clients, repositories, and usecases instead of dependency injection from `main`.
-- MCP exposes 5 consolidated tools (`src/ui/mcp/`) — `whatsapp_send`, `whatsapp_message`, `whatsapp_chat`, `whatsapp_group`, `whatsapp_app` — each dispatching on a `type`/`action` argument, versus one REST route per operation.
-- Chat storage migrations are Go string literals in the repository, not external migration files.
-- The embedded UI uses Vue 3 from CDN, Fomantic UI modals/toasts, and custom delimiters `[[`, `]]`.
-- Release workflows generate GoReleaser YAML into `/tmp`; there is no committed `.goreleaser.yml`.
-- `AppVersion` is hard-coded as `v8.6.0` in `src/config/settings.go`; release workflows do not inject it with ldflags.
-- `src/pkg/error` declares package name `error`; import it with aliases such as `pkgError`.
-- Default SQLite builds use CGO `github.com/mattn/go-sqlite3`; `-tags purego` switches to `modernc.org/sqlite`.
-
-## COMMANDS
-
-```bash
-cd src && go run . rest
-cd src && go build -o whatsapp
-cd src && go test ./...
-cd src && go vet ./...
-cd src && go mod tidy
-docker compose up --build
+# Working on GOWA
+
+GOWA is a Go WhatsApp API server using whatsmeow, Fiber, and SQLite. The Go module
+and local runtime directory are `src/`. `rest` also mounts MCP at `/mcp` when
+enabled; both transports share the same device manager and usecases.
+
+## Working scope and completion
+
+- Read the nearest scoped `AGENTS.md` and the source relevant to the task. Use the
+ entry points below as needed; a small edit does not require a full repository tour.
+- Continue authorized local edits, checks, and fixes until the requested behavior
+ is verified or a concrete blocker remains. Report the result, checks, and limitations.
+- Preserve unrelated working-tree changes. Keep `.env`, SQLite databases, session
+ data, QR codes, generated media, and history dumps out of commits.
+- Local tests using temporary databases, mocks, and fake clients can be run and
+ repaired within the task without repeated approval. Running the app against saved
+ sessions can reconnect real WhatsApp devices; use that runtime only within the
+ user's authorized scope.
+
+## Task entry points
+
+- API contracts and business behavior: [domains](src/domains/AGENTS.md),
+ [usecases](src/usecase/AGENTS.md), and [validation](src/validations/AGENTS.md).
+- REST, MCP, and websocket transport: [UI adapters](src/ui/AGENTS.md). For MCP
+ authentication, use [the OAuth guide](docs/mcp-oauth.md).
+- Device lifecycle, events, JIDs, and presence: [WhatsApp infrastructure](src/infrastructure/whatsapp/AGENTS.md).
+ For webhook payload changes, consult [the payload contract](docs/webhook-payload.md).
+- SQL queries, migrations, and cleanup: [chat storage](src/infrastructure/chatstorage/AGENTS.md).
+- Chatwoot routing, live sync, and history: [Chatwoot infrastructure](src/infrastructure/chatwoot/AGENTS.md)
+ and [configuration](docs/chatwoot.md). Direct Postgres changes have a [scoped guide](src/infrastructure/chatwoot/pgimport/AGENTS.md).
+- Embedded browser UI: `src/views/components/` and `src/views/index.html`. These are
+ plain Vue 3 modules loaded from CDN, with Fomantic UI and `[[`, `]]` delimiters.
+- Startup and configuration: `src/cmd/root.go`, `src/cmd/rest.go`,
+ `src/cmd/helpers.go`, `src/config/settings.go`, and `src/.env.example`. Configuration
+ and service wiring use package globals; flags override env/Viper and `.env` defaults.
+- Packaging: `docker/golang.Dockerfile`, `docker/entrypoint.sh`, and `.github/workflows/`.
+ Read toolchain versions from those files and `src/go.mod`. `AppVersion` is a source
+ constant in `src/config/settings.go`; release builds do not inject it with ldflags.
+ Release jobs require a pushed tag and generate GoReleaser configuration in `/tmp`;
+ there is no committed `.goreleaser.yml`. Docker image publication is tag/manual driven.
+- Publishing a stable release: use [new-release](.agents/skills/new-release/SKILL.md)
+ only when explicitly invoked. For an existing release's notes, use
+ [update-release-note](.agents/skills/update-release-note/SKILL.md).
+
+## Cross-layer contracts
+
+- Keep transport parsing in `ui/`, orchestration in `usecase/`, and DTOs/interfaces
+ in `domains/`. Preserve JSON/form fields used by REST, MCP, and browser clients.
+- User-facing chat/message access must carry device scope. After login, storage
+ uses `client.Store.ID.ToNonAD().String()`, not the user-facing device alias.
+- Repository interface changes must reach all three layers:
+ `src/domains/chatstorage/interfaces.go`, `src/infrastructure/chatstorage/sqlite_repository.go`,
+ and `src/infrastructure/whatsapp/chatstorage_wrapper.go`.
+- Tests that mutate config, package globals, or scheduler state stay serial and
+ restore that state. Use existing colocated test helpers and stubs.
+
+## Local commands and validation
+
+Run Go commands from `src/`:
+
+```sh
+go test ./path/to/affected/package/...
+go test ./...
+go vet ./...
+go build -o whatsapp .
+go run . rest
```
-## NOTES
+Choose checks for the changed behavior. Use the full suite for shared contracts,
+startup, or broad changes; repeat checks when edits or failures justify it. For
+Markdown-only changes, check the diff and references; application tests are unnecessary.
+Default SQLite builds use CGO; `-tags purego` selects `modernc.org/sqlite` when that
+build variant is relevant. Run `go mod tidy` when changing dependencies.
-- Docker builds use `docker/golang.Dockerfile`, Go `1.25-alpine3.23`, CGO, and a final non-root `gowauser` process after the entrypoint fixes volume ownership.
-- Docker Compose mounts root-level `./storages` and `./statics` into `/app`; direct local runs from `src/` use `src/storages` and `src/statics`.
-- Docker publish is tag/manual driven. Arch-specific `-amd`, `-arm`, and `-armv7` images are merged into a versioned manifest; `latest` is also promoted by workflows.
-- `release.yml` declares `workflow_dispatch`, but release jobs are still guarded to tag refs.
-- GitHub workflows are release/publish oriented; there is no PR workflow that runs `go test`, `go vet`, or lint.
-- `DBKeysURI` defaults to the main DB URI when empty; avoid in-memory keys storage in production because privacy tokens must survive long-lived sessions.
-- `status@broadcast` chat names intentionally resolve to `Status`.
-- `src/.air.toml` excludes `statics` and `storages`; keep hot reload from watching runtime data.
+Runtime paths are relative to the process directory. Direct runs use `src/storages`
+and `src/statics`; Docker Compose mounts the root-level directories into `/app`.
+Keep these paths excluded from hot reload in `src/.air.toml`. The Docker entrypoint
+fixes volume ownership before dropping to `gowauser`.
diff --git a/src/domains/AGENTS.md b/src/domains/AGENTS.md
index 7fdd5cc8..e14ca8b0 100644
--- a/src/domains/AGENTS.md
+++ b/src/domains/AGENTS.md
@@ -1,43 +1,19 @@
-# DOMAINS
-
-Generated: 2026-06-06
-
-## OVERVIEW
-
-Domain packages hold request/response DTOs and interfaces for usecases and storage. They are contracts, not execution layers.
-
-## STRUCTURE
-
-```text
-domains/
-|-- app/ chat/ device/ group/ message/ newsletter/ user/
-|-- send/ # one file per send request type plus combined sender interface
-`-- chatstorage/ # chat/message/edit/device storage entities, filters, repository interface
-```
-
-## WHERE TO LOOK
-
-| Task | Location | Notes |
-|------|----------|-------|
-| Add send request | `send/<type>.go`, `send/interfaces.go` | Keep `BaseRequest` embedding if the request targets a chat/contact. |
-| Add reply field | `send/text.go`, media request DTOs | Optional `ReplyMessageID *string` serializes as `reply_message_id`. |
-| Add usecase contract | `<domain>/interfaces.go` | Return the domain interface from `usecase.New*Service`. |
-| Add chat storage method | `chatstorage/interfaces.go` | Also update concrete repository and WhatsApp storage wrapper. |
-| Add Chatwoot storage state | `chatstorage/chatstorage.go`, `chatstorage/interfaces.go` | Link and retry queue contracts must remain device-scoped. |
-| Add response field | Matching DTO file | Check REST/MCP serialization expectations before renaming JSON fields. |
-
-## CONVENTIONS
-
-- DTOs use JSON tags for API payloads and may include form/multipart fields where existing request types already do.
-- Send requests are split by message type, but `ISendUsecase` composes smaller sender interfaces for compatibility.
-- Chat filters use pointer booleans, for example `*bool`, when "not set" differs from `false`.
-- Storage entities carry `DeviceID`; preserve it through chat/message/edit flows.
-- `GetMessageByIDAndDevice` is the device-scoped ID lookup for user/device-isolated flows.
-- `ChatwootMessageLink` and `ChatwootForwardEvent` are storage contracts, not Chatwoot API DTOs.
-- Existing contracts expose whatsmeow types in places. Keep that local to contracts that already need protocol details.
-
-## ANTI-PATTERNS
-
-- Do not put validation rules, SQL, Fiber handlers, MCP tool parsing, or whatsmeow send logic in domain packages.
-- Do not add a chat/message repository method that cannot be scoped by device unless the caller contract is explicitly global.
-- Do not rename JSON fields casually; views, REST clients, MCP tools, docs, and tests may rely on them.
+# Domain contracts
+
+These packages define request/response DTOs and usecase/storage interfaces.
+Validation, SQL, transport parsing, and WhatsApp operations belong in other layers.
+
+- Send DTOs live in `send/`; retain `BaseRequest` where chat/contact targeting uses
+ it. `send/interfaces.go` composes the smaller sender interfaces into `ISendUsecase`.
+- Preserve JSON and form tags across REST, MCP, views, docs, and tests. Optional
+ `ReplyMessageID *string` remains `reply_message_id`; boolean filters use `*bool`
+ when omitted and `false` have different meanings.
+- Existing multipart and whatsmeow types may remain in contracts that need them;
+ do not spread protocol dependencies into unrelated DTOs.
+- `chatstorage/chatstorage.go` holds storage entities, including Chatwoot links and
+ retry events. Preserve `DeviceID` throughout message, chat, and edit flows; these
+ Chatwoot entities are persistence contracts, not REST API payloads.
+- For repository changes, use `chatstorage/interfaces.go` and the linked
+ [storage guide](../infrastructure/chatstorage/AGENTS.md). User/device lookups use
+ `GetMessageByIDAndDevice`; chat-specific lookups can use `GetMessageByIDChatAndDevice`.
+ Global methods need an explicitly global caller contract.
diff --git a/src/infrastructure/chatstorage/AGENTS.md b/src/infrastructure/chatstorage/AGENTS.md
index 1d56f5e1..53114bc5 100644
--- a/src/infrastructure/chatstorage/AGENTS.md
+++ b/src/infrastructure/chatstorage/AGENTS.md
@@ -1,40 +1,33 @@
-# CHAT STORAGE
-
-Generated: 2026-06-06
-
-## OVERVIEW
-
-`SQLiteRepository` implements chat, message, edit-history, call, reaction, statistic, schema, and device-record storage behind `domains/chatstorage.IChatStorageRepository`.
-
-## WHERE TO LOOK
-
-| Task | Location | Notes |
-|------|----------|-------|
-| Repository contract | `../../domains/chatstorage/interfaces.go` | Any method addition must be implemented here and in WhatsApp wrapper. |
-| SQL implementation | `sqlite_repository.go` | Single large repository file. |
-| Migrations | `sqlite_repository.go` `getMigrations()` | Append-only list, currently 29 migrations. |
-| Message edit history | `sqlite_repository.go`, `sqlite_repository_edit_test.go` | `message_edits` is append-only history while original message content updates. |
-| Chatwoot links | `sqlite_repository.go`, `../../domains/chatstorage/chatstorage.go` | Maps WhatsApp and Chatwoot IDs for idempotency, read/delete sync, and webhook routing. |
-| Chatwoot retry queue | `sqlite_repository.go` | Persists live forward retry jobs across restarts. |
-| Tests | `sqlite_repository_test.go`, `sqlite_repository_edit_test.go` | Add coverage for schema/data isolation changes. |
-
-## CONVENTIONS
-
-- Default chat storage URI is `file:storages/chatstorage.db`; connection setup is in `cmd/root.go`.
-- `chats` primary key is `(jid, device_id)`; `messages` primary key is `(id, chat_jid, device_id)`.
-- `GetMessages` and `SearchMessages` fail fast if device ID is missing.
-- Use `GetMessageByIDAndDevice` for device-scoped ID lookups such as quoted replies.
-- Use `GetChatByDevice`, `DeleteChatByDevice`, `DeleteMessageByDevice`, and count-by-device variants for scoped flows.
-- `chatwoot_message_links` primary key is `(device_id, wa_message_id)`; link lookups by Chatwoot ID and unread chat are indexed.
-- `chatwoot_forward_queue` uniqueness is `(device_id, event_name, wa_message_id)`; cleanup paths must include it.
-- `CreateMessage` and sent-message storage derive the current device identity from the whatsmeow client context.
-- `status@broadcast` must always produce display name `Status`.
-- Storage tests use real SQLite drivers, including temp DB and in-memory variants.
-
-## ANTI-PATTERNS
-
-- Do not add new user-facing query paths that use `GetChat`, `DeleteChat`, or `GetMessageByID` without confirming device isolation.
-- Do not reorder or edit old migrations for a live DB; append a new migration.
-- Do not build SQL with untrusted string interpolation. Existing dynamic clauses use fixed fragments plus args.
-- Do not forget the device registry operations when changing purge/load behavior.
-- Do not leave Chatwoot link or retry rows behind when truncating all chats or deleting one device.
+# Chat storage
+
+`sqlite_repository.go` implements `domains/chatstorage.IChatStorageRepository`.
+For a contract change, update the domain interface and WhatsApp wrapper together.
+
+## Identity and queries
+
+- `chats` uses `(jid, device_id)`; `messages` uses `(id, chat_jid, device_id)`.
+ Use device-scoped chat, message, delete, and count methods for user-facing flows.
+- `GetMessages` and `SearchMessages` require device IDs. Quote lookups use
+ `GetMessageByIDAndDevice`; use `GetMessageByIDChatAndDevice` when chat identity
+ is part of the request. Do not copy legacy global lookups into scoped flows.
+- Event/sent-message storage derives device identity from the whatsmeow client
+ context. `status@broadcast` must display as `Status`.
+- Parameterize values in SQL; dynamic clauses use fixed fragments plus arguments.
+- `message_edits` retains append-only history while the current message updates.
+
+## Schema and cleanup
+
+- Append migrations to `getMigrations()`; do not reorder or rewrite applied entries.
+ Read the current schema there instead of relying on a documented migration count.
+- `chatwoot_message_links` uses `(device_id, wa_message_id)`; reverse conversation
+ lookup also needs account/config scope. Legacy account `0` is allowed only in
+ legacy single-account mode, never as a wildcard for per-device routing.
+- `chatwoot_forward_queue` uniqueness is `(device_id, event_name, wa_message_id)`.
+ Device deletion/truncation must clean up related links and retry jobs. Config
+ deletion removes its owned links so stale rows cannot route a rebound destination.
+- Preserve device registry operations during purge/load changes. Poll definitions
+ use `(device_id, chat_jid, poll_message_id)` and must retain that scope.
+
+Storage tests use real SQLite with temporary or in-memory databases. For schema,
+isolation, or cleanup changes, cover the affected query and deletion behavior with
+those fixtures; exercise CGO/purego variants when driver behavior is involved.
diff --git a/src/infrastructure/chatwoot/AGENTS.md b/src/infrastructure/chatwoot/AGENTS.md
index a383367b..ee9a777e 100644
--- a/src/infrastructure/chatwoot/AGENTS.md
+++ b/src/infrastructure/chatwoot/AGENTS.md
@@ -1,53 +1,34 @@
-# CHATWOOT INFRASTRUCTURE
-
-Generated: 2026-06-06
-
-## OVERVIEW
-
-This package handles Chatwoot API calls, live sync, historical import, echo-loop suppression, and optional direct Postgres writes for Chatwoot history.
-
-## STRUCTURE
-
-```text
-chatwoot/
-|-- client.go # Chatwoot REST API client: contacts, conversations (find/reopen),
-| # messages (source_id + reply attrs), inbox list/create, echo-loop cache
-|-- provision.go # EnsureInbox: startup auto-create/reuse of the API inbox
-|-- sync.go # Sync service, message import flow, direct-import orchestration
-|-- sync_types.go # Sync DTOs/state
-|-- types.go # Chatwoot API payloads (incl. Inbox, MessageOptions fields)
-`-- pgimport/ # Direct PostgreSQL importer for historical messages; see child AGENTS
-```
-
-## WHERE TO LOOK
-
-| Task | Location | Notes |
-|------|----------|-------|
-| REST API behavior | `client.go` | HTTP calls to Chatwoot, contact lookup, sent-message cache. |
-| Live/history sync | `sync.go` | Uses app/send usecases, storage, and Chatwoot settings. |
-| Direct DB import | `pgimport/` | SQL writer and identity mapping with sqlmock tests; see child AGENTS. |
-| Message links/read/delete | `sync.go`, `../../ui/rest/chatwoot.go`, `../../domains/chatstorage/` | Store mappings for idempotency, read state, webhook replies, and deletes. |
-| Forward retry worker | `../whatsapp/webhook_forward.go`, `../chatstorage/sqlite_repository.go` | Live WhatsApp-to-Chatwoot retries use persistent queue storage. |
-| REST surface | `../../ui/rest/chatwoot.go` | Public webhook plus authenticated manual sync/status endpoints. |
-| Config | `../../config/settings.go`, `../../cmd/root.go` | `CHATWOOT_*` env/flags. |
-
-## CONVENTIONS
-
-- Chatwoot webhook route is public relative to app Basic Auth and is registered before the Basic Auth middleware.
-- Webhook handling accepts only outgoing Chatwoot messages for WhatsApp send-back and skips IDs marked as sent by this app.
-- Outbound Chatwoot messages require a configured/selected device; preserve device context when calling send usecases.
-- Direct import is controlled separately from live REST forwarding.
-- Direct import owns historical non-media rows. Media history may pre-pass through REST only when `CHATWOOT_IMPORT_MEDIA_WITH_REST` is enabled.
-- Mirrored WhatsApp rows use `source_id` values like `WAID:<message_id>` and persistent links for idempotency and echo suppression.
-- `SyncService.Close()` owns closing the direct-Postgres importer pool during REST shutdown.
-- Chatwoot webhook can be public relative to Basic Auth and still require `CHATWOOT_WEBHOOK_SECRET`.
-- Groups and `@lid` contacts use identifier/custom attributes; private chats use normalized phone lookup.
-- Tests include regular sync tests and `pgimport` sqlmock tests.
-
-## ANTI-PATTERNS
-
-- Do not mix direct Postgres historical import with live REST forwarding semantics.
-- Do not treat Chatwoot API inbox identifiers as numeric account or inbox IDs.
-- Do not remove the sent-message cache unless another echo-loop guard exists.
-- Do not log API tokens or raw secrets from Chatwoot config.
-- Do not assume imported media is always downloadable; placeholder behavior is configurable.
+# Chatwoot integration
+
+Use [configuration and routing docs](../../../docs/chatwoot.md) for integration
+changes. `client.go` owns REST calls, `provision.go` inbox setup,
+`client_registry.go` destination routing, and `sync.go` history orchestration.
+Direct Postgres changes have a [scoped guide](pgimport/AGENTS.md).
+
+## Routing and live sync
+
+- Preserve device context on Chatwoot-to-WhatsApp sends. Once per-device configs
+ exist, `ClientRegistry` must not fall back to the global env inbox for an unmapped
+ or disabled device. Numeric account/inbox IDs differ from API-channel identifiers.
+- Webhooks in `../../ui/rest/chatwoot.go` bypass app Basic Auth and check
+ `CHATWOOT_WEBHOOK_SECRET` when configured. Only outgoing messages send back to
+ WhatsApp; preserve `source_id = WAID:<message_id>` and sent-message echo guards.
+- Persistent links support idempotency, replies, read/delete sync, and reverse
+ routing. Preserve device/account/config scope; separate servers can reuse numeric
+ IDs. Per-device webhook URLs disambiguate otherwise ambiguous agent-initiated sends.
+- Install the client registry before starting the persistent forward-retry worker
+ in `../whatsapp/webhook_forward.go`.
+- Private contacts use normalized phone lookup; groups and unresolved `@lid`
+ contacts use identifiers/custom attributes. Keep API tokens and config secrets out of logs.
+
+## History import
+
+- Direct Postgres import is separate from live REST forwarding and is supported
+ only in legacy/env mode with the global DSN. Per-device configs use REST import.
+- Direct import writes historical content/metadata. With
+ `CHATWOOT_IMPORT_MEDIA_WITH_REST`, downloadable media first goes through REST for
+ attachments; shared source IDs prevent duplicate import. Preserve configurable
+ placeholders for media that cannot be downloaded.
+- `SyncService.Close()` closes its importer pool; preserve cleanup of cached sync
+ services on shutdown. Use sync/registry tests for routing changes and `pgimport`
+ sqlmock tests for direct SQL behavior.
diff --git a/src/infrastructure/chatwoot/pgimport/AGENTS.md b/src/infrastructure/chatwoot/pgimport/AGENTS.md
index 95a64c17..f5e44631 100644
--- a/src/infrastructure/chatwoot/pgimport/AGENTS.md
+++ b/src/infrastructure/chatwoot/pgimport/AGENTS.md
@@ -1,50 +1,24 @@
-# CHATWOOT PGIMPORT
-
-Generated: 2026-06-06
-
-## OVERVIEW
-
-`pgimport` writes historical WhatsApp messages directly into Chatwoot's Postgres schema. It is not the live REST forwarding path.
-
-## STRUCTURE
-
-```text
-pgimport/
-|-- conn.go # DB connection, schema/account/inbox verification, importer lifecycle
-|-- identity.go # Chat/contact identity helpers and message type/content rules
-`-- writer.go # ImportChat transaction, contact/conversation/message writes, links
-```
-
-## WHERE TO LOOK
-
-| Task | Location | Notes |
-|------|----------|-------|
-| Open importer | `conn.go` | Verifies required Chatwoot tables plus configured account/inbox. |
-| Import a chat | `writer.go` `ImportChat` | Transaction with contact, contact_inbox, conversation, message loop, links. |
-| Contact identity | `identity.go`, `writer.go` `upsertContact` | Private chats use phone fallback; groups and `@lid` JIDs use identifiers. |
-| Conversation behavior | `writer.go` `findOrCreateConversation` | Reuses latest conversation and mirrors pending/reopen config. |
-| Message idempotency | `writer.go` `insertMessage` | Probe by `inbox_id` and `source_id` before insert. |
-| Content mapping | `identity.go`, `writer.go` `buildContent` | Group incoming messages get sender prefix; media placeholder behavior is configurable. |
-| Tests | `*_test.go` | sqlmock-heavy unit and flow coverage; update expected SQL with schema changes. |
-
-## CONVENTIONS
-
-- Use `source_id = WAID:<whatsapp_message_id>` for imported Chatwoot messages.
-- Preserve WhatsApp timestamps in message rows and anchor new conversations to the first valid message time.
-- Existing individual contact names are preserved; group names may refresh from the latest subject.
-- Per-message failures use savepoints so one bad row can be counted without rolling back the whole import.
-- Direct DB import inserts metadata/content only; REST attachment upload is orchestrated from parent `sync.go` when enabled.
-- `Importer.Close()` is idempotent and is reached through `SyncService.Close()` on REST shutdown.
-
-## ANTI-PATTERNS
-
-- Do not use this package for live Chatwoot forwarding.
-- Do not key idempotency only by conversation; resolved/reopened conversations can move rows.
-- Do not overwrite existing one-to-one contact names when attaching a WhatsApp JID.
-- Do not insert blank Chatwoot messages when both content and media placeholder are empty.
-- Do not bypass account/inbox verification when opening a direct database connection.
-
-## TESTING
-
-- Keep sqlmock expectations close to the SQL shape; broad regexes hide schema regressions.
-- Add focused unit tests for identity/content helpers before changing import flow tests.
+# Direct Chatwoot history import
+
+This package writes historical content/metadata to Chatwoot Postgres. Live sync
+uses REST; optional history attachments are orchestrated through REST in `../sync.go`.
+
+- `conn.go` verifies required tables, account, and inbox before opening an importer.
+ Preserve this verification and idempotent `Importer.Close()` cleanup through the
+ parent sync service.
+- `writer.go` imports each chat transactionally. Per-message savepoints let a bad
+ row be counted without losing the whole chat; a broken transaction/savepoint
+ must still fail the import rather than look like an isolated row failure.
+- Idempotency uses `source_id = WAID:<whatsapp_message_id>` scoped by `inbox_id`,
+ not conversation: a reopened/resolved conversation may change where rows belong.
+- Preserve WhatsApp message timestamps and anchor new conversations to the first
+ valid message time. Reuse the latest conversation and respect pending/reopen config.
+- Private contacts use phone fallback; groups and unresolved `@lid` use identifiers.
+ Preserve existing individual contact names; group names may refresh from the subject.
+- `identity.go` and `buildContent` handle content mapping. Incoming group messages
+ retain the sender prefix. Skip messages whose content and media placeholder are
+ both empty.
+
+Use helper tests for identity/content changes and transaction tests for SQL/flow
+changes. Keep sqlmock expectations specific enough to catch schema and scoping
+regressions, including savepoint failure behavior when that path changes.
diff --git a/src/infrastructure/whatsapp/AGENTS.md b/src/infrastructure/whatsapp/AGENTS.md
index 1e349fc6..0eaf6be4 100644
--- a/src/infrastructure/whatsapp/AGENTS.md
+++ b/src/infrastructure/whatsapp/AGENTS.md
@@ -1,51 +1,30 @@
-# WHATSAPP INFRASTRUCTURE
-
-Generated: 2026-06-06
-
-## OVERVIEW
-
-This package owns whatsmeow clients, multi-device lifecycle, JID normalization, events, send retry helpers,
-presence pulse scheduling, webhook forwarding, and the event-side chatstorage wrapper.
-
-## WHERE TO LOOK
-
-| Task | Location | Notes |
-|------|----------|-------|
-| Device lifecycle | `device_manager.go`, `device_instance.go`, `client_lifecycle.go` | Create/load/purge/reconnect and persisted registry behavior. |
-| Event routing | `event_handler.go`, `event_*.go` | Add new event types to the central switch. |
-| Message webhooks | `event_message.go`, `webhook_forward.go` | Payload construction, media fields, signatures, event filters. |
-| Chatwoot forward retry | `webhook_forward.go` | Queue-backed retries for WhatsApp-to-Chatwoot forward failures. |
-| Send retry / 463 | `send_retry.go`, `key_cache.go` | Reachout timelock retry and privacy-token store wiring. |
-| Presence behavior | `event_handler.go`, `event_chat_presence.go`, `presence_pulse.go` | Connect-time presence, chat presence webhooks, scheduled daily pulses. |
-| History import | `history_sync.go` | Stores chats/messages for history sync batches. |
-| JID conversion | `jid_utils.go`, `context_device.go` | LID normalization and request/device context. |
-| Storage wrapper | `chatstorage_wrapper.go` | Injects device ID into chat/message repository operations. |
-
-## CONVENTIONS
-
-- `DeviceManager` keys the active registry by requested device ID or alias, but logged-in storage identity may become the WhatsApp JID.
-- Chat/message table `device_id` should be the WhatsApp JID without device number: `client.Store.ID.ToNonAD().String()`.
-- Event handlers call `ContextWithDevice(ctx, instance)` before downstream logic.
-- Presence pulse only targets connected and logged-in devices, then returns them to unavailable after the configured duration.
-- Normalize `@lid` JIDs with `NormalizeJIDFromLID(ctx, jid, client)` before DB lookup/storage when a phone JID is needed.
-- Use `ToNonAD()` when persisting or emitting stable non-device JIDs.
-- Webhook forwarding uses goroutines and bounded contexts in selected handlers; keep failures logged without blocking the event loop.
-- `StartChatwootForwardRetryWorker` persists retry jobs in chat storage; queued events need stable `device_id`, event name, and WhatsApp message ID.
-- `chatstorage_wrapper.go` should provide device defaults for scoped repository methods, including message edit and device-scoped ID lookups.
-
-## ANTI-PATTERNS
-
-- Do not store `instance.ID()` as chat/message `device_id` after a real WhatsApp JID is available.
-- Do not bypass `chatstorage_wrapper.go` for event-side chat/message access.
-- Do not add an `IChatStorageRepository` method without implementing the wrapper method.
-- Do not remove the receipt `Device == 0` filter; linked devices produce duplicate receipts.
-- Do not start a second presence pulse loop; `cmd/helpers.go` uses `sync.Once` for process-wide startup.
-- Do not move privacy tokens to a volatile keys DB; long-lived sessions need them in durable primary WhatsApp storage.
-- Do not assume `client`, `client.Store`, or `client.Store.LIDs` is non-nil during LID resolution.
-- Do not replay Chatwoot forward events without device scoping; the retry queue uniqueness depends on it.
-
-## TESTING
-
-- Tests in this package often exercise unexported helpers directly from package `whatsapp`.
-- Webhook tests replace package-level functions/globals and restore them with `defer`; preserve cleanup on new tests.
-- Presence pulse tests use fake clients, injected clocks/sleeps, channels, and timeouts; avoid `t.Parallel` around shared scheduler state.
+# WhatsApp infrastructure
+
+This package owns clients, device lifecycle, JIDs, events, presence, and forwarding.
+
+- Lifecycle: `device_manager.go`, `device_instance.go`, `client_lifecycle.go`.
+ Registry aliases differ from logged-in storage identities: use
+ `client.Store.ID.ToNonAD().String()` for chat/message `device_id`, not `instance.ID()`.
+- Events: register event types in `event_handler.go` and carry
+ `ContextWithDevice(ctx, instance)` downstream. Keep event-side storage access
+ behind `chatstorage_wrapper.go`, including new repository methods.
+- JIDs: use `NormalizeJIDFromLID` in `jid_utils.go` before phone-JID lookups/storage
+ and `ToNonAD()` for stable identities. LID lookup may fail or have nil client,
+ store, or LID store; preserve the original JID fallback.
+- Webhooks: `event_message.go` and `webhook_forward.go`; use
+ [the payload contract](../../../docs/webhook-payload.md) for payload changes.
+ Keep work bounded and failures observable without blocking the event loop.
+ Preserve the `evt.Sender.Device != 0` receipt guard to prevent linked-device duplicates.
+- Chatwoot retries: `StartChatwootForwardRetryWorker` uses durable chat-storage jobs
+ keyed by device, event name, and WhatsApp message ID. Initialize the client registry
+ before the retry worker; preserve device routing when replaying queued events.
+- Presence: `presence_pulse.go` targets connected, logged-in devices, then returns
+ them to unavailable. `../../cmd/helpers.go` guards process-wide startup with
+ `sync.Once`; do not introduce a second scheduler.
+- Session keys: `key_cache.go` redirects selected key stores. Leave privacy tokens
+ in durable primary WhatsApp storage rather than moving them to a volatile keys DB.
+- History: `history_sync.go` handles batches; preserve the same device and JID rules.
+
+Tests commonly exercise unexported helpers and replace package globals. Restore
+replacements and keep scheduler tests serial; use fake clients/clocks and bounded
+waits for presence behavior.
diff --git a/src/ui/AGENTS.md b/src/ui/AGENTS.md
index 603d574b..19814801 100644
--- a/src/ui/AGENTS.md
+++ b/src/ui/AGENTS.md
@@ -1,47 +1,35 @@
-# UI ADAPTERS
-
-Generated: 2026-06-06
-
-## OVERVIEW
-
-`ui/` adapts HTTP REST, MCP tools (streamable HTTP, mounted at `/mcp` by `rest`), and websockets to domain usecases. It should parse transport payloads and delegate behavior.
-
-## STRUCTURE
-
-```text
-ui/
-|-- rest/ # Fiber handlers, helpers, middleware
-|-- mcp/ # MCP tools, route mounting, and device resolution
-`-- websocket/ # Browser device/status broadcast hub
-```
-
-## WHERE TO LOOK
-
-| Task | Location | Notes |
-|------|----------|-------|
-| Add REST route | `rest/<domain>.go` | `InitRest*` registers paths and stores the domain service. |
-| Add REST middleware | `rest/middleware/` | Use `fiber.Test()` for middleware tests. |
-| Add MCP tool | `mcp/<domain>.go` | Define `tool*`, `handle*`, and register in `Add*Tools`. |
-| Device context | `rest/middleware/device.go`, `mcp/route.go`, `mcp/device.go` | REST uses header/query; MCP uses the connection's `X-Device-Id` header (set in `route.go`'s `HTTPContextFunc`), overridable per call by a `device_id` tool argument (`resolveDeviceContext`), else the default/only device. |
-| Send transport fields | `rest/send.go`, `mcp/send.go` | REST receives full send DTOs; MCP send is a smaller tool subset with manual args. |
-| Chatwoot webhook | `rest/chatwoot.go` | Public route, optional shared secret, echo suppression, read/delete sync. |
-| Websocket changes | `websocket/websocket.go`, `../views/index.html` | Browser connects with `?device_id=`. |
-
-## CONVENTIONS
-
-- REST handlers parse request bodies with Fiber, add uploaded files from `FormFile`, sanitize phones where existing handlers do, then call usecases.
-- REST success payloads use `utils.ResponseData{Status: 200, Code: "SUCCESS", Message: ..., Results: ...}`.
-- Device management routes are registered outside `DeviceMiddleware`; most operational routes are wrapped by it.
-- Chatwoot webhook is registered before basic auth so Chatwoot can POST without the app's Basic Auth header.
-- If `CHATWOOT_WEBHOOK_SECRET` is set, the public Chatwoot webhook must pass the shared-secret check before sending to WhatsApp.
-- MCP handlers validate argument types manually and return `mcp.NewToolResultText(...)`.
-- MCP handlers must resolve the device via `resolveDeviceContext` (`mcp/device.go`) before device-bound usecase calls.
-- MCP exposes 5 consolidated tools: `whatsapp_send`, `whatsapp_message`, `whatsapp_chat`, `whatsapp_group`, `whatsapp_app`; each dispatches on a `type`/`action` argument rather than being one tool per operation.
-
-## ANTI-PATTERNS
-
-- Do not put WhatsApp business logic in REST/MCP handlers.
-- Do not assume every MCP call carries a `device_id` argument; fall through to the connection's `X-Device-Id`-derived device via `resolveDeviceContext`, and only then the default/only device.
-- Do not register device-scoped REST operations outside `DeviceMiddleware`.
-- Do not expose new unauthenticated REST paths unless they are health checks or explicitly public webhooks.
-- Do not remove Chatwoot `source_id` and sent-message cache echo guards without a replacement loop breaker.
+# Transport adapters
+
+`rest/`, `mcp/`, and `websocket/` parse transport inputs and delegate to domain
+usecases. REST and MCP share the `rest` process and device manager.
+
+## REST and websockets
+
+- `rest/<domain>.go` registers routes with `InitRest*`. Parse bodies/files and use
+ the existing `utils.ResponseData` success envelope (`Status: 200`, `Code: "SUCCESS"`).
+- Device operations belong behind `DeviceMiddleware`; management routes sit
+ outside it. Pass `whatsapp.ContextWithDevice(c.Context(), getDeviceFromCtx(c))`
+ to device-bound usecases. Browser websockets select a device with `?device_id=`.
+- Route/auth order lives in `../cmd/rest.go`. Chatwoot webhooks are mounted before
+ Basic Auth but enforce `CHATWOOT_WEBHOOK_SECRET` when configured. Keep manual
+ sync/config routes authenticated and preserve webhook device routing and echo guards.
+ New public routes need an explicit public contract, such as a health check or webhook.
+
+## MCP
+
+- `mcp/<domain>.go` defines tools/handlers and registers them via `Add*Tools`.
+ The consolidated `whatsapp_send`, `whatsapp_message`, `whatsapp_chat`,
+ `whatsapp_group`, and `whatsapp_app` tools dispatch on `type` or `action`.
+ MCP send arguments cover a subset of REST DTOs; validate types and preserve result formats.
+- Resolve device-bound calls with `resolveDeviceContext` in `mcp/device.go`:
+ explicit `device_id` overrides the device injected by `mcp/route.go` from
+ `X-Device-Id`. An empty header may resolve the default/only device at the HTTP
+ layer. If no device reaches the tool, resolution returns an error.
+- Keep streaming disabled in the Fiber adaptor: an idle GET SSE connection can
+ retain a goroutine/connection until shutdown. `mcp/route.go` mounts POST and DELETE.
+- For authentication changes, read [MCP OAuth](../../docs/mcp-oauth.md) and
+ `../cmd/mcp_oauth.go`. OAuth-protected MCP mounts before global Basic Auth;
+ when OAuth is disabled, MCP uses the ordinary authenticated router.
+
+Use the relevant handler tests, Fiber's `app.Test`, or MCP tool tests for changed
+routing, auth, parsing, and device resolution behavior.
diff --git a/src/usecase/AGENTS.md b/src/usecase/AGENTS.md
index 54f81526..7658a669 100644
--- a/src/usecase/AGENTS.md
+++ b/src/usecase/AGENTS.md
@@ -1,42 +1,26 @@
-# USECASE
-
-Generated: 2026-06-06
-
-## OVERVIEW
-
-Usecases orchestrate validation, device/client lookup, WhatsApp operations, storage, and response mapping.
-
-## WHERE TO LOOK
-
-| Task | Location | Notes |
-|------|----------|-------|
-| Send message/media | `send.go` | Largest file; handles text, media, links, contacts, polls, presence, quote context, and stored sent messages. |
-| Quoted replies | `send.go` `mergeReplyContext` | Uses `GetMessageByIDAndDevice(deviceIDFromContext(ctx), id)` before setting `ContextInfo`. |
-| Chat listing/history | `chat.go` | Device ID comes from context and must reach chat/message filters. |
-| Message actions | `message.go` | Reaction/revoke may use global ID lookup to resolve sender for WhatsApp protocol behavior. |
-| Group operations | `group.go` | Handles participant JID conversion, names, invite links, and group settings. |
-| Account/user operations | `user.go` | Uses current device client and chat storage. |
-| Device operations | `device.go` | Delegates to `whatsapp.DeviceManager`. |
-
-## CONVENTIONS
-
-- Constructor names are `New*Service` and return the matching domain interface.
-- Validate before doing network/storage work: `validations.Validate*`.
-- Resolve WhatsApp clients from context with `whatsapp.ClientFromContext(ctx)`.
-- For chat history, derive device scope with `deviceIDFromContext(ctx)` and pass it to repository filters.
-- For send operations, sanitize/validate phone/JID, build whatsmeow payloads, send, then store sent messages with context when appropriate.
-- `wrapSendMessage` uses `whatsapp.SendMessageWithReachoutRetry`; keep 463 normalization in this layer aligned with infrastructure retry behavior.
-- Preserve existing error style: package errors from `pkg/error`, wrapped validation errors, and direct `fmt.Errorf` for contextual failures.
-
-## ANTI-PATTERNS
-
-- Do not fall back to the global client when a request has an explicit device context.
-- Do not skip validation because the REST handler already parsed the body.
-- Do not return Fiber/MCP response objects from usecases.
-- Do not perform unscoped chat/message reads from this layer unless the operation documents why global ID lookup is protocol-safe.
-- Do not replace device-scoped reply lookup with `GetMessageByID`; quoted replies must not bind a message from another device.
-
-## TESTING
-
-- Existing usecase tests are narrow. Add focused tests when changing mapping, MIME/media decisions, reply context, or device-scoped chat behavior.
-- Stubs live beside tests rather than using gomock/mockery.
+# Usecases
+
+Usecases validate requests, resolve the device/client, perform WhatsApp and storage
+operations, and return domain responses. Constructors use `New*Service` and return
+the matching domain interface; keep Fiber/MCP response types in the adapters.
+
+- Validate with `validations.Validate*` before network or storage work, even when
+ the transport already parsed the request. Use existing `pkg/error` errors and
+ contextual wrapping; the package name is `error`, commonly aliased `pkgError`.
+- Resolve clients with `whatsapp.ClientFromContext(ctx)` and chat/message scope
+ with `deviceIDFromContext(ctx)`. An explicit device context must not fall back to
+ the global client. Pass scope through repository filters and sent-message storage.
+- `send.go` owns send payloads and quote context. `mergeReplyContext` must use
+ `GetMessageByIDAndDevice`; an unscoped lookup can quote another device's message.
+- `wrapSendMessage` calls whatsmeow's `SendMessage` and normalizes errors. Code 463
+ is surfaced as a server-side reach-out restriction; whatsmeow owns the token lifecycle.
+ Async sent-message persistence retains device context while detaching cancellation.
+- `chat.go` owns history queries; `message.go` owns reactions, revokes, edits, and
+ other message actions. Existing protocol-specific global ID lookups are exceptions,
+ not a pattern for new user-facing reads; verify their caller contract before reuse.
+- `group.go` handles participant JIDs and group settings, `user.go` account/contact
+ operations, and `device.go` delegates lifecycle operations to `DeviceManager`.
+
+For mapping, media, quote, or isolation changes, use the colocated tests and stubs
+to cover the affected behavior. Choose test scope from the change rather than
+requiring every usecase suite for each edit.
diff --git a/src/validations/AGENTS.md b/src/validations/AGENTS.md
index c8d81250..98ddadaa 100644
--- a/src/validations/AGENTS.md
+++ b/src/validations/AGENTS.md
@@ -1,34 +1,19 @@
-# VALIDATIONS
-
-Generated: 2026-06-06
-
-## OVERVIEW
-
-Validation functions enforce request shape before usecases touch whatsmeow, storage, or media helpers.
-
-## WHERE TO LOOK
-
-| Task | Location | Notes |
-|------|----------|-------|
-| Send validation | `send_validation.go` | Phone format, file-vs-URL, MIME, max sizes, duration, mentions, poll options. |
-| Reply message fields | `send_validation.go`, `send_validation_test.go` | `reply_message_id` is optional; tests cover pass-through for text/media requests. |
-| Chat validation | `chat_validation.go` | Mutates request defaults for limit/offset before validating. |
-| Group validation | `group_validation.go` | Uses whatsmeow participant action constants. |
-| Message validation | `message_validation.go` | Watch boolean `Required` behavior. |
-| Tests | `*_test.go` | Table-driven, expected error equality or substring checks. |
-
-## CONVENTIONS
-
-- Use `validation.ValidateStructWithContext(ctx, &request, validation.Field(...))`.
-- Wrap ozzo errors as `pkgError.ValidationError(err.Error())`.
-- Add custom checks after ozzo validation for cross-field rules and domain-specific formats.
-- Phone numbers must be international format; Indonesian local `08...` should fail.
-- `@everyone` is a special mention and bypasses phone validation.
-- Multipart tests usually construct `multipart.FileHeader` with a `Content-Type` header directly.
-- Max-size checks must read from `config.WhatsappSettingMax*`, not duplicated literals.
-
-## ANTI-PATTERNS
-
-- Do not use `validation.Required` on a plain `bool` when `false` is valid; use a pointer or explicit validation pattern.
-- Do not accept both file and URL for request types that require exactly one input.
-- Do not make optional metadata like `reply_message_id` required unless the API contract changes.
+# Request validation
+
+Use `validation.ValidateStructWithContext` and wrap ozzo errors with
+`pkgError.ValidationError(err.Error())`. Cross-field and format checks follow
+struct validation before the usecase touches WhatsApp, storage, or media helpers.
+
+- `send_validation.go` owns phone, mention, file/URL, MIME, size, duration, and poll
+ rules. Require international phone format; local `08...` fails. `@everyone`
+ bypasses phone validation.
+- Enforce exactly one of file/URL for request types with that contract. Read size
+ limits from `config.WhatsappSettingMax*`; keep `reply_message_id` optional.
+- `chat_validation.go` also applies pagination defaults. Preserve that mutation
+ when changing validators or their callers.
+- `group_validation.go` uses whatsmeow participant action constants.
+- In `message_validation.go` and other validators, `validation.Required` rejects
+ plain `false`. Use a pointer or explicit check when `false` is valid.
+
+Tests are colocated and table-driven. Multipart fixtures can use `multipart.FileHeader`
+with a `Content-Type` header. Cover the changed rule's accepted and rejected inputs.