# Cerebro

**Modern EPGP loot system with native RCLootCouncil integration.**

**Current Stable**: 0.6.3  
**Slash Commands**: `/cerebro`, `/cb`

---

## What It Does

- Calculates and surfaces **PR** (`EP / GP`) for every candidate inside RCLootCouncil.
- Manages EP/GP awards, decay, and audit logs with Ace3-backed persistence.
- Tracks raid sessions, readiness checks, and Mythic+ EP with guild-member dedupe.
- Enforces officer-only actions (charge GP, start session, run checks) via RBAC.

---

## Requirements

- World of Warcraft Retail (12.0.1 / 11.2.7)
- RCLootCouncil
- Ace3 libraries (bundled via `Libs/`)

---

## Installation

1. Download the latest `Cerebro-vX.Y.Z.zip` from [CurseForge](https://www.curseforge.com/wow/addons/cerebro) or Releases.
2. Extract to `Interface/AddOns/Cerebro`.
3. Ensure RCLootCouncil is installed and enabled.

---

## Usage

| Command | Description |
|:--------|:------------|
| `/cb show` | Toggle main window |
| `/cb standings` | View EP/GP/PR |
| `/cb start` | Begin raid session (officer) |
| `/cb check` | Run readiness/prep check (officer) |
| `/cb status` | Diagnostics (human or machine-readable) |
| `/cb selftest` | Run internal health checks |

---

## Architecture

### Foundation

- **Framework**: Built on **Ace3** (AceAddon, AceEvent, AceGUI, AceDB, AceComm).
- **Event-Driven**: Heavily utilizes WoW API events and internal messaging.
- **Database**: Uses `AceDB-3.0` for persistent storage in `CerebroDB`.

### Key Components

| File | Responsibility |
|:-----|:---------------|
| `Core.lua` | Initialization, slash commands, event routing, options menu |
| `Database.lua` | Database defaults, migrations, and shared storage access |
| `Utilities.lua` | Helper functions (Item parsing, Player name colors, Slot mapping) |
| `Models/Player.lua` | OO-style player data handling (Math for PR/EP/GP) |
| `Models/Ledger.lua` | Logging system for Transactions and Audit logs |
| `Modules/EPGP.lua` | Core logic for Awards, Charges, and Weekly Decay |
| `Modules/Session.lua` | Raid session management |
| `Modules/RCLC_Bridge.lua` | Integration with RCLootCouncil (UI injection + event hooks) |
| `Modules/MythicPlus.lua` | M+ run tracking with duplicate prevention |
| `Modules/Communication.lua` | Inter-client messaging and sync |
| `Modules/Preparation.lua` | Readiness checks and consumable tracking |
| `Modules/Diagnostics.lua` | Health checks and self-test runner |
| `UI/MainFrame.lua` | Main tabbed interface |
| `UI/StandingsFrame.lua` | Player rankings display |

---

## Data Model

### Database Structure (`CerebroDB.global`)

- **config.epgp**: Settings for decay rates, base GP, and slot weights.
- **players**: Map of `playerName: { ep, gp, class }`.
- **transactions**: Log of every EP/GP change.
- **audit**: Log of administrative actions.

### Priority Logic

- **Base GP**: Configuration option to prevent infinite PR for new players.
- **Decay**: Percentage-based weekly reduction of EP and GP.
- **Slot Weights**: Configurable GP multiplier per equipment slot.

---

## UI Tabs

- **Standings**: Sortable list of all players, EP, GP, and PR.
- **History**: Read-only log of transaction history.
- **Officer Tools**: Manual adjustments, GP weight config, Session controls.
- **Officer Logs**: Read-only audit trail.

---

## Documentation

- `docs/INDEX.md` — Governance and doc map (authoritative entry point)
- `docs/SPEC.md` — Canonical functional specification (highest authority)
- `docs/ARCHITECTURE.md` — Module contracts and design
- `docs/SECURITY_MODEL.md` — RBAC, officer detection, audit requirements
- `docs/USER_TEST_BLUEPRINT.md` — Authoritative user acceptance tests

---

## Changelog
*   **0.10.5**: Added /cb standingsreset YES officer command: zeroes EP, resets GP to base, and clears attendance for all players without incrementing epoch. Migrated /cb synccheck to V1 transport for reliable peer responses. Fixed totalBossKills sync guard to accept officer values unconditionally.

- **0.10.4**: Bugfix: Added nil checks to IsItemToken function to prevent Lua errors when hovering over world content items without GP values.

- **0.10.3**: Hotfix: Fixed nil target crash in SendFetch when RequestSync broadcasts to channel instead of specific peer.
- **0.10.2**: Migrated all remaining V1 broadcasts (Session, CommandRegistry, Ledger) to V2 RPC protocol. Added per-peer cooldown to prevent duplicate SNAPSHOT/FETCH sends during sync cycles.
- **0.10.1**: Auto-Recovery: Officers now automatically push standings to raiders who lost their SavedVariables, eliminating the need for manual re-admission.

- **0.10.0** (CORE UPGRADE): Communication V2 Protocol: Hash-based state sync using 4 message types (heartbeat/fetch/snapshot/RPC) replaces 29-type v1 congestion. DJB2 deterministic hashes for roster and config state enable divergence detection without full data transfer. 24-method RPC dispatch, session-start sync barrier, /cb synccheck, tiered debug system (Off/Simple/Technical/Both), sync status indicator in both UIs, and rank visibility auto-detection from player data.

- **0.9.8**: Gossip digest self-filter to prevent false mismatch from own GUILD broadcasts; Admit Candidates dropdown now respects rank visibility settings
- **0.9.7**: Sync Reliability Overhaul: Canonical content hash, sync leader election with non-leader forwarding, combat gate verification, dual-channel session broadcast with pre-raid convergence, guild rank visibility filter (3-layer defense + UI), whisper reliability, tooltip data pollution fix, /cb purgeghosted command
- **0.9.6**: Fix ANN_SELF announce spam from rapid guild triggers; improve post-sync checksum verification with retry logic; refactor tooltip injection to avoid WoW 12.0 taint and add player EPGP info on unit mouseover.
- **0.9.5**: Add GP cost tooltips on equippable items (Normal/Heroic/Mythic). Fix RCLC Bridge charging Normal GP regardless of raid difficulty.
- **0.9.4**: Add /cb syncaudit officer diagnostic for identifying per-player sync divergence across all online guild members. Fix attendance display by pre-computing eligible boss kills (fixes >100% attendance). Add addon icon to TOC.
- **0.9.3**: Raid Sync v2: Smart heartbeat with peer-aware sync, targeted whispers for stale players, receipt deferral during raid, and configurable sync intervals.
- **0.9.2**: Fixed taint error popup appearing after boss kills by queuing raid chat messages during combat lockdown.
- **0.9.1**: Fixed IsOfficer false-positive bug causing whisper spam to offline players. Added /cb auditofficers diagnostic command. Added online checks to all WHISPER sends.
- **0.9.0** (CORE UPGRADE): Delta Sync v2: Receipt cursor tracking with serial batching, retry logic, and robust state management
- **0.8.24**: Fixed Session ID Leak in History tab where M+ EP awards incorrectly displayed raid session tags when an officer had an active session
- **0.8.23**: Fixed attendance display bug: Officer Tools 'Admit to Core' button now correctly sets admission timestamp for fair attendance tracking
- **0.8.22**: Fixed session attendance tracking - on-time and full attendance flags are now correctly preserved during sync, preventing stale data from overwriting locally-set flags. Added session start/end entries to History tab.
- **0.8.21**: Fixed LWW sync bug where admitted players reverted to Pending when offline officers came online
- **0.8.20**: Fixed case sensitivity bug in EP/GP adjustment popup dialogs (editBox → EditBox)
- **0.8.19**: Fixed bug where Mythic+ runs from other characters would incorrectly display under My Progress when logging into alts.
- **0.8.18**: Fixed sync bug where offline officers' pre-reset EP/GP data could resurrect after factory reset. Added epoch tagging for stale record detection.
- **0.8.17**: Fixed raider EP sync gap after M+ runs; Fixed M+ duration display (API returns milliseconds)
- **0.8.16**: Fixed M+ completion time bug where UI reload during a run caused incorrect duration to be recorded; now uses server-authoritative completion time.
- **0.8.15**: Fixed M+ EP auto-sync: raiders' EP now properly syncs to officers after dungeon completion. Officers can now use /cb restore YES.
- **0.8.14**: Added paper doll GP slot weights configuration with 3D character model, slot icons matching WoW character frame layout, and weapon type overlays.
- **0.8.13**: Fixed M+ completion tracking broken in 12.0 by updating deprecated GetCompletionInfo API to GetChallengeCompletionInfo.
- **0.8.12**: In-game onboarding wizard (5 screens), native EP/GP/PR tiles, fixed Unicode encoding, consistent UI padding
- **0.8.11**: Added 5-screen onboarding wizard for new players with /cb intro command. Fixed Unicode characters for WoW font compatibility.
- **0.8.10**: My Progress UI: Equation layout (EP ÷ GP = PR) with hover tooltips explaining each stat, taller readiness bar, visual polish
- **0.8.9**: Added /cb freshstart YES command for local client recovery - wipes local data and re-syncs from officers without affecting guild epoch.
- **0.8.8**: Added raid attendance tracking: on-time bonus with configurable grace period, full attendance awards, per-boss tracking, new Attend column in Standings UI with color-coded percentages, 6 new /cb attendance subcommands, and fair calculation for new Core members.
- **0.8.7**: Add Player Purge system (/cb purge, /cb purgetest) for permanent player removal with sync-aware ledger. Add command validation lint script.
- **0.8.6**: Season auto-reset: Automatically clears M+ history and resets EP/GP standings when new M+ season detected. Guild M+ History improvements: Name-Realm format with class colors, compact filters with right-aligned count. EP cap message deduplication.
- **0.8.5**: Guild M+ History tab: Repurposed Raider Audit to display guild-wide M+ runs with native frames matching My Progress style, Player column, filter dropdowns (Player/Dungeon/Level/Result), and proper dungeon name lookup. Fixed test M+ run generation for 5-member parties with unique runKeys.
- **0.8.4**: Fixed debug mode sync leak (raiders no longer inherit officer's debug setting); added unit tests for Switch Guild feature; fixed GUEST_STUB freeze behavior
- **0.8.3**: Guild-wide factory reset, audit preservation with epoch markers, offline backup protection
- **0.8.2**: Fix scope override sync race condition - Wipe now activates quarantine to prevent incoming syncs from re-injecting stale scope; added defensive WIPE confirmation handling and fixed UI:Hide to close restricted access frame.
- **0.8.1**: Fixed debug mode toggle sync between Weights tab and Blizzard Options. Added /cb debug on|off arguments. Silenced RepairDatabase messages.
- **0.8.0** (CORE UPGRADE): Sync Architecture Overhaul: Self-only M+ awards, LWW standings sync with server timestamps, officer-only epoch propagation, local-only transaction history.
- **0.7.20**: Fixed missing version field in SyncToRaid payload causing officers to be incorrectly flagged as legacy clients during periodic sync.
- **0.7.19**: Improved version rejection logging with clear sender identification and chat warnings. Added audit log deduplication to prevent duplicate entries when multiple officers observe the same event.
- **0.7.18**: Added pre-award runKey deduplication using server time and full party composition for deterministic run identification
- **0.7.17**: Fixed test file loading errors in release (tests are now dev-only, excluded from CurseForge package)
- **0.7.16**: Added Version Enforcement: MIN_SYNC_VERSION (0.7.15) blocks outdated clients from syncing, transactions stamped with logicVersion for schema validation, legacy transactions marked with * in History tab. New /cb versioncheck command for officers. Added Officer Receipt Fallback when no officers online.
- **0.7.15**: Polish: class color on admit, delete resets to Pending
- **0.7.14**: Fixed HandleAnnounceSelf incorrectly promoting raiders to Core
- **0.7.13**: Added debug tracing for status changes during sync
- **0.7.12**: Fixed new player status bug: all entries now start as Pending, officers self-correct after login
- **0.7.11**: Fixed sync architecture bugs: self-sync guard, raider-to-raider sync prevention, player table merge instead of replace, guild sync fallback, and removed auto-promotion on raid join
- **0.7.10**: Add dev-only --target flag to M+ simulation for officer testing of EP sync to specific players
- **0.7.9**: Fixed GUID mismatch spam in debug output - now only logs once when actually healing the GUID
- **0.7.8**: Fixed sync registration bug where raiders weren't visible to officers after SV reset. Added GUID auto-heal for scope mismatches.
- **0.7.7**: Fix multi-officer sync EP data loss, add distribution validation, reorganize officer infrastructure
- **0.7.6**: Fixed IsOfficer solo fallback bug that auto-promoted new players to Core status; /cb admit now refreshes UI for already-Core players
- **0.7.5**: Fixed MythicPlus module missing AceTimer-3.0 mixin causing ScheduleRepeatingTimer errors
- **0.7.4**: Guild Locking feature - restrict EPGP data to authorized guild
- **0.7.3**: Fixed nil method error in MythicPlus.lua when addon loads during active M+ run
- **0.7.2**: Factory reset quarantine system - prevents data restoration via sync after reset
- **0.7.1**: Added season tracking utilities (GetSeasonInfo, GetCurrentSeasonWeek, GetGameVersion) with UI footer display and officer-configurable season start override
- **0.7.0** (CORE UPGRADE): My Progress UI: LFG-style icons, EP breakdown tooltips, randomized test data, role terminology standardization
- **0.6.6**: Remove test entries from TOC for CurseForge compatibility
- **0.6.5**: Fix packaging: strip test entries from TOC, add validation
- **0.6.4**: Consolidated documentation, excluded dev files from distribution

- **0.6.3**: Fixed packager workflow syntax
- **0.6.2**: Fixed package naming and game version configuration
- **0.6.1**: Added CurseForge CI/CD automation
- **0.6.0** (CORE UPGRADE): Communication module reworked for persistent guild database
- **0.5.8**: Fix: Sync Status bug - Officers now auto-initialize as Core
- **0.5.7**: Fixed LibDBIcon-1.0 compatibility
- **0.5.6**: Consolidated deploy scripts into single cross-platform script
- **0.5.5**: Refined Mythic+ EP formula and history breakdown
- **0.5.4**: Fixed scroll cutoff in Weights and Settings tabs
- **0.5.3**: Added minimap button for quick access
- **0.5.2**: Added factory reset failsafe with GM-only restrictions
- **0.5.1**: M+ Deduplication & Hardening
- **0.5.0** (CORE UPGRADE): Package-based dependency management for Ace3
- **0.4.4**: Fixed permissions regression and added diagnostics
- **0.4.3**: Added /cb status command
- **0.4.2**: Fixed layout regression in History/System Logs tabs
- **0.4.1**: Fixed Officer Tools tab scrollbar
- **0.4.0** (CORE UPGRADE): Documentation Governance with docs/INDEX.md
- **0.2.1**: RCLC bridge modernization (RBAC + idempotency)
- **0.2.0** (CORE UPGRADE): Core Modernization with comprehensive documentation
- **0.1.0** (CORE UPGRADE): Log-Based Sync architecture

<details>
<summary>Earlier versions (0.0.x)</summary>

- **0.0.49**: Hotfix: Fixed syntax error in Communication.lua
- **0.0.48**: Player Inclusion Logic with Pending status
- **0.0.47**: Fixed unwanted circle around portrait
- **0.0.46**: UI Polish: Added spacing in My Progress
- **0.0.45**: Enforce full name normalization
- **0.0.44**: Prevent regeneration of 'player' DB entry
- **0.0.43**: Fix hardcoded 'player' usage
- **0.0.42**: Correct MyProgress player binding
- **0.0.41**: Add audit logging to fixdb command
- **0.0.40**: Fix MyProgress Rank calculation
- **0.0.39**: Fix MyProgress UI bleed
- **0.0.38**: Added missing GetClassColorString utility
- **0.0.37**: Implemented My Progress UI
- **0.0.36**: Fixed IsOfficer variable assignment
- **0.0.35**: Corrected IsOfficer keyword detection
- **0.0.34**: Purged legacy DKP mentions
- **0.0.33**: Enhanced IsOfficer for Guild Master
- **0.0.32**: Updated versioning script
- **0.0.31**: Made Officer Logs read-only
- **0.0.30**: History tab defaults to read-only
- **0.0.29-0.0.1**: Initial development and iterations

</details>

---

## Credits

### Methodology & Design

- **Savas**: Core methodology derivation and system design.

### Active Feedback & QA

- **Savas**: Continuous feedback and loop validation.
- **Zurth**: Active feedback and edge-case identification.

### Beta Testing

- **Zurth**, **Savas**, **Phil**, **Dudley**

---

## License

GPLv3 - See [LICENSE](LICENSE) for details.
