# RBS REGAL — Global Development Rules (v1.0)
**Established by user on 2026-06-15. Apply to ALL current and future features automatically.**

> DO NOT ask user feature-by-feature whether these apply.
> Every PR, bug fix, AI feature, integration, UI tweak — must honour these by default.
> If a rule blocks progress, ESCALATE to the user with a concrete trade-off before bypassing.

---

## The 11 Rules

### 1. MULTI-USER FIRST
- Concurrent users · Role permissions · User isolation · Session control · Real-time sync · Separate activity
- No feature breaks under multi-user load
- **Implementation pattern**: every counter / cache / queue is keyed by `user_email` (lower-cased, trimmed)

### 2. MULTI-COMPANY FIRST
- Separate billing / stock / settings / prefix / users / reports / audit / data
- **Never mix company data**
- **Implementation pattern**: every API endpoint accepts `company_id` query param + filter on it; every collection write stores `company_id`

### 3. OFFLINE FIRST
- Priority: **Offline → LAN → Cloud**
- Maximum ops work offline · Queue sync · Auto recovery · Background sync · Conflict protection · Local cache · Fast startup
- Internet must NEVER block business operations
- **Implementation pattern**: Dexie v3 (`/app/frontend/src/lib/localdb.js`) + `syncEngine.js` queue + per-user `offline_mode` toggle (Phase B v12.4 ✅)

### 4. SECURITY FIRST
- Authentication · Authorization · Device validation · Session control · Encryption · Audit logs · Access control · Rate limiting · Secure backup
- **No shortcuts**
- **Implementation pattern**: `get_current_user` + `require_admin` dependencies on every route; device fingerprint in cookies; JWT with refresh; bcrypt for passwords

### 5. FRAUD PREVENTION
- Prevent: duplicate billing · fake invoices · sequence manipulation · unauthorized access · data tampering · company cloning · invalid edits
- Track: User · Device · Company · Timestamp · Action on every mutation
- **Implementation pattern**: every invoice / item / payment stores `created_by + device_id + company_id + ts`; per-user counters block sequence collisions (v12.7 ✅); `audit_log` collection captures every admin action

### 6. LOW BUG POLICY
- Before release: validate existing modules · regression · performance · offline behaviour · multi-user · multi-company
- **Rule**: Feature complete → **Test** → Deploy
- Avoid quick patches — always trace root cause
- **Implementation pattern**: pytest suite (currently 36 tests) MUST stay green; new features add tests; testing-agent runs after feature batches

### 7. EXISTING MODULE PROTECTION
- Modify existing modules only
- Avoid: duplicate modules / pages / settings / broken workflows
- **Respect existing UI** (when user says "no UI change", UI is byte-identical)
- **Implementation pattern**: prefer editing existing files via `search_replace`; new files only when no existing host module fits

### 8. PERFORMANCE FIRST
- Targets: instant actions · fast loading · minimal memory · background processing · no unnecessary API calls · no blocking UI
- **Implementation pattern**: optimistic UI updates · React.memo / useMemo on heavy lists · Dexie indices on hot read paths · MongoDB indexes on `(company_id, type, *)` for invoice queries

### 9. DATA SAFETY
- Never: delete silently · overwrite silently · corrupt records
- Always: backup · version · recovery
- **Implementation pattern**: `safeDelete` helper → soft-delete to Trash before API delete · 30-day Recycle Bin auto-sweep · per-user wipe on logout

### 10. ADMIN CONTROL
- All critical controls support Super Admin / Admin / Permissions
- Full audit history
- **Implementation pattern**: `audit_log` collection · `require_admin` on every destructive endpoint · per-action `_audit(...)` calls

### 11. AI DEVELOPMENT RULE (for me, the coding agent)
When adding any feature I MUST automatically think:
- Security?
- Offline?
- Multi-user?
- Multi-company?
- Low bugs (regression risk)?
- Backward compatibility?

**Optimize for production, not demo.**

---

## Compliance Checklist (run mentally on every PR)

| Check | Question |
|-------|----------|
| Multi-user | Is the key scoped to `user_email` where applicable? |
| Multi-company | Does the endpoint filter by `company_id`? Does the write store `company_id`? |
| Offline | Does the new flow respect `offline_mode` toggle? Queue mutations on network error? |
| Security | Is auth required? Are inputs validated? |
| Fraud | Is `created_by` + `device_id` recorded? Is the counter atomic? |
| Regression | Does pytest still pass? testing-agent green? |
| Existing module | Did I avoid creating a new page/route/module? |
| Performance | Atomic Mongo ops? No N+1 queries? |
| Data safety | Are deletes soft? Is there a restore path? |
| Admin | Is destructive action gated by `require_admin`? |
| Audit | Is the action logged? |

---

## Pre-implementation gate
Before writing code for a feature, the agent should be able to answer YES to every applicable row above. If something is consciously skipped, it MUST be flagged in the user-facing summary with reasoning.
