# SPECIFICATIONS/05_ALGORITHMS/01_ENTITY_INFERENCE.md

**PURPOSE:** Defines the system logic for determining a client's role(s) from stored data and the rules for generating unique reference numbers. This file answers "how are roles inferred?" and "how are reference numbers generated?" — it contains zero Eloquent model code.

> **Flag values and all flag assignment timing rules:** `../01_BUSINESS_CONTEXT/03_BUSINESS_RULES.md` → BR-001-3 through BR-001-6
> **How to enforce immutability and flag updates in code:** `../../CONSTITUTIONS/04_DATABASE_COMMUNICATION.md` → Write Path
> **Reference number generation locking mechanism:** `../../CONSTITUTIONS/04_DATABASE_COMMUNICATION.md` → Special Cases

---

## Role Inference

A client's roles are determined by checking whether each role flag exists in the `client_type_flags` JSONB array. This is an O(1) operation — no JOINs or subqueries are required.

**Valid Flag Values:** `customer`, `agent`, `investor`

**Inference Rule:** A client "is" a role if and only if the corresponding string exists in the flags array. A client can hold any combination of roles simultaneously.

> **Database index supporting this query:** `../04_DATABASE/03_INDEXES.md` → `idx_clients_type_flags` (GIN)

---

## Reference Number Generation

Reference numbers are generated automatically upon entity creation using a locking query pattern to guarantee uniqueness in concurrent environments.

**Format:** `{PREFIX}-{10-digit number with leading zeros}`

| Entity | Prefix | Example |
|:---|:---|:---|
| Customer | `CUS` | `CUS-0000000001` |
| Contract | `CTR` | `CTR-0000000001` |

**Rules:**
- Generated once, never modified
- Not used as a foreign key
- Used only for paper documents and human reference
- Prefix is defined by the entity's conceptual definition

---
