# Cerebro

**A guild-first EPGP loot system with RCLootCouncil integration and Mythic+ tracking.**

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

---

## What It Does

Cerebro is a **complete loot management solution** that brings fairness and transparency to your guild's EPGP economy.

### For Raiders

- **See your priority** — Know exactly where you stand with live PR (Priority Rating) displayed directly in RCLootCouncil
- **Earn EP from Mythic+** — Guild runs automatically award Effort Points with bonuses for higher keys and more guildies
- **Track your progress** — View your EP, GP, rank, and M+ history in the "My Progress" tab
- **Always in sync** — Your standings update automatically from officer broadcasts

### For Raid Leaders & Officers

- **Run sessions with ease** — Track attendance, award boss kill EP, and manage decay with simple commands
- **Automatic GP charges** — RCLootCouncil awards flow through seamlessly, applying correct GP costs per slot
- **Full audit trail** — Every EP/GP change is logged and visible for complete transparency
- **Guild M+ History** — See all guild members' Mythic+ activity in one place with filters by player, dungeon, or key level

---

## 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 |

---

## Changelog
*   **0.10.27**: Fix season reset double-fire and single-person standings on concurrent officer login. Prevent duplicate EP/GP wipe when multiple officers log in after a new season starts.
*   **0.10.26**: Prep check redesign with proportional EP scoring, per-section config LWW sync, realm name normalization, database hardening, and session lifecycle fixes.
*   **0.10.24**: Fix officer sync divergence: dynamic config hash covers all settings automatically, config merge uses LWW timestamps, auto-discovery no longer pollutes roster timestamps, purge/block zombie cleanup on snapshot receive.
*   **0.10.23**: Player Management Overhaul: new /cb block, /cb unblock, /cb blockedlist commands; purge is now a soft reset; auto-discover group members as Pending; Standings rank filters and Hide Non-Guildies restored; sync field whitelist drops junk data; UTF-8 player name fix; non-guild players display '--' rank instead of 'Unknown(R99)'.
*   **0.10.22**: Added calendar sign-up EP, custom EP templates, Farm/Prog boss EP split, collectible item GP (toys, pets, mounts), and duplicate slot GP multiplier. Fixed sync loop causes including officer-to-officer hash divergence, redundant dual-channel raid broadcasts (PR26), and synccheck self-echo.
*   **0.10.21**: Fix permanent sync divergence from ghost Pending records and eliminate thundering herd during raid sync (Options A/B/E).
*   **0.10.20**: Officer detection refactored to use guild permission flags (GuildControlGetRankFlags) instead of rank-name matching. Added per-tier RCLC GP modifiers, standings multi-select with bulk actions and context menu, configurable tooltip mode (always/raid/never), M+ EP formula v1.2 with min-level gate and per-tier guild bonuses, and session pre-flight player validation. Config schema reorganized into Admin, EP Awards, and GP Modifiers categories.
*   **0.10.19**: Accept M+ Readiness EP broadcasts from raiders (fixes stranded EP) and add bidirectional officer-to-officer snapshot exchange on mismatch (fixes post-season-reset sync stalls).
*   **0.10.18**: Rate-limit heartbeat echoes to once per peer per 90 seconds and add receive-side dedup (5s window) to eliminate duplicate HB processing from stacked senders.
*   **0.10.17**: Fix raider LWW merge to detect and override auto-created Pending stubs that block officer data, while preserving real EP/GP from multi-officer scenarios. Improves merge debug logging with stub override tracing.
*   **0.10.16**: Fix persistent roster hash divergence between officers and raiders by making raider-side reconciliation adopt the officer's player set as authoritative. Add /cb debughash diagnostic command for cross-client hash comparison. Fix heartbeat retry backoff to auto-reset after 5 minutes instead of permanently suppressing sync attempts.
*   **0.10.15**: Fixed V2 sync loop and whisper storm: Resolved cross-realm reachability check bug in SendV2Message preventing ghost player cleanup. Enhanced IsOfficer fallback to use cached guild ranks, preventing officers from misidentifying each other. Added 15-second cooldown to HandleHeartbeat to prevent rapid FETCH retry suppression during echo storms.
*   **0.10.14**: V2 Persistent Session Sync: Session state is now a first-class V2 sync citizen with instant propagation via SyncToRaid(). Session ID included in roster hash for automatic divergence detection. Fixed HandleSessionEnd destructive wipe and HandleSnapshot nil session propagation. Added startedBy field to session schema. Updated Interface version to 120001 (Midnight pre-patch). Dev deploy now uses incremental _devN build numbering.
*   **0.10.13**: V2 Persistent Session Sync: Session state is now a first-class V2 sync citizen with instant propagation
*   **0.10.12**: Fixed season reset status reversion: raiders stuck in Awaiting Officer Approval after epoch upgrade due to phantom Pending record creation race condition. Removed premature RefreshAllUI() from HandleEpochMismatch. Added post-merge self-correction in V2 HandleSnapshot.
*   **0.10.11**: Fixed stale data resurrection after season reset: RPC dispatch rejects messages from senders with stale epochs. Added zombie session guard in EndSession - sessions older than 12 hours are discarded without awarding EP. Added epoch checks to HandleEPGPUpdate and HandleEPGPForward.
*   **0.10.10**: Fixed stale data resurrection after season reset: RPC dispatch now rejects all messages from senders with stale epochs (blanket protection). Added zombie session guard in EndSession — sessions older than 12 hours are discarded without awarding EP. Added epoch checks to HandleEPGPUpdate and HandleEPGPForward (defense-in-depth).
*   **0.10.9**: Sync payload integrity hardening: post-merge hash verification in HandleSnapshot detects LWW races and partial delivery, triggering automatic re-fetch on mismatch. Added SNAPSHOT_ACK RPC so officers receive convergence confirmation from receivers.
*   **0.10.8**: Migrated M+ communications to V2 transport with raid suppression gate. Fixed My Progress rank to respect Standings visibility settings.
*   **0.10.7**: Fixed V2 reset RPC key mismatch (RESET vs FACTORY_RESET) that silently dropped reset broadcasts. Added targeted WHISPER snapshot propagation for immediate reset delivery to online guild members. Fixed epoch upgrade data loss for raiders by auto-fetching officer data after epoch acceptance. Filtered Officer tab Player dropdown by Standings Visibility ranks.
*   **0.10.6**: Fixed V2 epoch propagation failure and standings reset data reversion. HandleEpochMismatch() replaces flat epoch rejection in V2 handlers, enabling proper epoch upgrades from officers. standingsreset now increments epoch to prevent stale data resurrection. Shared ResetStandings() core for both reset commands. Expanded factoryreset wipe scope.
*   **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.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>

---

## Officer Companion (Cloud Sync)

> [!IMPORTANT]
> **This section is for OFFICERS ONLY.** Regular guild members do not need any external tools.

For officers who want to sync EPGP data across multiple computers or create cloud backups, a separate **desktop companion app** is available.

### What It Does

- Watches your WoW SavedVariables for changes
- Uploads snapshots to your guild's private Supabase cloud storage
- Runs in system tray (menu bar on macOS)

### Security Model

- **Each officer has their own unique API key** - keys are NOT shared between officers
- **Config is stored locally** on each officer's machine (`~/.config/cerebro/config.json` on macOS)
- **Nothing is bundled** - downloading the app gives you a fresh setup wizard
- **Guild Master controls access** - only the GM can generate API keys for officers

### Getting Started

1. Your GM will provide: Supabase URL, Guild ID, and your personal API key
2. Download the app from [Releases](https://github.com/Shezzannn/Cerebro/releases)
3. Run the setup wizard and enter your credentials
4. The app runs in the background and syncs automatically

See [`docs/HELPER_APP.md`](docs/HELPER_APP.md) for full documentation.

---

## 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.
- **MysterT**: Active feedback and QA.

### Beta Testing

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

---

## License

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