# AGENTS.md

## Project

**Eversatile Core** — a cPanel-friendly multi-tenant SaaS control panel that manages all current and future Eversatile apps such as Salon OS, POS, HRMS, CRM, and other products.

This document is the operating guide for any AI coding agent working in this repository.

---

## 1. Mission

Build a production-ready **central SaaS management platform** that:

* manages tenants/businesses
* manages apps/products
* manages packages/plans
* manages subscriptions
* manages invoices and payment records
* manages users across tenants
* manages roles and permissions
* provides dashboards for Super Admin and tenants
* supports M-Pesa subscription billing
* makes it easy to plug in future SaaS apps without redesigning the core system

This system is **not** Salon OS itself. It is the parent platform that will manage Salon OS, POS, HRMS, and future apps.

---

## 2. Hosting and deployment constraints

The system must be designed to run comfortably on **standard cPanel hosting**, especially Truehost.

### Therefore:

* Prefer **Laravel 12 + MySQL + Blade + Tailwind CSS**
* Avoid requiring Docker
* Avoid requiring Redis
* Avoid requiring Supervisor
* Avoid requiring server-level daemons that are unavailable in normal cPanel environments
* Use **database queues** if queues are required
* Use **Laravel scheduler via cPanel cron**
* Use **MySQL-compatible features only**
* Keep file storage compatible with shared hosting
* Keep installation and deployment simple

### Architecture preference:

Start as a **single Laravel monolith with modular internal structure**.
Later, if needed, individual apps may be split out.

---

## 3. Product vision

Eversatile Core must function as:

* app catalog
* tenant manager
* subscription manager
* billing center
* invoice center
* product access controller
* user registry
* package manager
* role/permission manager
* app launcher
* platform admin console

This platform must support future products without major schema redesign.

---

## 4. Core business concepts

### 4.1 Tenant

A **tenant** is a customer business using one or more apps.
Examples:

* salon
* barber shop
* beauty studio
* retail store
* clinic
* company

Each tenant can have:

* one owner
* multiple users
* one or more app subscriptions
* one or more invoices and payments
* app-specific access and usage limits

### 4.2 App

An **app** is a SaaS product managed by Eversatile Core.
Examples:

* Salon OS
* POS
* HRMS
* CRM
* future apps

Each app can have:

* many packages
* many features
* many tenant subscriptions
* a launch URL or portal URL

### 4.3 Package / Plan

A package defines the commercial tier of an app.
Examples:

* Starter
* Growth
* Pro
* Enterprise

Each package can define:

* monthly price
* yearly price
* setup fee
* trial days
* max users
* max branches
* max transactions
* max storage
* max admins
* feature access
* feature usage limits

### 4.4 Subscription

A subscription connects a **tenant** to an **app package**.
It must track:

* start date
* end date
* trial start and end
* billing cycle
* amount
* currency
* status
* renewal preference
* grace period behavior

### 4.5 User

Users belong to tenants, except platform-level Super Admin users.
User categories may include:

* Super Admin
* Billing Admin
* Support Admin
* Tenant Owner
* Tenant Admin
* Manager
* Staff
* Viewer
* custom tenant-defined roles

### 4.6 Billing records

The platform must support:

* invoices
* invoice items
* payments
* transactions
* receipt numbers
* transaction references
* payment status reconciliation

### 4.7 Access control

App access is controlled by:

* subscription status
* package rules
* roles and permissions
* feature availability
* usage limits

---

## 5. Non-negotiable technical principles

AI agents must follow these rules.

### 5.1 Do not over-engineer for infrastructure that does not exist

Do not introduce dependencies that assume:

* Kubernetes
* Redis-only queues
* message brokers
* Docker orchestration
* microservices by default

### 5.2 Preserve cPanel friendliness

Every major design choice must be evaluated against:

* easy deployment
* low server requirements
* cron compatibility
* shared hosting compatibility
* easy troubleshooting

### 5.3 Keep modules decoupled in code, but in one deployable app

Use clean modular organization inside Laravel:

* Models
* Services
* Policies
* Form Requests
* Actions or service classes where helpful
* Feature folders or sensible domain grouping

### 5.4 Avoid giant rewrites

When implementing a task:

* change only what is needed
* do not rewrite unrelated files
* do not rename core concepts without cause
* do not silently alter existing architecture

### 5.5 Use transaction-safe write flows

Critical workflows must use DB transactions where appropriate:

* registration
* tenant creation
* subscription creation
* payment reconciliation
* invoice creation
* subscription upgrade/downgrade

### 5.6 Respect tenant isolation

Tenant data must never leak across tenants.
All tenant-visible queries must be scoped properly.
Super Admin may bypass tenant scoping where explicitly intended.

### 5.7 Keep code production-oriented

Code should include:

* validation
* authorization
* indexes and foreign keys
* clean relationships
* status handling
* error handling
* audit logging where relevant

---

## 6. Preferred stack

* **Framework:** Laravel 12
* **Database:** MySQL
* **Frontend:** Blade + Tailwind CSS
* **Auth:** Laravel auth scaffolding
* **Queues:** database queue driver
* **Scheduler:** Laravel scheduler triggered from cPanel cron
* **Notifications:** database notifications and email where needed
* **Payments:** M-Pesa (Daraja API) first, extensible for card/bank later

---

## 7. Functional scope

### 7.1 Core platform modules

The following modules belong in Eversatile Core:

1. Authentication and onboarding
2. Tenant management
3. App catalog
4. Package management
5. Subscription management
6. Billing and invoice management
7. Payment records and transactions
8. M-Pesa subscription billing integration
9. Global user management
10. Roles and permissions
11. Super Admin dashboard
12. Tenant dashboard
13. App launcher
14. Settings
15. Activity logs and audit trail
16. Scheduled automation and reminders

### 7.2 Future-ready but not first priority

These may come later:

* coupons / promo codes
* referral codes
* reseller system
* white-labeling
* custom domains
* public API keys
* webhook logs
* usage-based billing
* external app trust / SSO bridge

Do not prioritize these unless explicitly requested.

---

## 8. Initial data model targets

These are the main tables/entities expected in the system.
Exact naming can follow Laravel conventions, but the concepts must exist.

### Core entities

* users
* tenants
* tenant_users (if needed for separation of membership logic)
* apps
* app_packages
* app_features
* package_feature_limits
* subscriptions
* subscription_histories
* invoices
* invoice_items
* payments
* transactions
* roles
* permissions
* role_permission
* user_role
* activity_logs
* settings
* notifications (Laravel native if used)

### Optional supporting entities later

* tenant_notes
* app_settings
* webhook_logs
* usage_counters
* coupons
* branches

---

## 9. Required system behaviors

### 9.1 Registration and onboarding

When a business owner registers:

1. create tenant
2. create owner user
3. assign owner role
4. attach selected app
5. attach selected package
6. create default subscription record
7. create invoice if required
8. log onboarding event

Rules:

* if package has trial days, subscription starts as trial
* if no trial, subscription may start as pending payment
* registration must be transactional
* prevent duplicate tenant/user creation on partial failure

### 9.2 App management

Super Admin must be able to:

* create apps
* edit apps
* enable/disable apps
* define visibility
* set launch URLs
* define features
* create packages per app
* configure feature limits per package

### 9.3 Subscription management

The platform must support:

* active subscriptions
* trial subscriptions
* pending subscriptions
* expired subscriptions
* cancelled subscriptions
* grace periods
* renewals
* upgrades
* downgrades
* reactivation
* admin override
* history timeline of subscription changes

### 9.4 Billing behavior

The platform must support:

* invoice generation
* invoice number generation
* invoice items
* subtotal, tax, total, amount due, amount paid
* invoice statuses
* receipt generation
* linking billing records to tenant, app, and subscription

### 9.5 Payments

Support:

* manual payment records
* M-Pesa STK push payment initiation
* callback processing
* duplicate callback protection
* failed payment tracking
* timeout handling
* reconciliation logging

### 9.6 User management

Super Admin must be able to:

* view all users across platform
* filter by tenant, app, package, status
* activate/suspend users
* reset passwords
* impersonate tenant owner if implemented
* see last login and registration date

Tenant owners/managers must be able to:

* invite users
* assign allowed roles
* deactivate tenant users
* view which apps their tenant has access to

### 9.7 Roles and permissions

The system must support both:

* platform-wide roles
* tenant-specific roles

Tenant role examples:

* Owner
* Admin
* Manager
* Staff
* Viewer
* custom roles

Platform role examples:

* Super Admin
* Billing Admin
* Support Admin

### 9.8 Dashboards

Super Admin dashboard should show:

* total tenants
* active subscriptions
* trial subscriptions
* expired subscriptions
* total users
* revenue summaries
* app adoption
* package popularity
* recent payments and registrations

Tenant dashboard should show:

* active apps
* package name
* renewal date
* invoices summary
* payment summary
* users count
* recent activity

### 9.9 App launcher

Each tenant should have an app launcher that shows:

* active apps
* locked apps
* trial apps
* package/tier status
* launch links where allowed

The launcher should rely on subscription/access checks, not hardcoded visibility.

---

## 10. Milestones

AI agents must implement the system in milestones. Do not try to build the entire platform in one step.

### Milestone 0 — Repository orientation and guardrails

Goal:

* inspect current repo structure
* understand what already exists
* do not assume blank project unless verified
* create or update a concise architecture summary if needed
* ensure AGENTS.md is followed for all later tasks

Deliverables:

* project structure note
* confirmed implementation order
* list of existing modules to preserve

### Milestone 1 — Foundation

Goal:
Set up the base Laravel platform structure.

Tasks:

* confirm Laravel 12 setup
* confirm MySQL config approach
* configure Tailwind
* configure auth scaffolding
* configure database queue driver
* configure scheduler readiness
* set up base layouts
* create base route groups for admin and tenant areas

Deliverables:

* base application shell
* auth working
* admin layout
* tenant layout

### Milestone 2 — Core data model

Goal:
Create the main migrations and relationships.

Tasks:

* create migrations for tenants, apps, app_packages, subscriptions, invoices, payments, transactions, roles, permissions, settings, activity logs, and related tables
* add indexes and foreign keys
* decide on ULIDs/IDs consistently
* create models and relationships
* create seeders for sample apps and packages

Deliverables:

* working schema
* working models
* seed data for Salon OS, POS, HRMS

### Milestone 3 — Registration and onboarding

Goal:
Allow a new business owner to register and become a tenant.

Tasks:

* business registration form
* create tenant + owner user transactionally
* assign initial app and package
* create initial subscription
* create initial invoice if needed
* create onboarding success flow
* save subscription history

Deliverables:

* owner signup flow
* automatic tenant creation
* automatic subscription creation

### Milestone 4 — App catalog and package manager

Goal:
Give Super Admin control over apps and plans.

Tasks:

* app CRUD
* package CRUD
* app feature definitions
* package feature mapping
* package limits configuration
* app status and visibility controls

Deliverables:

* admin app management pages
* admin package management pages

### Milestone 5 — Subscription engine

Goal:
Implement the full subscription lifecycle.

Tasks:

* subscription listing
* subscription detail page
* status changes
* renewals
* cancellations
* reactivations
* upgrades and downgrades
* grace periods
* subscription history timeline
* access helper methods

Deliverables:

* reliable subscription workflows
* centralized access-check logic

### Milestone 6 — Billing and records

Goal:
Implement billing records independent of gateway logic.

Tasks:

* invoices
* invoice items
* payments
* transactions
* printable invoice/receipt views
* invoice number generation
* filters and detail pages
* audit logging of changes

Deliverables:

* financial record system
* invoice and receipt pages

### Milestone 7 — M-Pesa integration

Goal:
Enable M-Pesa subscription billing.

Tasks:

* STK push initiation service
* callback endpoint
* callback log storage
* idempotency and duplicate protection
* payment reconciliation
* invoice update after confirmed payment
* activate/renew subscription after payment
* sandbox/live config handling

Deliverables:

* subscription payment flow through M-Pesa
* reliable callback handling

### Milestone 8 — User management

Goal:
Manage platform users and tenant users cleanly.

Tasks:

* global user list for Super Admin
* tenant-scoped user list
* filters by tenant, app, package, status
* invite flow for tenant users
* user activation/deactivation
* role assignment
* optional impersonation support if feasible

Deliverables:

* user directory pages
* tenant user administration

### Milestone 9 — RBAC

Goal:
Implement robust role and permission controls.

Tasks:

* platform roles
* tenant roles
* custom role builder
* permission matrix
* middleware and policies
* Blade permission helpers
* route protection

Deliverables:

* production-ready RBAC
* tenant-safe permission boundaries

### Milestone 10 — Dashboards and reporting

Goal:
Give visibility into platform and tenant activity.

Tasks:

* Super Admin dashboard widgets
* tenant dashboard widgets
* summary cards
* revenue summaries
* app adoption metrics
* subscription and billing summaries
* recent activity and payments

Deliverables:

* usable dashboards
* efficient reporting queries

### Milestone 11 — App launcher and modular app access

Goal:
Make the system future-proof for new apps.

Tasks:

* tenant app launcher page
* active vs locked app display
* launch URLs and portal links
* central access service
* app metadata and app settings support
* placeholder launch pages for Salon OS, POS, and HRMS

Deliverables:

* launcher interface
* reusable access gateway for future apps

### Milestone 12 — Automations and reminders

Goal:
Run subscription lifecycle actions automatically.

Tasks:

* expiring-soon checks
* expiry processing
* renewal invoice generation
* trial-ending reminders
* overdue invoice reminders
* grace period enforcement
* app access reduction after expiry if needed
* automation event logging

Deliverables:

* scheduled jobs
* reminder notifications
* cron-ready automation

### Milestone 13 — Settings and configuration

Goal:
Allow flexible platform-level and tenant-level configuration.

Tasks:

* platform settings UI
* tenant settings UI
* invoice settings
* billing defaults
* M-Pesa settings
* trial defaults
* grace period defaults
* branding fields
* support emails

Deliverables:

* settings management module

### Milestone 14 — Deployment hardening

Goal:
Make production deployment reliable on cPanel.

Tasks:

* cPanel deployment checklist
* .env example
* artisan setup instructions
* cron setup instructions
* queue usage instructions
* storage instructions
* security hardening checklist
* backup recommendations
* smoke test list

Deliverables:

* deployment docs
* stable cPanel-ready project

---

## 11. Agent operating rules for each task

Whenever an AI agent is assigned work, it must follow this execution pattern.

### 11.1 Scope tightly

Work on **one milestone or one subtask at a time**.
Do not attempt entire-platform rewrites.

### 11.2 Respect existing code

Before changing files:

* inspect current implementation
* preserve working logic
* avoid unnecessary churn

### 11.3 Limit blast radius

If a task is about subscriptions, do not rewrite billing, users, layouts, and dashboards unless required.

### 11.4 Show affected files clearly

For each change, identify:

* new files
* updated files
* deleted files, if any

### 11.5 Prefer complete code for touched files

When generating changes, provide complete code for the files being created or updated.

### 11.6 Use Laravel best practices

Prefer:

* Form Requests for validation
* Policies for authorization
* Service classes for complex business workflows
* Model relationships and scopes
* transactions for critical multi-write flows
* seeders/factories where useful

### 11.7 Keep UI practical

Use:

* Blade
* Tailwind
* clean table/list/detail pages
* no overcomplicated frontend build requirements

---

## 12. Prompting convention for AI agents

When working incrementally, use compact prompts in this style:

### Template

* Use existing project context
* State one task only
* State exact scope
* State what not to touch
* Request complete code for affected files only

### Example

“Use the existing Laravel 12 Eversatile Core project. Build only the Subscription model layer. Create or update Subscription and SubscriptionHistory models with relationships, casts, scopes, and helper methods. Do not create controllers or views. Assume migrations already exist.”

This avoids token waste and minimizes destructive rewrites.

---

## 13. Naming guidance

Preferred product naming:

* **Eversatile Core** = central SaaS control platform
* Salon OS = salon management app
* POS = point-of-sale app
* HRMS = human resource app

Use consistent naming in code, routes, labels, and seed data.

---

## 14. Access model recommendation for future apps

For now, future apps should be built as **modular internal sections** of the same Laravel codebase whenever possible.
Examples:

* `/apps/salon`
* `/apps/pos`
* `/apps/hrms`

Why:

* easiest for cPanel hosting
* simplest auth model
* easiest subscription gating
* least deployment complexity

Later, if an app outgrows the monolith, it may be separated and integrated back through the core platform.

---

## 15. Out-of-scope for first release

Do not prioritize these unless explicitly requested:

* full external SSO between separate apps
* multi-region infrastructure
* Kubernetes-style deployment
* usage-based metered billing
* reseller platform
* white-labeling
* public developer API ecosystem
* advanced analytics warehouse

The first release should focus on a strong, sellable, manageable control panel.

---

## 16. Definition of done

A milestone is complete only if:

* the code is cohesive
* the code is authorized and validated
* the feature works within tenant boundaries
* cPanel constraints were respected
* database integrity is preserved
* migrations are safe
* UI pages exist where required
* there is enough seed/test data to verify basic behavior

---

## 17. First release target

The first sellable version of Eversatile Core should include:

* auth
* tenant registration
* app catalog
* packages
* subscriptions
* invoices
* payments
* M-Pesa hooks
* tenant users
* roles and permissions
* Super Admin dashboard
* tenant dashboard
* app launcher
* scheduled expiry/reminder logic
* settings

That is the target foundation before building large product-specific modules.

---

## 18. Final instruction to AI agents

Build this platform in deliberate, milestone-based steps.
Do not chase perfection at the expense of shipping.
Prioritize:

1. correctness
2. maintainability
3. cPanel compatibility
4. tenant safety
5. clean extensibility for future apps

If you must choose between a clever distributed design and a simpler deployable design, choose the simpler deployable design.
