# Mana-Loop: Comprehensive Game Briefing Document

**Document Version:** 3.0
**Updated:** Post-refactoring — skills removed, disciplines procedural guardians, combo bosses, 14 mana types, localStorage-only

---

## Table of Contents

1. [Executive Summary](#executive-summary)
2. [Core Game Loop](#core-game-loop)
3. [Mana System](#mana-system)
4. [Time & Incursion System](#time--incursion-system)
5. [Spire & Floor System](#spire--floor-system)
6. [Combat System](#combat-system)
7. [Guardian System](#guardian-system)
8. [Attunement System](#attunement-system)
9. [Discipline System](#discipline-system)
10. [Equipment & Enchantment System](#equipment--enchantment-system)
11. [Golemancy System](#golemancy-system)
12. [Prestige/Loop System](#prestigeloop-system)
13. [Achievement System](#achievement-system)
14. [Formulas & Calculations](#formulas--calculations)
15. [System Interactions](#system-interactions)
16. [Code Architecture](#code-architecture)

---

## Executive Summary

**Mana-Loop** is a browser-based incremental/idle game with a 30-day time loop mechanic. Players gather mana, practice disciplines, climb a 100+ floor spire, defeat procedurally-tiered guardians, sign pacts, enchant equipment, summon golems, and prestige for permanent progression.

**Key Differentiators:**
- 3-class Attunement system (Enchanter, Invoker, Fabricator)
- Equipment-based spell system (spells come from enchanted gear and learned spells)
- Practice-based Discipline system — no discrete skill levels, only continuous XP growth
- Time pressure through the incursion mechanic (starts day 5)
- Guardian progression: base → compound → exotic → combination bosses (150+)
- Guardian pacts provide permanent multipliers that persist through prestige
- No backend — pure client-side with localStorage persistence

**Code Architecture:** Modular Zustand stores, crafting actions, discipline data, and constants. No legacy store files remain.

---

## Core Game Loop

### Primary Loop (Within Each Run)

```
┌─────────────────────────────────────────────────────────────┐
│                      TIME LOOP (30 Days)                     │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────┐    ┌────────────┐    ┌───────────┐    ┌──────┐ │
│  │ GATHER  │───▶│  PRACTICE  │───▶│   CLIMB   │───▶│CRAFT │ │
│  │  MANA   │    │ DISCIPLINES│    │   SPIRE   │    │ GEAR │ │
│  └─────────┘    └────────────┘    └───────────┘    └──────┘ │
│       │               │                │               │    │
│       └───────────────┴────────────────┴───────────────┘    │
│                            │                                 │
│                            ▼                                 │
│  ┌─────────────────────────────────────────────────────┐   │
│  │     DEFEAT GUARDIANS → SIGN PACTS (every 10th)      │   │
│  │     Base(10-80) → Compound(90-110) → Exotic(120-140)│   │
│  │     → Combination Bosses(150+)                       │   │
│  └─────────────────────────────────────────────────────┘   │
│                            │                                 │
│                            ▼                                 │
│  ┌─────────────────────────────────────────────────────┐   │
│  │           DAY 30: LOOP ENDS → GAIN INSIGHT           │   │
│  └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘
```

### Game Actions

| Action | Effect | Time Cost |
|--------|--------|-----------|
| **Meditate** | Regen mana with meditation bonus multiplier | Passive (auto-selected after actions) |
| **Climb** | Progress through spire floors, cast spells | Active combat |
| **Practice** | Run active disciplines, consuming mana each tick | Continuous |
| **Craft** | Create/enchant equipment (Design/Prepare/Apply) | Hours per stage |
| **Convert** | Auto-convert raw mana to elements | Per tick |
| **Design** | Create enchantment designs | Hours |
| **Prepare** | Ready equipment for enchanting | Hours + mana |
| **Enchant** | Apply enchantment to equipment | Hours + mana |

### Action Transitions
- After completing Design, Prepare, Enchant, or Craft the game automatically transitions to **Meditate**
- Action buttons are hidden when in Spire Mode
- `currentAction` state lives in the combat store

---

## Mana System

### Mana Types Hierarchy

```
Raw Mana (Base Resource)
    │
    ├──▶ Base Elements (7) ─────────────────────────────────────┐
    │    Fire*, Water*, Air*, Earth*, Light*, Dark*, Death*     │
    │    *Locked at start — must be unlocked via guardian pacts │
    │                                                           │
    ├──▶ Utility Element (1) ───────────────────────────────────┤
    │    Transference (Enchanter attunement — UNLOCKED at start)│
    │                                                           │
    ├──▶ Composite Elements (3) ── Created from 2 base ─────────┤
    │    Metal = Fire + Earth                                   │
    │    Sand  = Earth + Water                                  │
    │    Lightning = Fire + Air                                 │
    │                                                           │
    └──▶ Exotic Elements (3) ── Created from advanced recipes ──┤
         Crystal = Sand + Sand + Light                          │
         Stellar = Fire + Fire + Light                          │
         Void    = Dark + Dark + Death                          │
```

Only **Transference** is unlocked at start. All other elements must be unlocked through guardian pacts.

### Mana Formulas

**Maximum Raw Mana:**
```
base = 100 + (manaWell_prestige × 500) + disciplineMaxManaBonus
final = (base + equipmentMaxManaBonus) × equipmentMaxManaMultiplier
```

**Maximum Elemental Mana:**
```
elementMax = (10 + (elemAttune_prestige × 25)) × elementCapMultiplier
```

**Base Regeneration (per hour):**
```
base = 2 + (manaFlow_prestige × 0.5)
temporalMult = 1 + (temporalEcho_prestige × 0.1)
regen = base × temporalMult + attunementRegen + disciplineRegenBonus
final = (regen + equipmentRegenBonus) × equipmentRegenMultiplier
```

**Effective Regen (per tick):**
```
effectiveRegen = max(0, baseRegen × (1 - incursionStrength) × meditationMultiplier - totalConversionPerTick)
```

**Meditation Bonus:**
```
Base: 1 + min(hours/4, 0.5)  →  up to 1.5× after 4 hours
```

**Attunement Mana Conversion:**
- Enchanter: Raw → Transference at 0.2/hour base (scales with 1.5^level)
- Fabricator: Raw → Earth at 0.25/hour base (scales with 1.5^level)
- Invoker: No automatic conversion (gains mana from pacts)

### Mana Conversion Cost
- **100 Raw Mana = 1 Elemental Mana** (for base elements)
- Composite/Exotic elements are crafted, not converted

---

## Time & Incursion System

### Time Constants

| Constant | Value | Description |
|----------|-------|-------------|
| `TICK_MS` | 200ms | Real time per game tick |
| `HOURS_PER_TICK` | 0.04 | Game hours per tick |
| `MAX_DAY` | 30 | Days per loop |
| `INCURSION_START_DAY` | 5 | When incursion begins |

### Time Progression
- 1 real second = 5 game hours (at 5 ticks/second)
- 1 game day = 24 game hours = 4.8 real seconds
- Full 30-day loop ≈ 2.4 real minutes

### Incursion Mechanic

```
if (day < 5):  incursionStrength = else:          incursionStrength = min(0.95, (totalHours / maxHours) × 0.95)
  where totalHours = (day - 5) × 24 + hour
        maxHours   = (30 - 5) × 24 = 600
```

Reduces mana regeneration by `(1 - incursionStrength)`. Starts at 0% on Day 5, reaches 95% by Day 30.

---

## Spire & Floor System

### Floor Element Cycle

```
FLOOR_ELEM_CYCLE = [fire, water, air, earth, light, dark, death]
element = FLOOR_ELEM_CYCLE[(floor - 1) % 7]
```

### Floor HP Formulas

**Normal floors:**
```
HP = floor(100 + floor × 50 + floor^1.7)
```

**Guardian floors:**
```
HP = floor(5000 × (floor/10) ^ (1.1 + floor/200))
```

### Room Types

| Room Type | Chance | Description |
|-----------|--------|-------------|
| **Guardian** | Every 10th floor | Boss encounter |
| **Puzzle** | 20% on every 7th floor | Attunement-themed trial |
| **Swarm** | 15% | 3–6 enemies with 40% HP each |
| **Speed** | 10% | Enemy with dodge chance (25% base + 0.5%/floor, max 50%) |
| **Combat** | Default | Single enemy, normal combat |

### Puzzle Room Types
- Single attunement: `enchanter_trial`, `fabricator_trial`, `invoker_trial`
- Dual attunement: `hybrid_enchanter_fabricator`, `hybrid_enchanter_invoker`, `hybrid_fabricator_invoker`
- Base progress: 1.5–2% per tick; attunement bonus: 2.5–3% per relevant attunement level

### Enemy Modifiers (Non-Guardian Floors)

| Modifier | Min Floor | Effect | Scaling |
|----------|-----------|--------|---------|
| **Armored** | 5+ | Armor (damage reduction) | 10%–45%, scales with floor |
| **Agile** | 12+ | Dodge chance | 20% base + 0.4%/floor, max 55% |
| **Mage** | 15+ | Barrier (shield HP) | Up to 40% of max HP, recharges 5%/tick |
| **Shield** | 10+ | One-time shield | 15% of max HP |
| **Swarm** | 8+ | Multiple weaker enemies | 3–7 enemies, each 35% HP |

Max 2 modifiers per enemy. Low floors (1–4) get no modifiers.

### Armor Scaling (Non-Guardian)
- No armor below floor 10
- Armor chance: `min(0.5, (floor - 10) × 0.01)`
- Armor value: 5%–25% damage reduction, scaling with floor progress

---

## Combat System

### Spell Casting Mechanics

```
castProgress += HOURS_PER_TICK × spellCastSpeed × attackSpeedMultiplier
When castProgress >= 1: deduct mana, deal damage, reset progress
```

### Damage Calculation

```
baseDmg = spell.dmg + disciplineBaseDmgBonus
pctMult = 1 + disciplineDmgMult
elemMasteryMult = 1 + (elementalMastery × 0.15)
guardianBaneMult = 1 + (guardianBane × 0.2)  [guardian floors only]
rawDmgMult = 1 + boonRawDamage / 100
elemDmgMult = 1 + boonElementalDamage / 100

damage = baseDmg × pctMult × elemMasteryMult × guardianBaneMult × rawDmgMult × elemDmgMult
damage *= getElementalBonus(spellElement, floorElement)

// Critical hit
critChance = disciplineCritChance + boonCritChance / 100
critDmgMult = 1.5 + boonCritDamage / 100
if (random() < critChance) damage *= critDmgMult

// Special modifiers
if (floorHP / floorMaxHP < 0.25) damage *= 2    // Executioner
if (rawMana < maxMana × 0.5) damage *= 1.5      // Berserker

// Armor reduction
effectiveArmor = max(0, enemyArmor - armorPierce)
damage *= (1 - effectiveArmor)
```

### Elemental Effectiveness

| Condition | Multiplier |
|-----------|------------|
| Spell opposes floor element (super effective) | 1.50× |
| Spell matches floor element | 1.25× |
| Spell's opposite matches floor (not very effective) | 0.75× |
| Neutral / Raw mana spells | 1.00× |

**Element Opposites:**
```
Fire ↔ Water    Air ↔ Earth    Light ↔ Dark
Lightning → Earth (grounding)
```

### Spell Tiers

| Tier | Category | Example Spells |
|------|----------|----------------|
| 0 | Raw | Mana Bolt (5 dmg), Mana Strike (8 dmg) |
| 1 | Basic Elemental | Fireball, Water Jet, Gust, Stone Bullet, Light Lance, Shadow Bolt, Drain |
| 1 | Lightning | Spark, Lightning Bolt, Chain Lightning, Storm Call |
| 1 | Compound | Metal Shard, Iron Fist, Sand Blast, Sandstorm |
| 1 | AOE | Fireball AOE, Frost Nova, Meteor Shower, Blizzard |
| 1 | Utility | Transfer Strike, Mana Rip, Essence Drain |
| 2 | Advanced | Inferno, Tidal Wave, Earthquake, Hurricane |
| 3 | Master | Pyroclasm, Tsunami, Meteor Strike, Heaven Light, Oblivion |
| 3 | Compound Master | Furnace Blast, Dune Collapse |
| 4 | Legendary | Stellar Nova, Void Collapse, Crystal Shatter |

### Spell Effects
- `burn`: Damage over time
- `freeze`: Prevents dodge
- `chain`: Hits additional targets
- `aoe`: Area of effect
- `armor_pierce`: Ignores percentage of armor
- `stun`, `pierce`, `multicast`, `shield`, `buff`

---

## Guardian System

### Guardian Tiers

#### Tier 1 — Base Elements (Floors 10–80)

| Floor | Name | Element | Armor | Pact Mult | Pact Cost | Pact Time |
|-------|------|---------|-------|-----------|-----------|-----------|
| 10 | Ignis Prime | fire | 10% | 1.5× | 500 | 2h |
| 20 | Aqua Regia | water | 15% | 1.75× | 1,000 | 4h |
| 30 | Ventus Rex | air | 18% | 2.0× | 2,000 | 6h |
| 40 | Terra Firma | earth | 25% | 2.25× | 4,000 | 8h |
| 50 | Lux Aeterna | light | 20% | 2.5× | 8,000 | 10h |
| 60 | Umbra Mortis | dark | 22% | 2.75× | 15,000 | 12h |
| 70 | Mors Ultima | death | 25% | 3.0× | 25,000 | 14h |
| 80 | Vinculum Arcana | transference | 20% | 3.25× | 35,000 | 16h |

#### Tier 2 — Composite Elements (Floors 90–110)

| Floor | Element | Armor | Pact Mult | Pact Cost | Pact Time |
|-------|---------|-------|-----------|-----------|-----------|
| 90 | metal | 30% | 3.5× | 60,000 | 18h |
| 100 | sand | 25% | 3.75× | 80,000 | 20h |
| 110 | lightning | 22% | 4.0× | 100,000 | 22h |

#### Tier 3 — Exotic Elements (Floors 120–140)

| Floor | Element | Armor | Pact Mult | Pact Cost | Pact Time |
|-------|---------|-------|-----------|-----------|-----------|
| 120 | crystal | 35% | 4.5× | 150,000 | 26h |
| 130 | stellar | 30% | 5.0× | 200,000 | 30h |
| 140 | void | 35% | 5.5× | 300,000 | 34h |

Floors 90–140 have procedurally generated names via `generateGuardianName()`.

#### Tier 4 — Combination Bosses (Floor 150+)

Nine dual-element combinations cycle every 10 floors:

| Combo Index | Elements | Theme |
|-------------|----------|-------|
| 0 | fire + water | Steam |
| 1 | fire + air | Smoke |
| 2 | water + earth | Mud |
| 3 | light + dark | Twilight |
| 4 | death + light | Undeath |
| 5 | fire + death | Hellfire |
| 6 | water + dark | Abyssal |
| 7 | air + light | Radiant wind |
| 8 | earth + death | Fossil |

**Scaling (per floor above 150):**
```
armor           = min(0.5, 0.25 + (floor - 150) × 0.002)
pactMultiplier  = 6.0 + (floor - 150) × 0.05
pactCost        = floor(hp × 0.5)
pactTime        = 20 + floor((floor - 150) / 10)
damageMult      = 3.0 + (floor - 150) × 0.02
insightMult     = 2.5 + (floor - 150) × 0.01
```

Combo guardians grant boons to both elements (+10% each) and dual-aspect perks (+20% effectiveness to both element spells). Names generated from combined prefixes (e.g., "Ignis-Aqua the Warden").

### Guardian HP Formula (All Tiers)
```
HP(floor) = floor(5000 × (floor/10) ^ (1.1 + floor/200))
```

### Guardian Combat Effects

| Element | Passive Effect |
|---------|---------------|
| fire | burn (0.1) |
| water | armor_pierce (0.15) |
| air | cast_speed (0.05) |
| earth | armor_pierce (0.2) |
| light | crit_chance (0.1) |
| dark | crit_damage (0.15) |
| death | raw_damage (0.1) |
| transference | cost_reduction (0.25) |
| metal | armor_pierce (0.2) |
| sand | slow (0.25) |
| lightning | chain (2) |
| crystal | reflect (0.15) |
| stellar | night_bonus (0.3) |
| void | resist_ignore (0.4) |

### Guardian Boons (on pact)

Each guardian grants 2 boons from: `maxMana`, `manaRegen`, `castingSpeed`, `elementalDamage`, `rawDamage`, `critChance`, `critDamage`, `spellEfficiency`, `manaGain`, `insightGain`, `prestigeInsight`.

### Pact Ritual
1. Defeat guardian → floor added to `defeatedGuardians`
2. Start ritual: costs raw mana + time (guardian-specific)
3. Progress increases by `HOURS_PER_TICK` per tick
4. On completion: floor moves to `signedPacts`, boons applied
5. Pact slots limit simultaneous signed pacts (starting 1, upgradeable)

### Victory Condition
Defeat floor 100 guardian **and** sign the pact → 3× normal insight.

---

## Attunement System

Attunements are class-like specializations that unlock discipline pools and grant unique capabilities.

### The Three Attunements

#### 1. Enchanter (Right Hand) — Starting

| Property | Value |
|----------|-------|
| **Slot** | Right Hand |
| **Primary Mana** | Transference |
| **Raw Regen** | +0.5/hour base |
| **Conversion** | 0.2 raw→transference/hour |
| **Unlock** | Starting attunement |

**Disciplines:** 10 disciplines across 4 files (core, utility, spells, special)
**Capabilities:** Enchanting & disenchanting equipment

#### 2. Invoker (Chest) — Locked

| Property | Value |
|----------|-------|
| **Slot** | Chest |
| **Primary Mana** | None (gains from pacts) |
| **Raw Regen** | +0.3/hour base |
| **Conversion** | None |
| **Unlock** | Defeat first guardian |

**Disciplines:** 2 disciplines (Spell Casting, Void Manipulation)
**Capabilities:** Form pacts with guardians, access guardian powers

#### 3. Fabricator (Left Hand) — Locked

| Property | Value |
|----------|-------|
| **Slot** | Left Hand |
| **Primary Mana** | Earth |
| **Raw Regen** | +0.4/hour base |
| **Conversion** | 0.25 raw→earth/hour |
| **Unlock** | Prove crafting worth |

**Disciplines:** 2 disciplines (Golem Crafting, Crafting Efficiency)
**Capabilities:** Golem crafting, gear crafting, Earth shaping

### Attunement Leveling

```
Level 2: 1,000 XP
Level 3: 2,500 XP
Level 4+: 1000 × 2^(level-2) × 1.25
Max Level: 10

regenMultiplier  = 1.5^(level - 1)
conversionRate   = baseRate × 1.5^(level - 1)
```

---

## Discipline System

Disciplines replace the old skill system entirely. There are no discrete levels — disciplines grow **continuously** through practice. The player activates a discipline and it drains mana each tick in exchange for permanent stat growth within the run.

### Core Concept

> The more you practice a discipline, the stronger its effect — but the more mana it costs to maintain.

- **XP** accumulates each tick the discipline is active and has enough mana to drain
- **Stat bonus** grows as a power curve of XP (never resets within a run)
- **Mana drain** also increases with XP — mastery has a cost
- **Perks** unlock at XP thresholds, granting bonus effects

### Formulas

**Stat Bonus (continuous):**
```
StatBonus = baseValue × (XP / scalingFactor)^0.65
```

**Mana Drain Per Tick:**
```
ManaDrainPerTick = drainBase × (1 + (XP / difficultyFactor)^0.4)
```

### Concurrent Discipline Limit

```
concurrentLimit = min(1 + floor(totalXP / 500), 4)
```

Players start with 1 active discipline slot. As total XP across all disciplines grows, additional slots unlock (max 4 total).

### Perk Types

| Type | Behaviour |
|------|-----------|
| `once` | Unlocks permanently when XP reaches `threshold` |
| `capped` | Grants stacking bonus tiers; each tier requires another `interval` XP beyond `threshold` |
| `infinite` | Repeating bonus — a new stack every `interval` XP past `threshold` (no cap) |

### Discipline Pools (34 Total)

| Pool | File | Count | Requires |
|------|------|-------|----------|
| Base | `base.ts` | 1 | None |
| Elemental Attunement | `elemental.ts` | 7 | None |
| Elemental Regen | `elemental-regen.ts` | 8 | None |
| Advanced Regen | `elemental-regen-advanced.ts` | 6 | Mana type unlocked |
| Enchanter Core | `enchanter.ts` | 4 | Enchanter attunement |
| Enchanter Utility | `enchanter-utility.ts` | 2 | Enchanter attunement |
| Enchanter Spells | `enchanter-spells.ts` | 3 | Enchanter attunement |
| Enchanter Special | `enchanter-special.ts` | 1 | Enchanter attunement |
| Invoker | `invoker.ts` | 2 | Invoker attunement |
| Fabricator | `fabricator.ts` | 2 | Fabricator attunement |

### Example Disciplines

| Discipline | Pool | Mana Type | Stat Bonus | Description |
|------------|------|-----------|------------|-------------|
| Raw Mana Mastery | Base | raw | `maxManaBonus` | More raw mana from practice |
| Elemental Attunement (×7) | Elemental | per element | `elementCap_{type}` | Expanded element capacity |
| Elemental Regen (×8) | Regen | per element | `regen_{type}` | Passive element regen |
| Advanced Regen (×6) | Adv. Regen | composite/exotic | `regen_{type}` | Composite/exotic regen |
| Enchantment Crafting | Enchanter | transference | `enchantPower` | Stronger enchantments |
| Study Basic Weapon Enchantments | Enchanter | fire | — | Unlocks sword_fire, sword_frost, sword_lightning |
| Study Advanced Weapon Enchantments | Enchanter | dark | — | Unlocks sword_void, damage_5, crit_5, attack_speed_10 |
| Study Utility Enchantments | Enchanter | light | — | Unlocks meditate_10, study_10, insight_5 |
| Study Mana Enchantments | Enchanter | water | — | Unlocks mana_cap_50, mana_cap_100, mana_regen_1/2, click_mana_1/3 |
| Study Basic Spell Enchantments | Enchanter | air | — | Unlocks 8 basic spell enchants |
| Study Intermediate Spell Enchantments | Enchanter | earth | — | Unlocks 6 intermediate spell enchants |
| Study Advanced Spell Enchantments | Enchanter | dark | — | Unlocks 10 master spell enchants |
| Study Special Enchantments | Enchanter | death | — | Unlocks spell_echo_10, guardian_dmg_10, overpower_80, etc. |
| Spell Casting | Invoker | light | `baseDamage` | +Base damage |
| Void Manipulation | Invoker | void | `baseDamageMult` | +Base damage multiplier |
| Golem Crafting | Fabricator | earth | `golemCapacity` | +Golem capacity |
| Crafting Efficiency | Fabricator | sand | `craftCostReduction` | -Crafting costs |

### Discipline Lifecycle

```
1. Player opens Disciplines tab → sees available disciplines for their attunements
2. Player activates discipline (costs nothing up-front; requires mana type unlocked)
3. Each game tick:
   a. ManaDrain deducted from mana pool
   b. If insufficient mana → discipline auto-pauses
   c. If sufficient mana → disc.xp += 1; stat bonuses recomputed
4. Player can manually pause/resume disciplines
5. On loop end, XP resets (stat bonuses are per-run, not permanent)
```

---

## Equipment & Enchantment System

### Equipment Slots (8)

```
mainHand   - Casters (some 2H), Swords, Catalysts
offHand    - Shields, Catalysts (blocked by 2-handed weapons)
head       - Hoods, Hats, Helms
body       - Robes, Armor
hands      - Gloves, Gauntlets
feet       - Boots, Shoes
accessory1 - Rings, Amulets
accessory2 - Rings, Amulets
```

### Equipment Categories & Types (50 total)

| Category | Slot | Count | Examples |
|----------|------|-------|----------|
| Casters | mainHand | 6 | Basic Staff (2H), Apprentice Wand, Oak Staff (2H), Crystal Wand, Arcanist Staff (2H), Battlestaff (2H) |
| Swords | mainHand | 5 | Iron Blade, Steel Blade, Crystal Blade, Arcanist Blade, Void-Touched Blade |
| Catalysts | mainHand | 3 | Basic Catalyst, Fire Catalyst, Void Catalyst |
| Body | body | 5 | Civilian Shirt, Apprentice Robe, Scholar Robe, Battle Robe, Arcanist Robe |
| Head | head | 5 | Cloth Hood, Apprentice Cap, Wizard Hat, Arcanist Circlet, Battle Helm |
| Hands | hands | 4 | Civilian Gloves, Apprentice Gloves, Spellweave Gloves, Combat Gauntlets |
| Feet | feet | 4 | Civilian Shoes, Apprentice Boots, Traveler Boots, Battle Boots |
| Shields | offHand | 4 | Basic Shield, Reinforced Shield, Runic Shield, Mana Shield |
| Accessories | accessory1/2 | 11 | Copper Ring, Silver Ring, Gold Ring, Signet Ring, Copper Amulet, Silver Amulet, Crystal Pendant, Mana Brooch, Arcanist Pendant, Void-Touched Ring |

### Two-Handed Weapons
2H weapons (Basic Staff, Oak Staff, Arcanist Staff, Battlestaff) occupy both `mainHand` and `offHand`. The offhand slot is **blocked** when a 2H weapon is equipped.

### Equipment Instance Structure

```typescript
interface EquipmentInstance {
  instanceId:     string;
  typeId:         string;
  name:           string;
  enchantments:   AppliedEnchantment[];
  usedCapacity:   number;
  totalCapacity:  number;
  rarity:         'common' | 'uncommon' | 'rare' | 'epic' | 'legendary' | 'mythic';
  quality:        number;  // 0–100
}
```

### Enchantment Process (3 Stages)

#### Stage 1: Design
- Select effects from unlocked pool (`data/enchantments/`)
- Name the design, choose equipment type
- Time: 1h base + 0.5h per effect stack
- Dual design slot available with Enchant Mastery special
- 10% chance per tick for instant completion (Instant Designs special)
- Implemented in `crafting-design.ts` / `design-actions.ts`

#### Stage 2: Prepare
- Equipment must be equipped
- **Removes all existing enchantments** (confirmation dialog if enchanted)
- Mana cost: `totalCapacity × 10`
- Time: `2h + floor(totalCapacity / 50)` hours
- Auto-transitions to Meditate on complete
- **ONLY stage where explicit disenchanting is possible**
- Implemented in `crafting-prep.ts` / `preparation-actions.ts`

#### Stage 3: Apply
- Equipment must have "Ready for Enchantment" tag
- Select a saved design to apply
- Time: `2h + sum(stacks)` hours
- Mana per hour: `20 + 5 × sum(stacks)`
- Free enchant chances: Enchant Preservation (25%), Thrifty Enchanter (10%), Optimized Enchanting (25%)
- Pure Essence special: effects with base cost < 100 get 1.25× stacks
- Cannot re-enchant already enchanted gear (must Prepare first)
- Implemented in `crafting-apply.ts` / `application-actions.ts`

### Enchantment Effect Categories

| Category | File | Equipment Types | Example Effects |
|----------|------|-----------------|-----------------|
| **Mana** | `mana-effects.ts` | Most | `mana_cap_50`, `mana_regen_1`, `click_mana_1`, `{element}_cap_10/25/50` |
| **Combat** | `combat-effects.ts` | Casters, Hands | `damage_5`, `damage_10`, `damage_pct_10`, `crit_5`, `attack_speed_10` |
| **Elemental** | `elemental-effects.ts` | Casters, Swords | `sword_fire`, `sword_frost`, `sword_lightning`, `sword_void` |
| **Special** | `special-effects.ts` | Various | `spell_echo_10`, `guardian_dmg_10`, `overpower_80`, `first_strike`, `combo_master`, `adrenaline_rush` |
| **Utility** | `utility-effects.ts` | Most | `meditate_10`, `study_10`, `insight_5` |
| **Spell** | `spell-effects/` | Casters only | `manaBolt`, `fireball`, `inferno`, `pyroclasm`, `stellarNova`, etc. (~40+ spells) |
| **Defense** | `defense-effects.ts` | — | Placeholder (empty) |

### Capacity & Stacking
- Each equipment type has `baseCapacity` (15–80)
- Each enchantment effect has `baseCapacityCost` per stack
- **Stacking cost:** each additional stack costs 20% more: `cost × (1 + i × 0.2)` for stack index `i`
- Efficiency bonus reduces total cost: `totalCost × (1 - efficiencyBonus)`

### Disenchanting
- Only possible during **Prepare stage** (or via explicit disenchant action)
- Recovery rate: `0.1 + disenchantLevel × 0.2` (base 10% + 20% per level)
- Clears all enchantments, resets `usedCapacity` to 0

### Starting Equipment

| Slot | Item | Enchantment | Capacity |
|------|------|-------------|----------|
| Main Hand | Basic Staff (2H) | Mana Bolt spell | 50/50 |
| Body | Civilian Shirt | None | 0/30 |
| Feet | Civilian Shoes | None | 0/15 |

---

## Golemancy System

### Golem Slots

```
slots = floor(fabricatorLevel / 2)   [minimum 0]
Level 2: 1 slot
Level 4: 2 slots
Level 6: 3 slots
Level 8: 4 slots
Level 10: 5 slots
```

### Golem Types (10 Total)

#### Base Golems (1)

| Golem | Element | Damage | Speed | HP | Pierce | Unlock |
|-------|---------|--------|-------|----|--------|--------|
| Earth Golem | Earth | 8 | 1.5/s | 50 | 15% | Fabricator 2 |

#### Elemental Variant Golems (3)

| Golem | Element | Damage | Speed | HP | Pierce | Unlock |
|-------|---------|--------|-------|----|--------|--------|
| Steel Golem | Metal | 12 | 1.2/s | 60 | 35% | Metal mana unlocked |
| Crystal Golem | Crystal | 18 | 1.0/s | 40 | 25% | Crystal mana unlocked |
| Sand Golem | Sand | 6 | 2.0/s | 35 | 10% | Sand mana unlocked |

#### Hybrid Golems (6) — Require Enchanter 5 + Fabricator 5

| Golem | Elements | Damage | Speed | HP | Pierce | Special |
|-------|----------|--------|-------|----|--------|---------|
| Lava Golem | Earth + Fire | 15 | 1.0/s | 70 | 20% | AOE 2 |
| Galvanic Golem | Metal + Lightning | 10 | 3.5/s | 45 | 45% | Fast |
| Obsidian Golem | Earth + Dark | 25 | 0.8/s | 55 | 50% | High damage |
| Prism Golem | Crystal + Light | 20 | 1.5/s | 50 | 35% | AOE 3 |
| Quicksilver Golem | Metal + Water | 8 | 4.0/s | 40 | 30% | Very fast |
| Voidstone Golem | Earth + Void | 40 | 0.6/s | 100 | 60% | AOE 3, ultimate |

### Golem Combat

```
progressPerTick = HOURS_PER_TICK × attackSpeed × efficiencyBonus
damage = baseDamage × (1 + golemMasteryBonus)
```

Golems last `1 + golemLongevity` floors. Maintenance cost multiplier: `1 - (golemSiphon × 0.1)`.

---

## Prestige/Loop System

### Loop End Conditions

| Condition | Result |
|-----------|--------|
| Day 30 reached | Loop ends, gain insight |
| Floor 100 + Pact 100 signed | Victory! 3× insight |

### Insight Formula

```
skillBonus = 1 + (insightHarvest × 0.1) + disciplineInsightBonus
boonInsightMult = 1 + boonInsightGain / 100
mult = (1 + insightAmp × 0.25) × skillBonus × boonInsightMult

baseInsight = floor(maxFloorReached × 15 + totalManaGathered / 500 + signedPacts.length × 150 + prestigeInsightBonus)
finalInsight = floor(baseInsight × mult)
```

Victory bonus: ×3 if maxFloorReached ≥ 100 AND floor 100 guardian pact is signed.

### Prestige Upgrades (14 Types)

| ID | Name | Description | Max Level | Cost |
|----|------|-------------|-----------|------|
| `manaWell` | Mana Well | +500 starting max mana | 5 | 500 |
| `manaFlow` | Mana Flow | +0.5 regen/sec permanently | 10 | 750 |
| `insightAmp` | Insight Amp | +25% insight gain | 4 | 1500 |
| `spireKey` | Spire Key | Start at floor +2 | 5 | 4000 |
| `temporalEcho` | Temporal Echo | +10% mana generation | 5 | 3000 |
| `steadyHand` | Steady Hand | -15% durability loss | 5 | 1200 |
| `ancientKnowledge` | Ancient Knowledge | Start with blueprint discovered | 5 | 2000 |
| `elementalAttune` | Elemental Attunement | +25 elemental mana cap | 10 | 600 |
| `spellMemory` | Spell Memory | Start with random spell learned | 3 | 2500 |
| `guardianPact` | Guardian Pact | +10% pact multiplier | 5 | 3500 |
| `quickStart` | Quick Start | Start with 100 raw mana | 3 | 400 |
| `elemStart` | Elem. Start | Start with 5 of each unlocked element | 3 | 800 |
| `unlockedManaTypeCapacity` | Mana Type Capacity | +10 capacity for selected mana type | 5 | 1000 |

### Pact Persistence
- Signed pacts persist through prestige (bounded by `pactSlots`)
- `pactSlots` starting value: 1 (upgradeable)

---

## Achievement System

### Categories (24 Total)

| Category | Count | Examples |
|----------|-------|---------|
| **Combat** (9) | First Blood (floor 2), Floor Climber (10), Spire Assault (25), Tower Conqueror (50), Spire Master (75), Apex Reached (100), Heavy Hitter (100 dmg), Devastating Blow (1K dmg), Apocalypse Now (10K dmg) |
| **Progression** (3) | Pact Seeker (1 pact), Pact Collector (5), Pact Master (9) |
| **Magic** (6) | Spell Caster/Weaver/Storm (100/1K/10K spells), Mana Pool/Lake/Ocean (1K/100K/10M mana) |
| **Crafting** (3) | Enchanter (1 craft), Master Enchanter (10), Legendary Enchanter (50) |
| **Special** (3) | Speed Runner (floor 50 < 5 days, hidden), Perfectionist (floor 100 no pacts, hidden), Survivor (loop during full incursion day 30+) |

### Reward Types

| Reward | Effect |
|--------|--------|
| `insight` | One-time insight bonus (10–1000) |
| `manaBonus` | Permanent max mana (10–200) |
| `damageBonus` | Permanent damage increase (3%–25%) |
| `regenBonus` | Permanent regen increase (0.5–1) |
| `title` | Cosmetic title |
| `unlockEffect` | Unlocks game effect |

### Hidden Achievements
- 2 hidden achievements: Speed Runner and Perfectionist
- Revealed when player reaches 50% progress toward requirement

---

## Formulas & Calculations

### Damage Calculation (Complete)

```
baseDmg = spell.dmg + disciplineBaseDmgBonus
pctMult = 1 + disciplineDmgMult
elemMasteryMult = 1 + (elementalMastery × 0.15)
guardianBaneMult = 1 + (guardianBane × 0.2)  [guardian floors only]
rawDmgMult = 1 + boonRawDamage / 100
elemDmgMult = 1 + boonElementalDamage / 100

damage = baseDmg × pctMult × elemMasteryMult × guardianBaneMult × rawDmgMult × elemDmgMult
damage *= getElementalBonus(spellElement, floorElement)

// Critical hit
critChance = disciplineCritChance + boonCritChance / 100
critDmgMult = 1.5 + boonCritDamage / 100
if (random() < critChance) damage *= critDmgMult

// Special modifiers
if (floorHP / floorMaxHP < 0.25) damage *= 2    // Executioner
if (rawMana < maxMana × 0.5) damage *= 1.5      // Berserker

// Armor reduction
effectiveArmor = max(0, enemyArmor - armorPierce)
damage *= (1 - effectiveArmor)

return floor(damage)
```

### DPS Calculation

```
dps = damage × castSpeed × attackSpeedMultiplier
```

### Elemental Bonus Lookup

```
getElementalBonus(spellElement, floorElement):
  if spell == floor: return 1.25 (same element)
  if spell opposes floor: return 1.50 (super effective)
  if floor opposes spell: return 0.75 (not very effective)
  return 1.00 (neutral)
```

---

## System Interactions

### Primary Interaction Map

```
┌─────────────────────────────────────────────────────────────────────────┐
│                         CORE SYSTEM INTERACTIONS                         │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                          │
│  ┌──────────┐        ┌────────────┐        ┌──────────┐                │
│  │   MANA   │───────▶│ DISCIPLINES│───────▶│  COMBAT  │                │
│  └──────────┘        └────────────┘        └──────────┘                │
│       │                    │                    │                       │
│       │                    │                    │                       │
│       ▼                    ▼                    ▼                       │
│  ┌──────────┐        ┌──────────┐         ┌──────────┐                │
│  │ATTUNEMENT│───────▶│ENCHANTING│────────▶│  SPIRE   │                │
│  └──────────┘        └──────────┘         └──────────┘                │
│       │                    │                    │                       │
│       │                    │                    │                       │
│       ▼                    ▼                    ▼                       │
│  ┌──────────┐        ┌──────────┐         ┌──────────┐                │
│  │GOLEMANCY │        │EQUIPMENT │────────▶│ GUARDIAN │                │
│  └──────────┘        └──────────┘         └──────────┘                │
│                                                 │                       │
│                                                 ▼                       │
│                                          ┌──────────┐                  │
│                                          │   PACT   │                  │
│                                          └──────────┘                  │
│                                                 │                       │
│                                                 ▼                       │
│                                          ┌──────────┐                  │
│                                          │ PRESTIGE │                  │
│                                          └──────────┘                  │
└─────────────────────────────────────────────────────────────────────────┘
```

### Key System Dependencies

| System | Depends On | Unlocks/Enables |
|--------|------------|-----------------|
| **Disciplines** | Mana (drain cost), Attunement (pool access) | All combat/crafting stat bonuses |
| **Enchanting** | Enchanter attunement, Enchanter disciplines | Equipment spells, bonuses |
| **Golemancy** | Fabricator attunement, Earth mana | Additional combat damage |
| **Pacts** | Guardian defeat | Permanent multipliers, boons |
| **Prestige** | Loop completion | Permanent upgrades, pact persistence |
| **Equipment** | Crafting/Blueprints | Spell access, stat bonuses |

### Progression Gates

1. **Early Game (Floors 1–10):** Mana gathering and regen, base disciplines, starting equipment
2. **Mid Game (Floors 10–40):** First guardian pacts, attunement unlocking, attunement discipline pools, equipment enchanting, Golemancy
3. **Late Game (Floors 40–140):** Compound/exotic elements, hybrid golems, advanced discipline perks, advanced enchantments, all guardian tiers
4. **End Game (Floors 150+):** Combination bosses with dual elements, indefinite scaling

---

## Code Architecture

### Modular Structure Overview

#### Store Architecture (7 Zustand Stores)

**Active Stores (`src/lib/game/stores/`):**
- **gameStore.ts** — Coordinator/tick pipeline, combines all stores
- **manaStore.ts** — Mana pools, regen, element conversion
- **combatStore.ts** — Spire/floors, combat, spells, achievements
- **craftingStore.ts** — Enchanting (Design/Prepare/Apply), equipment instances, loot
- **attunementStore.ts** — Enchanter/Invoker/Fabricator attunement levels & XP
- **prestigeStore.ts** — Insight, prestige upgrades, pact persistence, loop state
- **discipline-slice.ts** — Discipline activation, XP ticking, perk evaluation
- **uiStore.ts** — Logs, pause, game over/victory flags

**Supporting store files:**
- `tick-pipeline.ts` — `buildTickContext()` / `applyTickWrites()` pattern
- `combat-actions.ts` — Combat tick processing
- `gameLoopActions.ts` — Climb/spire actions
- `gameHooks.ts` — React hooks bound to stores
- `craftingStore.types.ts` — Crafting type definitions
- `crafting-initial-state.ts` — Default crafting state
- `combat-state.types.ts` — Combat type definitions

**No legacy store files remain.** The old `store.ts`, `store/`, and `store-modules/` directories have been fully removed.

#### Data Layer (`src/lib/game/data/`)
- `disciplines/` — 11 files: per-attunement discipline definitions (34 disciplines total)
- `enchantments/` — 7 files + `spell-effects/` subdirectory: enchantment effects by category
- `equipment/` — 13 files: equipment type definitions by slot
- `golems/` — 7 files: golem definitions (base, elemental, hybrid)
- `guardian-data.ts` — Static guardian definitions (floors 10–140)
- `guardian-encounters.ts` — Procedural guardian lookup & combo bosses (150+)
- `attunements.ts` — Attunement definitions
- `achievements.ts` — Achievement definitions (24 achievements)
- `crafting-recipes.ts` / `fabricator-recipes.ts` — Crafting recipes
- `loot-drops.ts` — Loot drop tables
- `enchantment-effects.ts` / `enchantment-types.ts` — Enchantment metadata

#### Constants (`src/lib/game/constants/`)
- `core.ts` — Tick rate, caps, time constants
- `elements.ts` — Element definitions, opposites, floor cycle
- `prestige.ts` — Prestige upgrade definitions
- `rooms.ts` — Room type configs (armor, speed, swarm, puzzle)
- `spells.ts` — Spell constants barrel
- `spells-modules/` — 10 files: spell definitions by category (raw, basic, advanced, master, legendary, lightning, compound, AOE, utility, enchantment)

#### Types (`src/lib/game/types/`)
- `game.ts` — Core game types (GameState, ActivityLogEntry, etc.)
- `disciplines.ts` — Discipline definition types
- `attunements.ts` — Attunement types
- `equipment.ts` — Equipment instance types
- `equipmentSlot.ts` — Equipment slot enum
- `elements.ts` — Element type definitions
- `spells.ts` — Spell types

#### Utilities (`src/lib/game/utils/`)
- `combat-utils.ts` — Damage calculation, elemental bonuses, insight formula
- `spire-utils.ts` — Spire/floor progression
- `mana-utils.ts` — Mana calculation helpers
- `enemy-generator.ts` — Enemy spawning with modifiers
- `discipline-math.ts` — Discipline XP/drain/perk formulas
- `room-utils.ts` — Room type generation
- `enemy-utils.ts` — Enemy stat calculations
- `pact-utils.ts` — Guardian pact helpers
- `floor-utils.ts` — Floor HP calculations
- `formatting.ts` — Number/time formatting
- `activity-log.ts` — Activity log helper
- `result.ts` — Result/Either type
- `safe-persist.ts` — Safe localStorage persistence

#### Effects (`src/lib/game/effects/`)
- `discipline-effects.ts` — Discipline → stat bonuses/multipliers/specials
- `dynamic-compute.ts` — Dynamic stat computation
- `special-effects.ts` — Special one-off effects
- `upgrade-effects.ts` — Upgrade effect application
- `upgrade-effects.types.ts` — Types for upgrade effects

#### Top-Level Game Logic (`src/lib/game/`)
- `effects.ts` — Unified effects orchestration (merges equipment + discipline + upgrade effects)
- `crafting-design.ts` — Enchantment design logic
- `crafting-prep.ts` — Preparation logic
- `crafting-apply.ts` — Application logic
- `crafting-equipment.ts` — Equipment crafting logic
- `crafting-loot.ts` — Loot generation from crafting
- `crafting-utils.ts` — Shared crafting utilities
- `crafting-attunements.ts` — Attunement-crafting integration

#### Crafting Actions (`src/lib/game/crafting-actions/`)
- `design-actions.ts` — Design stage actions
- `preparation-actions.ts` — Preparation stage actions
- `application-actions.ts` — Application stage actions
- `crafting-equipment-actions.ts` — Equipment crafting actions
- `equipment-actions.ts` — Equipment management (equip/unequip/delete)
- `disenchant-actions.ts` — Disenchant/salvage actions
- `computed-getters.ts` — Derived crafting state

#### UI Components (`src/components/game/`)

**Tabs (14 tabs):**
- `SpireSummaryTab.tsx` — Spire overview/progress (largest tab)
- `DisciplinesTab.tsx` — Discipline management
- `GolemancyTab.tsx` — Golem summoning/management
- `PrestigeTab.tsx` — Prestige/insight upgrades
- `CraftingTab.tsx` — Crafting wrapper (with EnchanterSubTab, FabricatorSubTab)
- `EquipmentTab.tsx` — Equipment management
- `GuardianPactsTab.tsx` — Guardian pact signing
- `SpellsTab.tsx` — Spell management
- `AttunementsTab.tsx` — Attunement management
- `AchievementsTab.tsx` — Achievement viewer
- `StatsTab.tsx` — Player statistics
- `DebugTab.tsx` — Debug tools (8 sections)
- `SpireCombatPage/` — In-combat UI (7 files)
- `ActivityLog.tsx` — Activity log display

**Shared Components:**
- `ManaDisplay.tsx`, `ActionButtons.tsx`, `TimeDisplay.tsx`
- `AttunementStatus.tsx`, `GameToast.tsx`, `UpgradeDialog.tsx`
- `crafting/` — EnchantmentDesigner, EnchantmentPreparer, EnchantmentApplier, EquipmentCrafter
- `debug/` — Debug components for each system
- `LootInventory/` — Loot/blueprint/materials UI

### Persistence
- All state persisted to **localStorage** via Zustand `persist` middleware
- No backend, no database, no Prisma
- Store keys: `mana-loop-crafting`, `mana-loop-ui-storage`, etc.

### File Size Guidelines
All files kept under **400 lines** (enforced by pre-commit hook).

---

## Appendix: Removed Systems

The following systems no longer exist and should not be re-introduced:

| Removed | Replacement |
|---------|-------------|
| Skill System (study, tiers T1–T5, milestone upgrades) | Discipline System |
| `skillStore.ts` / `store.ts` / `store-modules/` | Modular Zustand stores in `stores/` |
| `skill-evolution-modules/` | `data/disciplines/` + `discipline-math.ts` |
| `docs/skills.md` | This document (Discipline System section) |
| `docs/strategy/` | Fully implemented; folder removed |
| Ascension skills | Deleted (no replacement) |
| Scroll crafting | Deleted (violates no-instant-finishing pillar) |
| Lifesteal/healing | Banned permanently |
| Familiar System | Replaced by Golemancy and Pact systems |
| Legacy static guardians (named Primordialis, The Awakened One) | Procedural guardian system with 4 tiers |
| Prisma / database | Removed; localStorage-only persistence |

---

*Document Version: 3.0 — Post-Refactoring Update*
*End of Game Briefing Document*
