# WhatsApp Remediation Plan

Date: 2026-10-13

## Implementation status

Implemented on branch `codex/whatsapp-production-audit`; nothing in this audit was deployed to production.

- Read-only health is now the scheduled default. Application recovery is disabled unless explicitly enabled, normalized connection states suppress recovery while connecting/restricted, and the watchdog has a per-incident recovery cap.
- Manual text/resend, queued retry, media, and auto-reply sends now use one atomic dispatcher with durable, non-sensitive attempt records. Request idempotency keys are unique within a conversation.
- Auto-replies reserve each incoming event before provider I/O and serialize cooldown checks per contact/rule.
- Consent history, opt-out handling, message purpose, and unanswered-outbound controls are implemented. Compatibility flags default off; a recorded opt-out is always honored.
- Destination numbers and full malformed webhook payloads were removed from the affected logs. Database queue visibility timeout now defaults above the worker timeout.
- Evolution webhooks fail closed when the production secret is missing, and outbound calls resolve an explicit allow-listed instance (`main`, `main966`, or configured equivalents) for send/edit/delete operations.
- Per-instance, per-employee, and per-contact traffic controls plus a sender circuit breaker now stop bursts and repeated authentication/transient failures before provider I/O.
- Human takeover suppresses automated replies, automated reply volume is bounded, and official-provider free-form sends are blocked outside the 24-hour customer-service window.
- Delivery status events now have a durable idempotency ledger; queue backlog, queue age, recent failures, and sanitized failed-job alerts are included in health monitoring.
- Media uploads are capped and rejected before storage when disk headroom is unsafe. A dry-run-first retention command prunes only operational audit data and deliberately preserves messages, contacts, and consent evidence.

Validation completed locally with stray HTTP requests prohibited and all provider HTTP calls faked: 496 PHP tests (1,633 assertions), 116 JavaScript tests, and the production frontend build all passed. PHP formatting for every changed PHP file and `git diff --check` passed. The repository-wide Pint check still reports pre-existing formatting issues in unrelated files; this branch does not reformat them.

## Principles

- Monitoring is read-only by default; recovery is explicit and separately controlled.
- A logical outbound message has one durable database row and one dispatch owner at a time.
- Unknown acceptance is never retried automatically.
- Consent and opt-out decisions are auditable and feature-flagged for rollout.
- Operational rate controls are internal safety limits, not Meta compliance or anti-ban thresholds.
- No test sends use a real provider.

## Implementation sequence

### 1. Stop competing recovery actors

- Replace the scheduled legacy `evolution:health` command with `evolution:health-check --no-recovery`.
- Normalize provider states to `connected`, `connecting`, `disconnected`, `restricted`, and `unknown`.
- Keep app reconnect behind an explicit command/flag and a durable cooldown.
- Make the watchdog react only to read-only health results, remain bounded, and escalate after failed recovery rather than loop.

### 2. Centralize and serialize outbound dispatch

- Add an outbound coordinator used by manual text, resend, retry, media, and auto-reply paths.
- Atomically claim a message before provider I/O using a database transaction plus a unique claim/version.
- Return a `SEND_IN_PROGRESS`/`DUPLICATE_REQUEST` result instead of dispatching twice.
- Record every attempt in an audit table without message bodies, phone numbers, API responses, or credentials.
- Preserve `accepted_pending_confirmation` on ambiguous outcomes.

### 3. Auto-reply idempotency and cooldown

- Reserve `(auto_reply_id, incoming_message_id)` before send with a unique constraint.
- Serialize cooldown decisions per rule/contact and write the reservation before provider I/O.
- Keep failed attempts auditable while allowing only an explicit, bounded retry policy.

### 4. Consent, purpose, and repeated follow-ups

- Add contact consent state/source/timestamps and an append-only consent event table.
- Add message purpose (`service` or `marketing`) and initiation context.
- Feature-flag enforcement initially; opt-out is always enforced once recorded.
- For business-initiated sends, require recorded consent when enforcement is enabled.
- Add a configurable unanswered-outbound limit with a clear operator error; do not silently drop messages.

### 5. Webhook and status hardening

- Keep message-event uniqueness.
- Add a compact status-event idempotency key where the provider supplies enough evidence.
- Apply status changes transactionally and forward-only.

### 6. Logging and operations

- Remove destination phone numbers and full payloads from logs.
- Align database queue `retry_after` above the longest worker timeout.
- Default to one outbound-capable worker and configurable conservative pacing.
- Document backup, migration, worker/php-fpm/reverb restart, observation, and rollback steps.

## Feature flags

- `WHATSAPP_OUTBOUND_CONTROLS_ENABLED`
- `WHATSAPP_CONSENT_ENFORCEMENT_ENABLED`
- `WHATSAPP_MAX_UNANSWERED_OUTBOUND`
- `WHATSAPP_OUTBOUND_MIN_INTERVAL_MS`
- `EVOLUTION_APP_RECOVERY_ENABLED` (default false)

## Test plan

- Four employee requests contending for outbound capacity.
- Duplicate request id submitted twice.
- Two retry workers for one message.
- Duplicate message and status webhooks.
- Auto-reply keyword match, zero/nonzero cooldown, concurrent job reservation.
- Timeout/ambiguous acceptance, retryable rejection, permanent rejection.
- `connecting` state does not trigger repeated reconnect.
- Watchdog consumes read-only health and respects threshold/cooldown.
- Missing consent, opted-out contact, service versus marketing purpose.
- Repeated unanswered follow-up feedback.
- Transaction rollback and queue failure recovery.

All provider calls must be faked. No test may call Evolution or Meta.

## Rollout

1. Take and verify a backup with `ops/backup-predeploy.sh`.
2. Deploy migrations with controls disabled except read-only health scheduling.
3. Restart php-fpm and `whatsapp-worker` (jobs/services/providers changed); restart Reverb only if broadcast code changes.
4. Run `ops/post-deploy-check.sh` and observe health/queue/error-category aggregates.
5. Enable dispatch locking/audit first, then consent enforcement for a small operator group, then unanswered-follow-up controls.
6. Keep recovery disabled until the read-only state history is stable and an operator explicitly approves recovery behavior.

## Rollback

- Disable the new feature flags first.
- Roll back application code while leaving additive audit/consent columns in place; they are backward-compatible.
- Do not drop audit or consent data during an incident.
- If a migration rollback is explicitly approved, take another verified backup and roll back only the named migration batch.
- Never delete Evolution containers, volumes, sessions, or credentials as a rollback step.

## Remaining risks

- Evolution API is unofficial connectivity; no application throttle guarantees account compliance or prevents restrictions.
- Provider timeouts can remain permanently ambiguous without a later webhook/provider lookup.
- Consent imported from external systems is only as trustworthy as its source and audit trail.
- Phone-originated messages bypass CRM operator controls; they can only be observed after provider webhook echo.
