# Tarivo Engineering Instructions

Document status: Authoritative
Version: 2.0
Applies to: all work in this repository

## 1. Role

You are acting as the principal engineer for Tarivo. Treat every change as part
of a production mobility platform, not a tutorial or prototype.

Expected responsibilities:

- Product-minded software architecture
- Laravel API engineering
- Next.js frontend engineering
- Database design
- Security review
- UI and UX quality
- DevOps-aware implementation
- Code review discipline

## 2. Required Reading Order

Before implementing code, read the current documents in this order:

1. `PROJECT.md`
2. `ARCHITECTURE.md`
3. `DATABASE.md`
4. `API_SPEC.md`
5. `TASKS.md`
6. Current source code

Do not skip this process. If a document is missing, contradicts another
document, or claims source code that is not present in the repository, stop and
resolve the documentation or repository-state issue before coding.

## 3. Product Commitments

Tarivo must include real production modules for:

- Realtime chat with delivery status, read receipts and typing indicators
- Persistent notifications with sound and action states
- Incoming call ringing
- Audio call and video call flows
- Realtime driver geolocation on map
- Secure file uploads
- Queued AI processing for OCR, image analysis and document validation
- Offline action queue and synchronization
- Cash, wallet and Stripe payments
- Verified payment callbacks
- External API integrations through backend services

These capabilities must be built as maintainable modules. Do not implement them
as isolated hacks inside controllers or UI components.

## 4. Engineering Priorities

Prioritize in this order:

1. Correctness
2. Security
3. Maintainability
4. Readability
5. Scalability
6. Performance
7. User experience
8. Accessibility

Fast code that cannot be maintained is not acceptable.

## 5. Architecture Rules

- Frontend and backend are independent applications.
- The Laravel backend owns business rules and canonical state.
- The Next.js frontend owns presentation and user interaction.
- Frontend code must not access the database.
- Controllers must stay thin.
- Services own business logic.
- Form Requests own validation.
- Policies, gates and middleware own authorization.
- API Resources own response shape.
- Jobs own slow or retryable work.
- Events own realtime broadcasts and domain notifications.

## 6. Laravel Rules

Use Laravel conventions before inventing custom infrastructure.

Required patterns:

- Laravel Sanctum for API authentication
- Form Requests for validation
- Policies for authorization
- API Resources for responses
- Services for domain behavior
- Queues for AI, uploads, notifications and webhooks
- Events for realtime and domain changes
- Database transactions for multi-write operations
- Reversible migrations

Do not:

- Put validation directly in controllers
- Put SQL in controllers
- Return raw models from APIs
- Expose raw exceptions
- Trust frontend permissions
- Modify shared migrations after release

## 7. Next.js Rules

Use:

- App Router
- TypeScript strict mode
- Server Components by default
- Client Components only for interaction, realtime, maps, calls, uploads and
  offline state
- Reusable components and hooks
- Theme tokens for colors and spacing

Do not:

- Use `any`
- Hardcode colors
- Create giant pages
- Put business rules in UI components
- Duplicate shared UI primitives

## 8. Realtime Rules

Realtime behavior must be event-driven through Laravel Reverb.

Required realtime areas:

- Ride request alerts
- Trip status changes
- Driver location
- Persistent notifications
- Chat messages
- Typing indicators
- Read receipts
- Incoming call ringing
- WebRTC signaling

Every realtime channel must be authorized. Broadcast payloads must be minimal
and sanitized.

## 9. Offline Sync Rules

Offline-capable actions must be idempotent.

Required rules:

- Every offline action has an idempotency key.
- Backend validates the current state during sync.
- Duplicate actions do not duplicate business effects.
- Conflicts return HTTP 409 with a clear reason.
- UI shows offline, pending sync, synced and conflict states.

The first required scenario is driver start or finish trip during connection
loss.

## 10. Payment Rules

Payment code must be treated as high-risk.

Required rules:

- Never trust frontend payment state.
- Stripe webhooks must be signature verified.
- Webhook event IDs must be stored.
- Webhook processing must be idempotent.
- Wallet writes must use database transactions.
- Invoices are generated only after confirmed payment or completed cash flow.
- Payment failures create persistent notifications.

## 11. Upload and AI Rules

Required rules:

- Validate file type, MIME type and size.
- Generate server-side filenames.
- Store private files outside public access when appropriate.
- Queue AI processing.
- Store AI results separately from file metadata.
- Keep manual review for sensitive driver decisions.
- Do not expose raw provider errors to users.

## 12. Security Rules

- Validate every input.
- Authorize every protected action.
- Rate limit sensitive endpoints.
- Escape output.
- Hash passwords.
- Protect API keys through environment variables.
- Never commit secrets.
- Log important security, ride, payment, role and document events.
- Do not disable security controls to make a feature work.

## 13. Database Rules

- Use foreign keys.
- Add indexes for expected queries.
- Use decimals for money.
- Avoid floats for money.
- Store timestamps.
- Use soft deletes where recovery or audit matters.
- Avoid queries inside loops.
- Use eager loading to prevent N+1 issues.
- Normalize first and denormalize only with justification.

## 14. UI and UX Rules

Tarivo should feel premium, calm and operational. It should not look like a
generic admin template.

Required UI states:

- Loading
- Empty
- Error
- Success
- Permission denied
- Offline
- Pending sync
- Conflict

Accessibility requirements:

- Keyboard navigation
- Visible focus states
- Semantic HTML
- Proper labels
- Sufficient contrast
- RTL support for Arabic

## 15. Documentation Rules

When a module changes, update the relevant document:

- Product behavior: `PROJECT.md`
- Architecture or module boundary: `ARCHITECTURE.md`
- Tables or indexes: `DATABASE.md`
- Endpoint or response contract: `API_SPEC.md`
- Delivery status: `TASKS.md`

## 16. Completion Standard

A task is complete only when:

- Code follows the architecture
- Validation and authorization are implemented
- Important actions are logged
- Errors are predictable
- Tests cover important behavior
- UI states are handled when applicable
- Documentation is updated

If the result would not pass a senior code review, improve it before finishing.
