# AGENTS.md

WhatsApp CRM — Laravel backend + Filament admin + Vue/Inertia SPA chat workspace,
integrated with the Evolution API (and optionally Meta Cloud API) for WhatsApp.
Arabic RTL UI. This file covers the repository root only (see References for the
Flutter mobile sub-package).

## Stack
- PHP ^8.2 (production runs ea-php83), Laravel ^12.61, Filament ^3.3.53
- Laravel Sanctum ^4.3 (mobile tokens), spatie/laravel-permission ^6.25, Horizon ^5.46, Reverb ^1.10
- kreait/firebase-php ^7.0 (push), Inertia ^3.1 + Vue ^3.5 + Tailwind ^3.4, Vite ^5, laravel-echo + pusher-js
- DB: SQLite (`DB_CONNECTION` default `sqlite`); tests run on sqlite `:memory:`
- Queue: database driver, queues `webhooks,default`; broadcasting via Reverb
- Tests: Pest ^3.8 / PHPUnit ^11.5; JS tests via node:test. Lint: laravel/pint (no pint.json — Laravel preset)

## Structure
- `app/Http/Controllers` — HTTP/JSON endpoints; edit for API or workspace request behaviour.
- `app/Http/Middleware` — auth/activity gates and webhook signature verification.
- `app/Services` — business logic (WhatsApp providers, Evolution import/health, conversation lifecycle, routing, waiting list). Put logic here, not in controllers.
- `app/Models` (+ `Scopes/AssignedScope`) — Eloquent models and role-based row scoping.
- `app/Jobs`, `app/Events`, `app/Observers`, `app/Policies`, `app/Notifications` — async work, broadcast events, model hooks, authorization, alerts.
- `app/Console/Commands` — operational/repair commands (`evolution:*`, `conversations:*`, contact/media repairs).
- `app/Filament` + `app/Providers/Filament` — admin panel at `/admin`; resources/pages/widgets auto-discovered.
- `app/Support` — pure helpers (Arabic text, phone numbers, message ids, Evolution payload parsing).
- `routes/` — `api.php`, `web.php`, `channels.php`, `console.php` (scheduler lives in `console.php`).
- `resources/js` (Pages/Components/Layouts), `resources/css`, `resources/views` — frontend + Blade/Filament views.
- `database/` — migrations, factories, seeders; `tests/Feature`, `tests/Unit`, `tests/js`.
- `deploy/`, `ops/`, `docs/` — deploy script + systemd/supervisor units, ops scripts, runbooks.
- `Project_memory/` — historical audits/plans; context only, not authoritative over code.

## Conventions
- Naming: PSR-4 `App\` → `app/`; classes match filenames. Services end in `Service`/`Manager`/`Resolver`/`Guard`/`Fetcher`; interfaces end in `Interface`; commands end in `Command`; middleware named `Ensure*`/`Verify*`.
- Imports: explicit `use` statements at top, no inline FQCNs (facades imported); frontend alias `@` → `/resources/js`.
- Layering: controllers authorize (`$this->authorize(...)`), validate, delegate to a service, return an `App\Http\Resources\*Resource`; multi-table writes wrapped in `DB::transaction`.
- Conversation state changes go through `ConversationLifecycleService` only — the single source of truth for status/`assigned_to`/`assigned_at`.
- Error handling: JSON errors return a machine-readable `code` (e.g. `CONVERSATION_CLOSED`, `CONTACT_EXISTS`, `ALREADY_SENT`) with an HTTP status; failures logged via `Log::` with context rather than thrown blindly.
- Non-obvious decisions are documented as block comments above the code they explain — follow this when changing such code.
- Tests: Pest function style (`test('...', function () {...})`) with `uses(RefreshDatabase::class)`, `beforeEach` seeding Spatie roles and `Http::fake()`; named `*Test.php` in `tests/Feature`. JS tests are `tests/js/*.test.mjs`.

## Commands
- Install: `composer install` / `npm install`
- Dev frontend: `npm run dev`
- Build frontend: `npm run build`
- PHP tests: `php artisan test` (phpunit.xml suites: Unit, Feature)
- JS tests: `npm test` (`node --test "tests/js/**/*.test.mjs"`)
- Lint/format PHP: `vendor/bin/pint` (check only: `vendor/bin/pint --test`)
- Lint JS/Vue: `npm run lint` (fix: `npm run lint:fix`) — ESLint flat config in `eslint.config.js`
- Format JS/CSS: `npm run format` (check only: `npm run format:check`) — Prettier, 4-space/single-quote
- Migrate: `php artisan migrate` (prod: `php artisan migrate --force`)
- Queue worker: `php artisan queue:work --queue=webhooks,default --timeout=600 --sleep=1 --tries=3 --max-time=3600 --rest=1`
- Scheduler (cron, every minute): `php artisan schedule:run`
- Realtime server: `php artisan reverb:start`
- Health: `php artisan evolution:health`; integrity: `php artisan conversations:audit-status` (fix: `conversations:repair-status --apply`)
- Clear caches: `php artisan optimize:clear`
- Deploy: `deploy/deploy.sh` (pull → composer → migrate → optimize:clear → restart php-fpm, whatsapp-worker, whatsapp-reverb)
- CI: `.github/workflows/ci.yml` on push/PR to `master` — PHP 8.3 Pest, node:test + `npm run build` (blocking); Pint/ESLint/Prettier advisory only (pre-existing violations)

## Rules
- Always pass `--queue=webhooks,default` to the worker; without it webhook jobs are not processed and no new messages appear.
- The queue worker must run under systemd/supervisor, never a bare `&` background process, and only one worker at a time.
- Deploy discipline (R-8): after changing jobs/services/providers restart `whatsapp-worker`; after HTTP-path changes restart php-fpm (opcache); after broadcast/event changes restart `whatsapp-reverb`. Skipping this makes fixed bugs reappear.
- `contacts.profile_name`, `messages.body`, `message_edits.old_body/new_body` are `encrypted` casts — never filter them with SQL `LIKE`; filter in PHP (R-3).
- Never commit or paste secrets; configuration comes from `.env` (see `.env.example` for required variable names only).
- Bypass `AssignedScope` only via the explicit `system()` scope; do not remove the scope to "fix" visibility.
- Conversation status must not be written directly from controllers/observers outside the lifecycle service.
- `AGENTS.md` scope note: root README.md is upstream Laravel boilerplate — do not treat it as project documentation.

## References
- `docs/deployment.md` — deploy + production `.env` checklist and queue setup; read before deploying.
- `docs/EVOLUTION_RECOVERY_RUNBOOK.md`, `docs/EVOLUTION_MONITORING.md`, `docs/EVOLUTION_INCIDENT_ROOT_CAUSE.md` — WhatsApp/Evolution outage diagnosis and recovery; read when messages stop syncing.
- `docs/BACKUP_RESTORE_RUNBOOK.md`, `docs/POST_DEPLOY_OBSERVATION_CHECKLIST.md` — backup/restore drills and post-deploy verification.
- `docs/OPS_SECURITY_REVIEW.md` — known security posture and gaps; read before touching auth/permissions.
- `docs/WHATSAPP_CRM_ENHANCEMENTS_PLAN.md` — staged enhancement roadmap and status.
- `HTTPS_REVERSE_PROXY_SETUP.md` — reverse proxy/TLS setup; read when links, mic access, or websockets misbehave.
- `deploy/AGENTS.md` + `deploy/README.md`, `REVERB_SETUP.md` — deploy script, supervision units, R-8 restart discipline; read before deploying.
- `ops/AGENTS.md` + `ops/README.md` — host watchdog, backups, read-only diagnostics and their enforced safety rules; read before editing any `ops/` script.
- `Project_memory/` — historical audits, phase reports, decisions; read for background on past fixes only.
- `mobile/raito_whatsapp/AGENTS.md` + its `README.md` — Flutter client: separate package, own toolchain and rules.
