# Combat Resolution System Design

**Document Version:** 1.0.0 **Game Mode:** The Veil War (Mode 1) **Design
Date:** December 2024 **Status:** Initial Design

---

## Overview

The Combat Resolution System extends the core Echo Dice mechanics for
multi-planar strategic warfare in The Veil War. Combat can occur simultaneously
across Material, Resonance, and Void planes, with distinct modifiers, resolution
rules, and cross-plane interactions.

**Design Principles:**

1. **Plane Distinction:** Each plane has unique combat modifiers and resolution
   rules
2. **Cross-Plane Synergy:** Controlling multiple planes grants stacking bonuses
   in combat
3. **Echo Dice Foundation:** All combat uses the Echo Dice system with
   plane-specific extensions
4. **Army Composition Matters:** Mixed forces with complementary units
   outperform homogeneous armies
5. **Tactical Depth:** Retreat, terrain, flanking, and siege mechanics create
   meaningful choices
6. **Weave Integration:** All significant combat outcomes are logged for
   narrative memory

**Research Sources:**

- Board Game Designers Forum discussions on combat mechanics
- SGS stacking point leadership systems
- Multi-domain warfare modeling principles
- Cry Havoc asymmetric combat resolution
- Root-style faction balance approaches

---

## 1. Multi-Plane Echo Dice Combat

The Echo Dice system is extended with plane-specific modifiers that affect dice
pools, success thresholds, and special effects.

### 1.1 Plane-Specific Dice Modifiers

**Material Plane Combat:** The Material Plane favors conventional military
strength - numbers, equipment, and fortifications matter most.

| Modifier Source   | Dice Effect                        | Condition                   |
| ----------------- | ---------------------------------- | --------------------------- |
| Superior Numbers  | +1 die per 25% strength advantage  | Attacker/Defender           |
| Fortification     | +1 to +8 defense dice              | Defender in fort            |
| Supply Status     | -1 die if foraging, -2 if starving | Affected units              |
| High Ground       | +1 attack die                      | Elevated position           |
| Flanking          | +2 dice                            | Attacked from 2+ directions |
| Commander Present | +1 to +3 dice                      | Based on commander rating   |

```typescript
interface MaterialCombatModifiers {
  strengthRatio: number; // 0.5 = 2:1 disadvantage, 2.0 = 2:1 advantage
  fortificationBonus: number; // 0-8 based on fortification type
  supplyPenalty: number; // 0, -1, or -2
  terrainModifier: number; // -2 to +2 based on terrain
  flankingBonus: number; // 0, +2, or +4 (surrounded)
  commanderBonus: number; // 0-3 based on commander
}

function calculateMaterialDicePool(
  basePool: number,
  modifiers: MaterialCombatModifiers
): number {
  let pool = basePool;

  // Strength ratio bonus (capped at +4)
  const strengthBonus = Math.min(
    4,
    Math.floor((modifiers.strengthRatio - 1) * 4)
  );
  pool += Math.max(-4, strengthBonus);

  // Defense-specific (only for defender)
  pool += modifiers.fortificationBonus;

  // Universal modifiers
  pool += modifiers.supplyPenalty;
  pool += modifiers.terrainModifier;
  pool += modifiers.flankingBonus;
  pool += modifiers.commanderBonus;

  return Math.max(1, pool); // Minimum 1 die
}
```

**Resonance Plane Combat:** The Resonance Plane favors magical prowess - ley
line connections, power nodes, and Veil manipulation dominate.

| Modifier Source       | Dice Effect                            | Condition                   |
| --------------------- | -------------------------------------- | --------------------------- |
| Ley Line Connection   | +1 die per active ley line             | Connected territory         |
| Power Node Control    | +2 dice                                | Controlling power node      |
| Resonance Superiority | +1 die per 2 Resonance level advantage | Based on attacker Resonance |
| Veil Density          | +1 to +3 dice                          | High Veil areas             |
| Essence Expenditure   | +1 die per 5 Essence spent             | Active choice               |
| Arcane Disruption     | -2 dice                                | Under arcane interference   |

```typescript
interface ResonanceCombatModifiers {
  leyLineCount: number; // Number of connected ley lines
  powerNodeBonus: number; // +2 if controlling power node
  resonanceAdvantage: number; // Resonance level difference / 2
  veilDensityBonus: number; // 0-3 based on local Veil strength
  essenceExpended: number; // Essence spent for bonus
  arcaneDisruption: boolean; // Under disruption effect
}

function calculateResonanceDicePool(
  basePool: number,
  modifiers: ResonanceCombatModifiers
): number {
  let pool = basePool;

  // Ley line bonus (capped at +4)
  pool += Math.min(4, modifiers.leyLineCount);

  // Power node control
  pool += modifiers.powerNodeBonus;

  // Resonance level advantage
  pool += Math.floor(modifiers.resonanceAdvantage);

  // Veil density
  pool += modifiers.veilDensityBonus;

  // Essence expenditure (capped at +4)
  pool += Math.min(4, Math.floor(modifiers.essenceExpended / 5));

  // Arcane disruption
  if (modifiers.arcaneDisruption) {
    pool -= 2;
  }

  return Math.max(1, pool);
}
```

**Void Plane Combat:** The Void Plane is chaotic and unpredictable - entropy,
corruption, and hidden strikes dominate.

| Modifier Source      | Dice Effect                        | Condition                     |
| -------------------- | ---------------------------------- | ----------------------------- |
| Entropy Level        | +1 die per entropy level (max +4)  | High entropy territory        |
| Corruption Alignment | +2 dice if aligned with corruption | Void-aligned factions         |
| Shadow Concealment   | +3 dice for ambush                 | Attacking from Hidden Passage |
| Void Instability     | -1 to +2 dice (random)             | All Void combat               |
| Paradox Presence     | Echoes become wild                 | Near paradox wells            |
| Reality Anchor       | -3 dice penalty                    | Void-resistant effects        |

```typescript
interface VoidCombatModifiers {
  entropyLevel: number; // 0-5 local entropy
  corruptionAlignment: boolean; // True for Void-aligned factions
  ambushBonus: number; // +3 if attacking from Hidden Passage
  instabilityRoll: number; // -1 to +2 random each combat
  paradoxPresence: boolean; // Wild Echo effects
  realityAnchorPenalty: number; // 0 or -3 if anchored
}

function calculateVoidDicePool(
  basePool: number,
  modifiers: VoidCombatModifiers
): number {
  let pool = basePool;

  // Entropy bonus (capped at +4)
  pool += Math.min(4, modifiers.entropyLevel);

  // Corruption alignment
  if (modifiers.corruptionAlignment) {
    pool += 2;
  }

  // Ambush from Hidden Passage
  pool += modifiers.ambushBonus;

  // Random instability (-1 to +2)
  pool += modifiers.instabilityRoll;

  // Reality Anchor penalty
  pool += modifiers.realityAnchorPenalty;

  return Math.max(1, pool);
}

function rollVoidInstability(): number {
  // -1 to +2 distribution: 25% each
  const roll = Math.floor(Math.random() * 4) - 1;
  return roll;
}
```

### 1.2 Cross-Plane Attack Resolution

Cross-plane attacks allow units on one plane to strike targets on another, but
with significant penalties and restrictions.

**Cross-Plane Attack Matrix:**

| Attacker Plane       | Target Plane | Base Penalty                            | Requirements |
| -------------------- | ------------ | --------------------------------------- | ------------ |
| Material → Resonance | -3 dice      | Arcane ammunition or Veil-touched unit  |
| Material → Void      | -4 dice      | Void-touched unit or special equipment  |
| Resonance → Material | -2 dice      | Spell with Material effect              |
| Resonance → Void     | -2 dice      | Void-attuned caster                     |
| Void → Material      | -3 dice      | Manifest ability or corrupted territory |
| Void → Resonance     | -1 dice      | Natural affinity                        |

**Cross-Plane Attack Types:**

```typescript
type CrossPlaneAttackType =
  | 'veil_strike' // Resonance → Material: Magical attack on physical targets
  | 'void_eruption' // Void → Material: Corruption damage burst
  | 'reality_anchor' // Material → Void: Stabilizing strike
  | 'arcane_disruption' // Resonance → Void: Counter-entropy spell
  | 'material_shatter' // Void → Resonance: Break ley line connections
  | 'sanctified_strike'; // Material → Resonance: Anti-magic attack

interface CrossPlaneAttack {
  attackType: CrossPlaneAttackType;
  sourcePlane: PlaneType;
  targetPlane: PlaneType;

  // Resolution
  baseDicePenalty: number;
  requirements: CrossPlaneRequirement[];

  // Effects on success
  primaryDamage: number;
  secondaryEffects: CrossPlaneEffect[];

  // Costs
  veilPointCost: number;
  essenceCost: number;
  entropyCost: number;
}

interface CrossPlaneEffect {
  effectType:
    | 'damage'
    | 'disruption'
    | 'corruption'
    | 'stabilization'
    | 'severance';
  magnitude: number;
  duration: number;
  targetType: 'units' | 'territory' | 'ley_line' | 'power_node';
}
```

**Cross-Plane Resolution Flow:**

```typescript
function resolveCrossPlaneAttack(
  attacker: Army | MagicalEntity,
  target: Army | Territory | LeyLine,
  attack: CrossPlaneAttack,
  gameState: GameState
): CrossPlaneCombatResult {
  // 1. Verify requirements
  const requirementsMet = verifyRequirements(attacker, attack.requirements);
  if (!requirementsMet.success) {
    return { success: false, reason: requirementsMet.reason };
  }

  // 2. Pay costs
  const costsResult = payCrossPlaneCosts(attacker.owner, attack, gameState);
  if (!costsResult.paid) {
    return { success: false, reason: 'Insufficient resources' };
  }

  // 3. Calculate attacker dice pool
  let attackPool = getBaseAttackPool(attacker);
  attackPool = applyPlaneModifiers(
    attackPool,
    attack.sourcePlane,
    attacker,
    gameState
  );
  attackPool -= attack.baseDicePenalty;

  // 4. Calculate defender dice pool
  let defensePool = getBaseDefensePool(target);
  defensePool = applyPlaneModifiers(
    defensePool,
    attack.targetPlane,
    target,
    gameState
  );

  // 5. Roll Echo Dice
  const attackRoll = performRoll(Math.max(1, attackPool));
  const defenseRoll = performRoll(Math.max(1, defensePool));

  // 6. Compare results
  const netSuccesses = attackRoll.netSuccesses - defenseRoll.netSuccesses;

  // 7. Apply damage and effects
  const result: CrossPlaneCombatResult = {
    success: netSuccesses > 0,
    netSuccesses,
    attackerRoll: attackRoll,
    defenderRoll: defenseRoll,
    damageDealt: 0,
    effectsApplied: [],
    weaveEntry: null,
  };

  if (netSuccesses > 0) {
    result.damageDealt = attack.primaryDamage + netSuccesses;
    result.effectsApplied = applyCrossPlaneEffects(
      attack.secondaryEffects,
      target,
      netSuccesses
    );
  }

  // 8. Generate Weave entry for significant outcomes
  if (Math.abs(netSuccesses) >= 3 || result.effectsApplied.length > 0) {
    result.weaveEntry = generateCombatWeaveEntry(attacker, target, result);
  }

  return result;
}
```

### 1.3 Synergy Chain Combat Bonuses

When a player controls a territory on multiple planes, their combat forces gain
stacking bonuses.

**Dual-Plane Control Bonuses:**

| Planes Controlled    | Combat Bonus | Special Effect                          |
| -------------------- | ------------ | --------------------------------------- |
| Material + Resonance | +2 dice      | Veil-strikes cost 50% less              |
| Material + Void      | +2 dice      | Immune to corruption spread from combat |
| Resonance + Void     | +2 dice      | Shadows grant +1 success (not just VP)  |

**Full Dominion Combat Bonuses:**

| Bonus Type         | Effect                                | Condition                              |
| ------------------ | ------------------------------------- | -------------------------------------- |
| Tri-Planar Strike  | +4 dice to all attacks                | Attacking from Full Dominion territory |
| Reality Lock       | Cannot be cross-plane attacked        | Defending Full Dominion                |
| Echo Amplification | Echoes roll 2 dice instead of 1       | All combat in Full Dominion            |
| Shadow Immunity    | Shadows do not generate complications | Defending Full Dominion                |

```typescript
interface SynergyChainBonus {
  planesControlled: PlaneType[];
  diceBonus: number;
  specialEffect: SynergySpecialEffect | null;
}

interface FullDominionCombatBonus {
  triPlanarStrikeBonus: number; // +4 dice
  realityLockImmunity: boolean; // Cannot be cross-plane attacked
  echoAmplification: boolean; // Echoes roll 2 dice
  shadowImmunity: boolean; // No shadow complications
}

function calculateSynergyBonus(
  territory: TerritoryState,
  attackingPlayer: PlayerId
): SynergyChainBonus {
  const controlledPlanes: PlaneType[] = [];

  if (territory.material.controller === attackingPlayer) {
    controlledPlanes.push('material');
  }
  if (territory.resonance.controller === attackingPlayer) {
    controlledPlanes.push('resonance');
  }
  if (territory.void_.controller === attackingPlayer) {
    controlledPlanes.push('void');
  }

  // No bonus for single plane
  if (controlledPlanes.length <= 1) {
    return {
      planesControlled: controlledPlanes,
      diceBonus: 0,
      specialEffect: null,
    };
  }

  // Dual plane bonus: +2 dice
  if (controlledPlanes.length === 2) {
    const specialEffect = getDualPlaneSpecialEffect(controlledPlanes);
    return { planesControlled: controlledPlanes, diceBonus: 2, specialEffect };
  }

  // Full Dominion: +4 dice + special
  return {
    planesControlled: controlledPlanes,
    diceBonus: 4,
    specialEffect: { type: 'full_dominion' },
  };
}

function applyEchoAmplification(
  roll: DiceResultBreakdown,
  hasFullDominion: boolean,
  randomFn: () => number
): DiceResultBreakdown {
  if (!hasFullDominion) return roll;

  // Each Echo rolls 2 additional dice instead of 1
  const amplifiedEchoChain: number[] = [];
  let echoesToProcess = roll.echoes;
  let safetyCounter = 0;

  while (echoesToProcess > 0 && safetyCounter < 200) {
    // Roll 2 dice per Echo instead of 1
    const newRolls = rollPool(echoesToProcess * 2, randomFn);
    amplifiedEchoChain.push(...newRolls);
    echoesToProcess = countEchoes(newRolls);
    safetyCounter += newRolls.length;
  }

  const allResults = [...roll.results, ...amplifiedEchoChain];

  return {
    ...roll,
    echoChain: amplifiedEchoChain,
    successes: countSuccesses(allResults),
    shadows: countShadows(allResults),
    netSuccesses: countSuccesses(allResults),
    veilPointsGained: countShadows(allResults),
  };
}
```

---

## 2. Unit Stacking and Army Composition

The Veil War uses a leadership-based stacking system where commanders can only
effectively control a limited number of units, and army composition creates
meaningful strategic choices.

### 2.1 Maximum Units Per Territory Per Plane

**Material Plane Stacking:**

| Territory Type | Base Capacity | With Fortification | Notes                   |
| -------------- | ------------- | ------------------ | ----------------------- |
| Heartland      | 12 units      | +4 per fort level  | High population centers |
| Borderland     | 8 units       | +3 per fort level  | Strategic chokepoints   |
| Wasteland      | 6 units       | +2 per fort level  | Sparse terrain          |
| Sacred Site    | 4 units       | No fortifications  | Cross-plane focus       |
| Nexus          | 10 units      | +3 per fort level  | Critical locations      |

**Resonance Plane Stacking:**

| Territory Type | Entity Capacity | With Power Node     | Notes               |
| -------------- | --------------- | ------------------- | ------------------- |
| Standard       | 6 entities      | +3 with active node | Magical beings      |
| Ley Nexus      | 10 entities     | +5 with active node | Power concentration |
| Veil Thin Zone | 8 entities      | +4 with active node | Reality weakened    |
| Void-Touched   | 4 entities      | Cannot build nodes  | Corrupted areas     |

**Void Plane Stacking:**

| Territory Type | Shadow Capacity | With Entropy | Notes               |
| -------------- | --------------- | ------------ | ------------------- |
| Low Entropy    | 4 shadows       | -            | Stable reality      |
| Medium Entropy | 6 shadows       | +2           | Growing instability |
| High Entropy   | 8 shadows       | +4           | Near collapse       |
| Paradox Zone   | 10 shadows      | +6           | Reality fractured   |

```typescript
interface StackingLimits {
  territory: TerritoryId;

  material: {
    baseCapacity: number;
    fortificationBonus: number;
    currentUnits: number;
    overStackPenalty: number;
  };

  resonance: {
    baseCapacity: number;
    powerNodeBonus: number;
    currentEntities: number;
    overStackPenalty: number;
  };

  void_: {
    baseCapacity: number;
    entropyBonus: number;
    currentShadows: number;
    overStackPenalty: number;
  };
}

function calculateOverStackPenalty(
  currentUnits: number,
  capacity: number
): number {
  if (currentUnits <= capacity) return 0;

  const excessUnits = currentUnits - capacity;
  // -1 to morale and combat per 2 units over capacity
  return Math.ceil(excessUnits / 2);
}

function validateArmyPlacement(
  army: Army[],
  territory: TerritoryState,
  plane: PlaneType
): PlacementValidation {
  const limits = getStackingLimits(territory, plane);
  const totalStrength = army.reduce(
    (sum, unit) => sum + getUnitStackValue(unit),
    0
  );
  const capacity = limits.baseCapacity + limits.fortificationBonus;

  return {
    valid: totalStrength <= capacity,
    currentLoad: totalStrength,
    capacity,
    overStackPenalty: calculateOverStackPenalty(totalStrength, capacity),
    warnings:
      totalStrength > capacity * 0.8 ? ['Army approaching stacking limit'] : [],
  };
}
```

### 2.2 Army Composition Bonuses

Mixed armies with complementary unit types gain combat bonuses.

**Composition Categories:**

| Category | Unit Types                           | Role                 |
| -------- | ------------------------------------ | -------------------- |
| Core     | Militia, Regulars, Veterans          | Line holding         |
| Elite    | Elite Guard, Bastion Lords           | Decisive strikes     |
| Mobile   | Scouts, Light Cavalry, Heavy Cavalry | Flanking, pursuit    |
| Support  | Engineers, War Machines              | Siege, fortification |
| Magical  | Veil-Touched, Resonance Entities     | Cross-plane combat   |
| Shadow   | Void Agents, Shadow Infiltrators     | Void operations      |

**Mixed Resonance Bonuses:**

When an army contains units from multiple Resonance affinities, they gain
synergy bonuses:

| Combination     | Bonus                     | Thematic Reasoning          |
| --------------- | ------------------------- | --------------------------- |
| Clarity + Flow  | +1 die to all attacks     | Perfect coordination        |
| Flow + Presence | +1 defense die            | Inspiring adaptability      |
| Presence + Root | +1 morale                 | Unshakeable resolve         |
| Root + Void     | +1 die vs magical attacks | Grounded against chaos      |
| Void + Clarity  | +1 die to ambush          | Mystery reveals opportunity |

```typescript
interface ArmyComposition {
  armyId: string;
  units: Army[];

  // Category counts
  coreCount: number;
  eliteCount: number;
  mobileCount: number;
  supportCount: number;
  magicalCount: number;
  shadowCount: number;

  // Resonance mix
  resonanceMix: Map<ResonanceType, number>;

  // Calculated bonuses
  compositionBonus: CompositionBonus;
}

interface CompositionBonus {
  attackDice: number;
  defenseDice: number;
  moralBonus: number;
  specialAbilities: string[];
}

function calculateCompositionBonus(
  composition: ArmyComposition
): CompositionBonus {
  const bonus: CompositionBonus = {
    attackDice: 0,
    defenseDice: 0,
    moralBonus: 0,
    specialAbilities: [],
  };

  // Balanced army bonus (at least 2 units in 3+ categories)
  const categoriesWithUnits = [
    composition.coreCount >= 2,
    composition.eliteCount >= 1,
    composition.mobileCount >= 2,
    composition.supportCount >= 1,
    composition.magicalCount >= 1,
    composition.shadowCount >= 1,
  ].filter(Boolean).length;

  if (categoriesWithUnits >= 3) {
    bonus.attackDice += 1;
    bonus.defenseDice += 1;
    bonus.specialAbilities.push('Combined Arms');
  }

  // Heavy core bonus (4+ core units)
  if (composition.coreCount >= 4) {
    bonus.defenseDice += 1;
    bonus.moralBonus += 5;
    bonus.specialAbilities.push('Steadfast Line');
  }

  // Mobile strike bonus (3+ mobile units)
  if (composition.mobileCount >= 3) {
    bonus.attackDice += 1;
    bonus.specialAbilities.push('Swift Strike');
  }

  // Magical support bonus (2+ magical units)
  if (composition.magicalCount >= 2) {
    bonus.attackDice += 1;
    bonus.specialAbilities.push('Veil Support');
  }

  // Resonance synergy bonuses
  const resonanceTypes = Array.from(composition.resonanceMix.keys());
  for (const synergy of RESONANCE_SYNERGIES) {
    if (
      resonanceTypes.includes(synergy.primary) &&
      resonanceTypes.includes(synergy.secondary)
    ) {
      bonus.attackDice += synergy.attackBonus;
      bonus.defenseDice += synergy.defenseBonus;
      bonus.moralBonus += synergy.moraleBonus;
      bonus.specialAbilities.push(synergy.name);
    }
  }

  return bonus;
}

const RESONANCE_SYNERGIES: ResonanceSynergy[] = [
  {
    primary: 'clarity',
    secondary: 'flow',
    attackBonus: 1,
    defenseBonus: 0,
    moraleBonus: 0,
    name: 'Perfect Coordination',
  },
  {
    primary: 'flow',
    secondary: 'presence',
    attackBonus: 0,
    defenseBonus: 1,
    moraleBonus: 0,
    name: 'Inspiring Adaptability',
  },
  {
    primary: 'presence',
    secondary: 'root',
    attackBonus: 0,
    defenseBonus: 0,
    moraleBonus: 10,
    name: 'Unshakeable Resolve',
  },
  {
    primary: 'root',
    secondary: 'void',
    attackBonus: 1,
    defenseBonus: 0,
    moraleBonus: 0,
    name: 'Grounded Mystery',
  },
  {
    primary: 'void',
    secondary: 'clarity',
    attackBonus: 1,
    defenseBonus: 0,
    moraleBonus: 0,
    name: 'Revealed Opportunity',
  },
];
```

### 2.3 Elite Unit Caps and Legendary Restrictions

To prevent armies from becoming homogeneous blobs of elite units, the system
enforces caps.

**Elite Unit Caps:**

| Unit Tier | Max Per Army | Max Per Player | Notes                     |
| --------- | ------------ | -------------- | ------------------------- |
| Standard  | Unlimited    | Unlimited      | Basic units               |
| Veteran   | 6 per army   | 18 total       | Experienced troops        |
| Elite     | 3 per army   | 9 total        | Specialized forces        |
| Legendary | 1 per army   | 3 total        | Unique heroes             |
| Mythic    | 1 per player | 1 per player   | Faction-specific ultimate |

**Legendary Unit Restrictions:**

```typescript
interface UnitCaps {
  standard: { perArmy: number; perPlayer: number };
  veteran: { perArmy: number; perPlayer: number };
  elite: { perArmy: number; perPlayer: number };
  legendary: { perArmy: number; perPlayer: number };
  mythic: { perArmy: number; perPlayer: number };
}

const DEFAULT_UNIT_CAPS: UnitCaps = {
  standard: { perArmy: Infinity, perPlayer: Infinity },
  veteran: { perArmy: 6, perPlayer: 18 },
  elite: { perArmy: 3, perPlayer: 9 },
  legendary: { perArmy: 1, perPlayer: 3 },
  mythic: { perArmy: 1, perPlayer: 1 },
};

interface LegendaryUnit extends Army {
  tier: 'legendary' | 'mythic';
  uniqueName: string;
  loreEntry: string;

  // Legendary abilities
  legendaryAbility: LegendaryAbility;
  deathConsequence: WeaveConsequence; // What happens to the Weave when they die

  // Restrictions
  recruitmentRequirements: Requirement[];
  cannotRetreat: boolean;
  bonusAgainstOtherLegendaries: number;
}

function validateUnitRecruitment(
  player: Player,
  unit: Army,
  targetArmy: Army[],
  allPlayerUnits: Army[]
): RecruitmentValidation {
  const tier = getUnitTier(unit);
  const caps = player.faction.unitCaps ?? DEFAULT_UNIT_CAPS;

  // Count current units of this tier
  const inArmy = targetArmy.filter((u) => getUnitTier(u) === tier).length;
  const playerTotal = allPlayerUnits.filter(
    (u) => getUnitTier(u) === tier
  ).length;

  const armyCap = caps[tier].perArmy;
  const playerCap = caps[tier].perPlayer;

  if (inArmy >= armyCap) {
    return {
      valid: false,
      reason: `Army already has maximum ${tier} units (${armyCap})`,
    };
  }

  if (playerTotal >= playerCap) {
    return {
      valid: false,
      reason: `Player already has maximum ${tier} units (${playerCap})`,
    };
  }

  // Legendary-specific requirements
  if (unit.tier === 'legendary' || unit.tier === 'mythic') {
    const reqsMet = checkLegendaryRequirements(unit as LegendaryUnit, player);
    if (!reqsMet.success) {
      return { valid: false, reason: reqsMet.reason };
    }
  }

  return { valid: true };
}
```

---

## 3. Tactical Combat Options

### 3.1 Retreat and Fallback Mechanics

Armies can attempt to disengage from combat, preserving forces at the cost of
position.

**Retreat Conditions:**

| Situation                         | Retreat Difficulty     | Penalty on Failure                 |
| --------------------------------- | ---------------------- | ---------------------------------- |
| Winning (margin +2 or more)       | Automatic              | None                               |
| Tied or close (margin -1 to +1)   | Moderate (3 successes) | 25% casualties                     |
| Losing (margin -2 to -3)          | Hard (4 successes)     | 50% casualties                     |
| Badly losing (margin -4 or worse) | Extreme (5 successes)  | 75% casualties, commander captured |
| Surrounded                        | Cannot retreat         | Full destruction                   |

**Fallback Mechanics:**

```typescript
interface RetreatAttempt {
  retreatingArmy: Army[];
  combatMargin: number;
  retreatDestination: TerritoryId;

  // Modifiers
  hasMobileUnits: boolean; // +1 die
  hasOpenRetreatRoute: boolean; // Required
  pursuingCavalry: boolean; // -2 dice
  commanderPresent: boolean; // +1 die
}

interface RetreatResult {
  success: boolean;
  casualtyPercentage: number;
  unitsLost: Army[];
  unitsSurvived: Army[];
  commanderCaptured: boolean;
  destination: TerritoryId | null;
  weaveEntry: WeaveEntry | null;
}

function attemptRetreat(
  attempt: RetreatAttempt,
  gameState: GameState
): RetreatResult {
  // Cannot retreat if surrounded
  if (!attempt.hasOpenRetreatRoute) {
    return {
      success: false,
      casualtyPercentage: 100,
      unitsLost: attempt.retreatingArmy,
      unitsSurvived: [],
      commanderCaptured: attempt.commanderPresent,
      destination: null,
      weaveEntry: generateLastStandWeaveEntry(attempt),
    };
  }

  // Automatic retreat if winning decisively
  if (attempt.combatMargin >= 2) {
    return {
      success: true,
      casualtyPercentage: 0,
      unitsLost: [],
      unitsSurvived: attempt.retreatingArmy,
      commanderCaptured: false,
      destination: attempt.retreatDestination,
      weaveEntry: null,
    };
  }

  // Calculate retreat difficulty
  let difficulty: number;
  let failureCasualties: number;

  if (attempt.combatMargin >= -1) {
    difficulty = 3;
    failureCasualties = 25;
  } else if (attempt.combatMargin >= -3) {
    difficulty = 4;
    failureCasualties = 50;
  } else {
    difficulty = 5;
    failureCasualties = 75;
  }

  // Build dice pool
  let dicePool = 3; // Base pool
  if (attempt.hasMobileUnits) dicePool += 1;
  if (attempt.commanderPresent) dicePool += 1;
  if (attempt.pursuingCavalry) dicePool -= 2;

  // Roll retreat
  const roll = performRoll(Math.max(1, dicePool));
  const success = roll.netSuccesses >= difficulty;

  // Calculate casualties
  const actualCasualties = success
    ? Math.floor(failureCasualties / 2)
    : failureCasualties;
  const casualties = applyArmyCasualties(
    attempt.retreatingArmy,
    actualCasualties
  );

  return {
    success,
    casualtyPercentage: actualCasualties,
    unitsLost: casualties.lost,
    unitsSurvived: casualties.survived,
    commanderCaptured:
      !success && attempt.combatMargin <= -4 && attempt.commanderPresent,
    destination: success ? attempt.retreatDestination : null,
    weaveEntry: generateRetreatWeaveEntry(attempt, roll, success),
  };
}
```

### 3.2 Defensive Terrain Bonuses

Terrain significantly affects combat outcomes.

**Terrain Combat Modifiers:**

| Terrain Type   | Attacker Modifier | Defender Modifier | Special Rules                     |
| -------------- | ----------------- | ----------------- | --------------------------------- |
| Open Field     | 0                 | 0                 | Cavalry charge bonus              |
| Forest         | -1                | +2                | No cavalry bonus, ambush possible |
| Mountains      | -2                | +3                | Limited unit capacity             |
| River Crossing | -2                | +1                | Cannot retreat forward            |
| Swamp          | -1                | +1                | Siege units cannot deploy         |
| Urban          | -1                | +2                | Street fighting rules             |
| Sacred Ground  | 0                 | +1                | Resonance abilities enhanced      |
| Void Scar      | +1 (Void-aligned) | -1 (others)       | Corruption spreads                |

```typescript
interface TerrainCombatEffect {
  terrainType: TerrainType;

  // Dice modifiers
  attackerModifier: number;
  defenderModifier: number;

  // Special rules
  cavalryChargeAllowed: boolean;
  ambushPossible: boolean;
  siegeUnitsAllowed: boolean;
  retreatRestriction: 'none' | 'forward_blocked' | 'all_blocked';

  // Plane-specific modifiers
  resonanceEffectMultiplier: number; // 1.0 = normal, 1.5 = enhanced
  voidCorruptionRate: number; // 1.0 = normal, 2.0 = doubled
}

const TERRAIN_EFFECTS: Record<TerrainType, TerrainCombatEffect> = {
  open_field: {
    terrainType: 'open_field',
    attackerModifier: 0,
    defenderModifier: 0,
    cavalryChargeAllowed: true,
    ambushPossible: false,
    siegeUnitsAllowed: true,
    retreatRestriction: 'none',
    resonanceEffectMultiplier: 1.0,
    voidCorruptionRate: 1.0,
  },
  forest: {
    terrainType: 'forest',
    attackerModifier: -1,
    defenderModifier: 2,
    cavalryChargeAllowed: false,
    ambushPossible: true,
    siegeUnitsAllowed: true,
    retreatRestriction: 'none',
    resonanceEffectMultiplier: 1.0,
    voidCorruptionRate: 0.5,
  },
  mountains: {
    terrainType: 'mountains',
    attackerModifier: -2,
    defenderModifier: 3,
    cavalryChargeAllowed: false,
    ambushPossible: true,
    siegeUnitsAllowed: false,
    retreatRestriction: 'none',
    resonanceEffectMultiplier: 0.8,
    voidCorruptionRate: 0.5,
  },
  river_crossing: {
    terrainType: 'river_crossing',
    attackerModifier: -2,
    defenderModifier: 1,
    cavalryChargeAllowed: false,
    ambushPossible: false,
    siegeUnitsAllowed: true,
    retreatRestriction: 'forward_blocked',
    resonanceEffectMultiplier: 1.2,
    voidCorruptionRate: 1.0,
  },
  swamp: {
    terrainType: 'swamp',
    attackerModifier: -1,
    defenderModifier: 1,
    cavalryChargeAllowed: false,
    ambushPossible: true,
    siegeUnitsAllowed: false,
    retreatRestriction: 'none',
    resonanceEffectMultiplier: 1.0,
    voidCorruptionRate: 1.5,
  },
  urban: {
    terrainType: 'urban',
    attackerModifier: -1,
    defenderModifier: 2,
    cavalryChargeAllowed: false,
    ambushPossible: true,
    siegeUnitsAllowed: true,
    retreatRestriction: 'none',
    resonanceEffectMultiplier: 1.0,
    voidCorruptionRate: 0.8,
  },
  sacred_ground: {
    terrainType: 'sacred_ground',
    attackerModifier: 0,
    defenderModifier: 1,
    cavalryChargeAllowed: true,
    ambushPossible: false,
    siegeUnitsAllowed: false,
    retreatRestriction: 'none',
    resonanceEffectMultiplier: 1.5,
    voidCorruptionRate: 0.25,
  },
  void_scar: {
    terrainType: 'void_scar',
    attackerModifier: 0, // +1 for Void-aligned
    defenderModifier: -1, // Unless Void-aligned
    cavalryChargeAllowed: true,
    ambushPossible: true,
    siegeUnitsAllowed: false,
    retreatRestriction: 'none',
    resonanceEffectMultiplier: 0.5,
    voidCorruptionRate: 3.0,
  },
};
```

### 3.3 Siege and Fortification Rules

Sieges are extended combat actions against fortified positions.

**Siege Mechanics:**

| Fortification Level | Defense Bonus | Siege Duration | Starvation Timer |
| ------------------- | ------------- | -------------- | ---------------- |
| Watchtower          | +1            | 1 round        | N/A              |
| Palisade            | +2            | 2 rounds       | 3 turns          |
| Stone Fort          | +4            | 4 rounds       | 6 turns          |
| Citadel             | +6            | 6 rounds       | 10 turns         |
| Veil Fortress       | +8            | 8 rounds       | 15 turns         |

**Siege Resolution:**

```typescript
interface SiegeState {
  siegeId: string;
  fortificationId: string;
  attackingPlayer: PlayerId;
  defendingPlayer: PlayerId;

  // Progress
  currentRound: number;
  totalRoundsRequired: number;
  breachProgress: number; // 0-100

  // Resources
  attackerSupply: number;
  defenderSupply: number;
  defenderStarvationTimer: number;

  // Modifiers
  siegeEngineCount: number;
  engineerCount: number;
  reinforcementsPossible: boolean;

  // Combat log
  roundResults: SiegeRoundResult[];
}

interface SiegeRoundResult {
  round: number;
  attackerLosses: number;
  defenderLosses: number;
  breachProgress: number;
  wallIntegrity: number;
  specialEvents: SiegeEvent[];
}

type SiegeEvent =
  | { type: 'breach'; section: string }
  | { type: 'sortie'; success: boolean; casualties: number }
  | { type: 'reinforcement'; player: PlayerId; units: number }
  | { type: 'starvation'; moraleImpact: number }
  | { type: 'sabotage'; target: 'siege_engine' | 'supplies' | 'morale' }
  | { type: 'parley'; outcome: 'rejected' | 'surrender' | 'terms' };

function resolveSiegeRound(
  siege: SiegeState,
  gameState: GameState
): SiegeRoundResult {
  const fort = getFortification(siege.fortificationId, gameState);
  const attackers = getArmyAtTerritory(siege.attackingArmy, gameState);
  const defenders = fort.currentGarrison;

  // Calculate attacker dice pool
  let attackPool = calculateSiegeAttackPool(attackers, siege);

  // Calculate defender dice pool
  let defensePool = calculateSiegeDefensePool(defenders, fort, siege);

  // Roll combat
  const attackRoll = performRoll(attackPool);
  const defenseRoll = performRoll(defensePool);

  // Calculate results
  const netSuccesses = attackRoll.netSuccesses - defenseRoll.netSuccesses;

  // Breach progress
  let breachGain = 0;
  if (netSuccesses > 0) {
    breachGain = netSuccesses * 5; // 5% per net success
    breachGain *= 1 + siege.siegeEngineCount * 0.25; // Siege engines boost
    breachGain *= 1 + siege.engineerCount * 0.15; // Engineers boost
  }

  siege.breachProgress = Math.min(100, siege.breachProgress + breachGain);

  // Calculate casualties
  const attackerCasualties = calculateSiegeCasualties(
    attackers,
    defenseRoll,
    'attacker'
  );
  const defenderCasualties = calculateSiegeCasualties(
    defenders,
    attackRoll,
    'defender'
  );

  // Update starvation
  if (siege.defenderSupply <= 0) {
    siege.defenderStarvationTimer--;
    if (siege.defenderStarvationTimer <= 0) {
      // Garrison surrenders or dies
      return generateStarvationResult(siege);
    }
  }

  // Check for breach
  const events: SiegeEvent[] = [];
  if (siege.breachProgress >= 100) {
    events.push({ type: 'breach', section: determineBreach(fort) });
  }

  return {
    round: siege.currentRound,
    attackerLosses: attackerCasualties,
    defenderLosses: defenderCasualties,
    breachProgress: siege.breachProgress,
    wallIntegrity: 100 - siege.breachProgress,
    specialEvents: events,
  };
}

function calculateSiegeAttackPool(
  attackers: Army[],
  siege: SiegeState
): number {
  let pool = 0;

  // Sum attacker strength
  for (const unit of attackers) {
    pool += unit.currentStrength;
  }

  // Siege engine bonus
  pool += siege.siegeEngineCount * 3;

  // Engineer bonus
  pool += siege.engineerCount * 2;

  // Long siege penalty (-1 per 2 rounds after round 3)
  if (siege.currentRound > 3) {
    pool -= Math.floor((siege.currentRound - 3) / 2);
  }

  return Math.max(1, pool);
}
```

### 3.4 Naval/Aerial Equivalent Mechanics Per Plane

Each plane has unique "mobility layer" equivalents that function like naval or
aerial units.

**Material Plane - Naval Forces:**

| Unit Type       | Speed | Transport | Combat | Special              |
| --------------- | ----- | --------- | ------ | -------------------- |
| River Boat      | 4     | 4 units   | 1      | River-only           |
| Coastal Ship    | 3     | 8 units   | 2      | Coast and open water |
| War Galley      | 3     | 4 units   | 5      | Combat-focused       |
| Transport Fleet | 2     | 20 units  | 0      | Mass transport       |

**Resonance Plane - Ley Line Riders:**

| Entity Type   | Range          | Power Draw      | Combat | Special                     |
| ------------- | -------------- | --------------- | ------ | --------------------------- |
| Ley Runner    | 6 ley segments | 5 essence/turn  | 2      | Fast scouting               |
| Veil Walker   | 4 ley segments | 10 essence/turn | 4      | Standard transport          |
| Nexus Striker | 3 ley segments | 20 essence/turn | 8      | Combat-focused              |
| Anchor Ship   | 2 ley segments | 30 essence/turn | 3      | Establishes temporary nodes |

**Void Plane - Shadow Vessels:**

| Entity Type    | Speed | Corruption | Combat | Special                         |
| -------------- | ----- | ---------- | ------ | ------------------------------- |
| Shadow Skiff   | 5     | +1/turn    | 1      | Stealth movement                |
| Void Drifter   | 3     | +2/turn    | 3      | Cross-entropy travel            |
| Paradox Barge  | 2     | +3/turn    | 6      | Can create paradox wells        |
| Reality Anchor | 1     | 0          | 0      | Stabilizes areas, counters Void |

```typescript
interface MobilityUnit {
  id: string;
  type: MobilityUnitType;
  plane: PlaneType;
  owner: PlayerId;

  // Movement
  speed: number;
  currentLocation: LocationId;
  movementPath: LocationId[];

  // Capacity
  transportCapacity: number;
  currentCargo: TransportedUnit[];

  // Combat
  combatStrength: number;
  specialAbilities: MobilityAbility[];

  // Plane-specific
  planeSpecificCost: PlaneCost;
}

interface PlaneCost {
  // Material: gold upkeep
  goldPerTurn?: number;

  // Resonance: essence consumption
  essencePerTurn?: number;
  leyLineRequired?: boolean;

  // Void: corruption accumulation
  corruptionPerTurn?: number;
  entropyRequirement?: number;
}

function moveResonanceEntity(
  entity: MobilityUnit,
  destination: LocationId,
  gameState: GameState
): MoveResult {
  if (entity.plane !== 'resonance') {
    throw new Error('Cannot use Resonance movement for non-Resonance entity');
  }

  // Check ley line connection
  const leyPath = findLeyLinePath(
    entity.currentLocation,
    destination,
    gameState.leyLines
  );

  if (!leyPath || leyPath.length > entity.speed) {
    return { success: false, reason: 'No valid ley line path within range' };
  }

  // Check essence cost
  const essenceCost = entity.planeSpecificCost.essencePerTurn! * leyPath.length;
  if (gameState.players.get(entity.owner)!.essence < essenceCost) {
    return { success: false, reason: 'Insufficient essence' };
  }

  // Execute movement
  deductEssence(entity.owner, essenceCost, gameState);
  entity.currentLocation = destination;
  entity.movementPath = leyPath;

  return { success: true, essenceSpent: essenceCost, pathTaken: leyPath };
}
```

---

## 4. Combat Logging for Weave Integration

All significant combat outcomes are recorded in the Weave system, creating
narrative threads that influence future events and provide persistent memory.

### 4.1 Battle Outcome Recording

**What Gets Recorded:**

| Event Type           | Trigger Condition                | Weave Weight |
| -------------------- | -------------------------------- | ------------ |
| Minor Skirmish       | < 5 units involved               | 1            |
| Battle               | 5-20 units involved              | 3            |
| Major Battle         | 20-50 units involved             | 5            |
| Campaign Decisive    | 50+ units or strategic objective | 8            |
| Legendary Clash      | Legendary units involved         | 10           |
| Mythic Confrontation | Mythic units involved            | 15           |

```typescript
interface BattleWeaveEntry {
  // Identification
  battleId: string;
  timestamp: Date;
  turnNumber: number;

  // Location
  territoryId: TerritoryId;
  plane: PlaneType;
  terrain: TerrainType;

  // Participants
  attacker: BattleParticipant;
  defender: BattleParticipant;

  // Outcome
  victor: PlayerId | 'draw';
  victoryType: VictoryType;
  margin: number;

  // Significance
  weaveWeight: number;
  narrativeTags: NarrativeTag[];

  // Consequences
  territoryControlChange: boolean;
  legendaryUnitsInvolved: LegendaryUnitId[];
  heroicDeeds: HeroicDeed[];
  tragedies: Tragedy[];

  // Generated narrative
  battleTitle: string; // e.g., "The Siege of Echoing Halls"
  briefDescription: string; // 1-2 sentence summary
  detailedAccount: string; // Full narrative
}

interface BattleParticipant {
  playerId: PlayerId;
  factionId: FactionId;
  commander: CommanderId | null;

  // Forces
  initialStrength: number;
  unitsInvolved: UnitSummary[];
  legendaryUnits: LegendaryUnitId[];

  // Casualties
  unitsLost: number;
  legendaryUnitsLost: LegendaryUnitId[];
  commanderStatus: 'alive' | 'wounded' | 'captured' | 'killed';
}

type VictoryType =
  | 'decisive' // Margin >= 5
  | 'clear' // Margin 3-4
  | 'narrow' // Margin 1-2
  | 'pyrrhic' // Won but lost more than defender
  | 'mutual_destruction' // Both forces destroyed
  | 'draw'; // Neither side gained advantage

function recordBattleOutcome(
  battle: CombatResult,
  gameState: GameState
): BattleWeaveEntry {
  const weaveWeight = calculateWeaveWeight(battle);
  const victoryType = determineVictoryType(battle);
  const heroicDeeds = extractHeroicDeeds(battle);
  const tragedies = extractTragedies(battle);

  const entry: BattleWeaveEntry = {
    battleId: generateBattleId(),
    timestamp: new Date(),
    turnNumber: gameState.currentTurn,

    territoryId: battle.location,
    plane: battle.plane,
    terrain: getTerrain(battle.location, gameState),

    attacker: summarizeParticipant(battle.attacker, battle.attackerResult),
    defender: summarizeParticipant(battle.defender, battle.defenderResult),

    victor: battle.victor,
    victoryType,
    margin: battle.margin,

    weaveWeight,
    narrativeTags: generateNarrativeTags(battle),

    territoryControlChange: battle.controlChanged,
    legendaryUnitsInvolved: extractLegendaryUnits(battle),
    heroicDeeds,
    tragedies,

    battleTitle: generateBattleTitle(battle, gameState),
    briefDescription: generateBriefDescription(battle),
    detailedAccount: generateDetailedAccount(battle, heroicDeeds, tragedies),
  };

  // Store in Weave
  gameState.weave.addBattleEntry(entry);

  // Create connections to existing nodes
  createBattleWeaveConnections(entry, gameState.weave);

  return entry;
}
```

### 4.2 Casualty Tracking for Narrative Weight

Casualties are tracked not just as numbers, but as narrative elements that
affect the Weave.

**Casualty Categories:**

| Category     | Threshold | Narrative Impact    |
| ------------ | --------- | ------------------- |
| Light        | < 10%     | Minor mention       |
| Moderate     | 10-25%    | Notable losses      |
| Heavy        | 25-50%    | Significant grief   |
| Devastating  | 50-75%    | Generation-defining |
| Annihilation | > 75%     | Legendary tragedy   |

```typescript
interface CasualtyRecord {
  // Raw numbers
  totalUnitsInvolved: number;
  unitsLost: number;
  percentage: number;

  // Categorization
  category: CasualtyCategory;

  // Named losses
  namedUnitsLost: NamedUnit[];
  commandersLost: Commander[];
  legendaryUnitsLost: LegendaryUnit[];

  // Narrative elements
  lastStands: LastStandRecord[];
  heroicSacrifices: SacrificeRecord[];

  // Long-term effects
  moraleImpact: number; // -100 to +10
  recruitmentPenalty: number; // Turns of reduced recruitment
  revengeThreadGenerated: boolean;
}

interface LastStandRecord {
  unit: Army;
  location: TerritoryId;
  enemiesSlain: number;
  finalWords: string | null; // Generated narrative
  weaveImpact: number; // +2 to +10 based on drama
}

function calculateCasualtyNarrativeWeight(casualties: CasualtyRecord): number {
  let weight = 0;

  // Base weight from percentage
  switch (casualties.category) {
    case 'light':
      weight += 1;
      break;
    case 'moderate':
      weight += 3;
      break;
    case 'heavy':
      weight += 5;
      break;
    case 'devastating':
      weight += 8;
      break;
    case 'annihilation':
      weight += 12;
      break;
  }

  // Named unit multiplier
  weight += casualties.namedUnitsLost.length * 2;

  // Commander loss
  weight += casualties.commandersLost.length * 5;

  // Legendary unit loss
  weight += casualties.legendaryUnitsLost.length * 10;

  // Heroic moments
  weight += casualties.lastStands.reduce((sum, ls) => sum + ls.weaveImpact, 0);
  weight += casualties.heroicSacrifices.length * 3;

  return weight;
}

function generateRevengeThread(
  casualties: CasualtyRecord,
  losingPlayer: PlayerId,
  winningPlayer: PlayerId,
  battle: BattleWeaveEntry,
  gameState: GameState
): WeaveThread | null {
  // Only generate for devastating+ casualties
  if (casualties.percentage < 50) return null;
  if (
    !casualties.legendaryUnitsLost.length &&
    !casualties.commandersLost.length
  ) {
    return null;
  }

  const thread: WeaveThread = {
    id: generateThreadId(),
    type: 'revenge',
    importance: casualties.category === 'annihilation' ? 'major' : 'minor',
    status: 'active',

    // Connections
    sourceEvent: battle.battleId,
    participants: [losingPlayer, winningPlayer],

    // Narrative
    title: generateRevengeTitle(casualties, battle),
    description: `${getPlayerName(losingPlayer)} swears vengeance for the losses at ${battle.battleTitle}`,

    // Mechanical effects
    effects: [
      {
        type: 'combat_bonus',
        target: losingPlayer,
        against: winningPlayer,
        value: Math.ceil(casualties.percentage / 25), // +1 to +4
        duration: 10, // turns
      },
    ],

    // Resolution conditions
    resolutionConditions: [
      { type: 'defeat_player', target: winningPlayer },
      { type: 'legendary_kill', target: winningPlayer },
      { type: 'territory_capture', location: battle.territoryId },
    ],
  };

  return thread;
}
```

### 4.3 Heroic Deed Documentation

Exceptional actions during combat are captured as heroic deeds that become part
of the persistent narrative.

**Deed Categories:**

| Deed Type          | Trigger                          | Weave Impact |
| ------------------ | -------------------------------- | ------------ |
| Against the Odds   | Won with 50%+ disadvantage       | +5           |
| Perfect Victory    | Won with 0 casualties            | +3           |
| Legendary Duel     | Legendary vs Legendary combat    | +8           |
| Last Stand         | Held position to the last unit   | +6           |
| Tactical Genius    | Won using special maneuver       | +4           |
| Cross-Plane Strike | Decisive cross-plane attack      | +5           |
| Mercy Shown        | Accepted surrender, spared lives | +2           |
| Oath Fulfilled     | Completed specific vengeance     | +7           |

```typescript
interface HeroicDeed {
  deedId: string;
  deedType: DeedType;
  performer: PlayerId | UnitId | CommanderId;

  // Context
  battleId: string;
  turnNumber: number;
  circumstances: string;

  // Details
  targetOfDeed: PlayerId | UnitId | TerritoryId | null;
  difficultyOvercome: number; // 1-10 scale

  // Narrative
  title: string; // "The Stand at Broken Bridge"
  description: string; // Full narrative description
  witnessQuote: string | null; // Optional flavor quote

  // Mechanical effects
  weaveImpact: number;
  permanentEffects: DeedEffect[];

  // Fame/Infamy
  fameGenerated: number; // Positive reputation
  infamyGenerated: number; // Negative reputation (for dark deeds)
}

interface DeedEffect {
  effectType:
    | 'stat_bonus'
    | 'ability_unlock'
    | 'title_gain'
    | 'weave_connection';
  target: PlayerId | UnitId | TerritoryId;
  value: number | string;
  duration: 'permanent' | 'campaign' | number; // number = turns
}

function extractHeroicDeeds(battle: CombatResult): HeroicDeed[] {
  const deeds: HeroicDeed[] = [];

  // Check for Against the Odds
  const oddsRatio = battle.attacker.strength / battle.defender.strength;
  if (battle.victor === battle.attacker.playerId && oddsRatio < 0.5) {
    deeds.push(createAgainstTheOddsDeed(battle, battle.attacker));
  }
  if (battle.victor === battle.defender.playerId && oddsRatio > 2.0) {
    deeds.push(createAgainstTheOddsDeed(battle, battle.defender));
  }

  // Check for Perfect Victory
  const victorCasualties =
    battle.victor === battle.attacker.playerId
      ? battle.attackerResult.casualties
      : battle.defenderResult.casualties;
  if (victorCasualties.percentage === 0) {
    deeds.push(createPerfectVictoryDeed(battle));
  }

  // Check for Legendary Duel
  if (battle.legendaryDuelOccurred) {
    deeds.push(createLegendaryDuelDeed(battle));
  }

  // Check for Last Stand
  const loserCasualties =
    battle.victor === battle.attacker.playerId
      ? battle.defenderResult.casualties
      : battle.attackerResult.casualties;
  if (
    loserCasualties.percentage >= 90 &&
    loserCasualties.lastStands.length > 0
  ) {
    for (const lastStand of loserCasualties.lastStands) {
      deeds.push(createLastStandDeed(battle, lastStand));
    }
  }

  // Check for Cross-Plane Strike
  if (battle.crossPlaneAttackDecisive) {
    deeds.push(createCrossPlaneStrikeDeed(battle));
  }

  return deeds;
}

function generateDeedTitle(
  deedType: DeedType,
  performer: string,
  location: string,
  context: CombatResult
): string {
  const templates: Record<DeedType, string[]> = {
    against_the_odds: [
      `${performer}'s Impossible Victory at ${location}`,
      `The Miracle of ${location}`,
      `${performer} Defies the Odds at ${location}`,
    ],
    perfect_victory: [
      `The Flawless Triumph of ${location}`,
      `${performer}'s Masterful Victory`,
      `Not a Drop at ${location}`,
    ],
    legendary_duel: [
      `The Clash of Legends at ${location}`,
      `When Giants Met at ${location}`,
      `The Duel That Shook ${location}`,
    ],
    last_stand: [
      `The Final Stand at ${location}`,
      `${performer}'s Last Dawn`,
      `The Heroes of ${location}`,
    ],
    tactical_genius: [
      `${performer}'s Masterstroke at ${location}`,
      `The Cunning of ${location}`,
      `Outmaneuvered at ${location}`,
    ],
    cross_plane_strike: [
      `The Veil-Piercing Strike at ${location}`,
      `${performer} Shatters Reality at ${location}`,
      `The Impossible Attack on ${location}`,
    ],
  };

  const options = templates[deedType];
  return options[Math.floor(Math.random() * options.length)];
}
```

### 4.4 Combat-to-Weave Integration API

The complete API for integrating combat outcomes with the Weave system.

```typescript
interface CombatWeaveIntegration {
  // Recording
  recordBattle(result: CombatResult): BattleWeaveEntry;
  recordSiege(siege: SiegeState, outcome: SiegeOutcome): SiegeWeaveEntry;
  recordSkirmish(skirmish: SkirmishResult): SkirmishWeaveEntry;

  // Querying
  getBattlesInTerritory(territoryId: TerritoryId): BattleWeaveEntry[];
  getBattlesBetweenPlayers(p1: PlayerId, p2: PlayerId): BattleWeaveEntry[];
  getRecentBattles(turnCount: number): BattleWeaveEntry[];
  getLegendaryBattles(): BattleWeaveEntry[];

  // Thread management
  getActiveRevengeThreads(player: PlayerId): WeaveThread[];
  getPendingOaths(player: PlayerId): WeaveThread[];
  getConsequenceThreads(triggeredBy: BattleId): WeaveThread[];

  // Narrative generation
  generateBattleSummary(battleId: string): string;
  generateCampaignHistory(player: PlayerId): CampaignHistory;
  generateTerritoryHistory(territoryId: TerritoryId): TerritoryHistory;

  // Mechanical effects
  getCombatModifiersFromWeave(
    attacker: PlayerId,
    defender: PlayerId,
    location: TerritoryId
  ): WeaveBasedModifiers;
}

interface WeaveBasedModifiers {
  // From revenge threads
  revengeBonus: number;

  // From territory history
  homegroundBonus: number; // Defender held for 5+ turns
  cursedGroundPenalty: number; // Site of massacre
  sacredGroundBonus: number; // Site of heroic deed

  // From relationship history
  oldEnemyBonus: number; // Many battles against same foe
  betrayalPenalty: number; // Broke oath with this player

  // From legendary unit history
  legendaryPresenceBonus: number; // Famous unit in army
  demoralizingPresencePenalty: number; // Feared enemy unit
}

function getCombatModifiersFromWeave(
  weave: WeaveSystem,
  attacker: PlayerId,
  defender: PlayerId,
  location: TerritoryId
): WeaveBasedModifiers {
  const modifiers: WeaveBasedModifiers = {
    revengeBonus: 0,
    homegroundBonus: 0,
    cursedGroundPenalty: 0,
    sacredGroundBonus: 0,
    oldEnemyBonus: 0,
    betrayalPenalty: 0,
    legendaryPresenceBonus: 0,
    demoralizingPresencePenalty: 0,
  };

  // Check for active revenge threads
  const revengeThreads = weave.getActiveRevengeThreads(attacker);
  for (const thread of revengeThreads) {
    if (thread.participants.includes(defender)) {
      modifiers.revengeBonus += thread.effects
        .filter((e) => e.type === 'combat_bonus')
        .reduce((sum, e) => sum + e.value, 0);
    }
  }

  // Check territory history
  const territoryHistory = weave.getTerritoryHistory(location);
  if (territoryHistory.controlHistory.continuousControlTurns(defender) >= 5) {
    modifiers.homegroundBonus = 2;
  }

  // Check for cursed/sacred ground
  const locationDeeds = weave.getDeedsAtLocation(location);
  for (const deed of locationDeeds) {
    if (deed.deedType === 'last_stand' || deed.weaveImpact >= 8) {
      if (deed.performer === attacker) {
        modifiers.sacredGroundBonus += 1;
      }
    }
  }

  const locationTragedies = weave.getTragediesAtLocation(location);
  if (locationTragedies.some((t) => t.severity === 'massacre')) {
    modifiers.cursedGroundPenalty = -1;
  }

  // Check battle history between players
  const sharedBattles = weave.getBattlesBetweenPlayers(attacker, defender);
  if (sharedBattles.length >= 5) {
    modifiers.oldEnemyBonus = Math.min(3, Math.floor(sharedBattles.length / 5));
  }

  // Check for betrayal
  const betrayalThreads = weave.getBetrayalThreads(attacker, defender);
  if (betrayalThreads.some((t) => t.betrayer === attacker)) {
    modifiers.betrayalPenalty = -2; // Penalty for the betrayer, not the betrayed
  }

  return modifiers;
}
```

---

## 5. Complete Combat Resolution Flow

### 5.1 Full Combat Resolution Algorithm

```typescript
interface CombatResolutionInput {
  attacker: CombatForce;
  defender: CombatForce;
  territory: TerritoryState;
  plane: PlaneType;
  attackType: AttackType;

  // Optional
  crossPlaneAttack?: CrossPlaneAttack;
  siegeState?: SiegeState;
}

interface CombatForce {
  playerId: PlayerId;
  armies: Army[];
  commander: Commander | null;
  composition: ArmyComposition;
  supportUnits: MobilityUnit[];
}

interface CombatResolutionResult {
  victor: PlayerId | 'draw';
  margin: number;

  attackerResult: {
    dicePoolUsed: number;
    roll: DiceResultBreakdown;
    casualties: CasualtyRecord;
    retreatResult: RetreatResult | null;
  };

  defenderResult: {
    dicePoolUsed: number;
    roll: DiceResultBreakdown;
    casualties: CasualtyRecord;
    retreatResult: RetreatResult | null;
  };

  territoryChange: {
    controlChanged: boolean;
    newController: PlayerId | null;
    planesAffected: PlaneType[];
  };

  weaveEntries: WeaveEntry[];
  heroicDeeds: HeroicDeed[];
  activeThreadsTriggered: WeaveThread[];
}

function resolveCombat(
  input: CombatResolutionInput,
  gameState: GameState
): CombatResolutionResult {
  // 1. Calculate base dice pools
  let attackerPool = calculateBasePool(input.attacker);
  let defenderPool = calculateBasePool(input.defender);

  // 2. Apply plane-specific modifiers
  const planeModifiers = getPlaneModifiers(
    input.plane,
    input.territory,
    gameState
  );
  attackerPool = applyPlaneModifiers(
    attackerPool,
    planeModifiers,
    'attacker',
    input
  );
  defenderPool = applyPlaneModifiers(
    defenderPool,
    planeModifiers,
    'defender',
    input
  );

  // 3. Apply synergy chain bonuses
  const attackerSynergy = calculateSynergyBonus(
    input.territory,
    input.attacker.playerId
  );
  const defenderSynergy = calculateSynergyBonus(
    input.territory,
    input.defender.playerId
  );
  attackerPool += attackerSynergy.diceBonus;
  defenderPool += defenderSynergy.diceBonus;

  // 4. Apply army composition bonuses
  attackerPool += input.attacker.composition.compositionBonus.attackDice;
  defenderPool += input.defender.composition.compositionBonus.defenseDice;

  // 5. Apply terrain modifiers
  const terrain = getTerrain(input.territory.id, gameState);
  const terrainEffect = TERRAIN_EFFECTS[terrain];
  attackerPool += terrainEffect.attackerModifier;
  defenderPool += terrainEffect.defenderModifier;

  // 6. Apply Weave-based modifiers
  const weaveModifiers = getCombatModifiersFromWeave(
    gameState.weave,
    input.attacker.playerId,
    input.defender.playerId,
    input.territory.id
  );
  attackerPool +=
    weaveModifiers.revengeBonus +
    weaveModifiers.sacredGroundBonus +
    weaveModifiers.oldEnemyBonus;
  attackerPool -=
    weaveModifiers.cursedGroundPenalty + weaveModifiers.betrayalPenalty;
  defenderPool += weaveModifiers.homegroundBonus;

  // 7. Apply cross-plane penalties if applicable
  if (input.crossPlaneAttack) {
    attackerPool -= input.crossPlaneAttack.baseDicePenalty;
  }

  // 8. Ensure minimum pools
  attackerPool = Math.max(1, attackerPool);
  defenderPool = Math.max(1, defenderPool);

  // 9. Roll Echo Dice
  let attackerRoll = performRoll(attackerPool);
  let defenderRoll = performRoll(defenderPool);

  // 10. Apply Full Dominion Echo Amplification
  if (attackerSynergy.specialEffect?.type === 'full_dominion') {
    attackerRoll = applyEchoAmplification(attackerRoll, true, defaultRandom);
  }
  if (defenderSynergy.specialEffect?.type === 'full_dominion') {
    defenderRoll = applyEchoAmplification(defenderRoll, true, defaultRandom);
  }

  // 11. Apply Full Dominion Shadow Immunity
  if (defenderSynergy.specialEffect?.type === 'full_dominion') {
    defenderRoll = { ...defenderRoll, shadows: 0, veilPointsGained: 0 };
  }

  // 12. Calculate margin
  const margin = attackerRoll.netSuccesses - defenderRoll.netSuccesses;
  const victor =
    margin > 0
      ? input.attacker.playerId
      : margin < 0
        ? input.defender.playerId
        : 'draw';

  // 13. Calculate casualties
  const attackerCasualties = calculateCasualties(
    input.attacker,
    defenderRoll,
    margin < 0 ? Math.abs(margin) : 0,
    'attacker'
  );
  const defenderCasualties = calculateCasualties(
    input.defender,
    attackerRoll,
    margin > 0 ? margin : 0,
    'defender'
  );

  // 14. Handle retreats if applicable
  let attackerRetreat: RetreatResult | null = null;
  let defenderRetreat: RetreatResult | null = null;

  if (victor === input.defender.playerId && margin <= -2) {
    attackerRetreat = attemptRetreat(
      {
        retreatingArmy: input.attacker.armies,
        combatMargin: margin,
        retreatDestination: findRetreatDestination(
          input.attacker.playerId,
          input.territory,
          gameState
        ),
        hasMobileUnits: hasMobileUnits(input.attacker),
        hasOpenRetreatRoute: hasOpenRetreatRoute(
          input.attacker.playerId,
          input.territory,
          gameState
        ),
        pursuingCavalry: hasCavalry(input.defender),
        commanderPresent: input.attacker.commander !== null,
      },
      gameState
    );
  }

  // 15. Determine territory control changes
  const territoryChange = determineControlChange(
    input.territory,
    input.plane,
    victor,
    input.attacker.playerId,
    input.defender.playerId,
    margin
  );

  // 16. Extract heroic deeds
  const heroicDeeds = extractHeroicDeeds({
    attacker: input.attacker,
    defender: input.defender,
    attackerResult: { roll: attackerRoll, casualties: attackerCasualties },
    defenderResult: { roll: defenderRoll, casualties: defenderCasualties },
    victor,
    margin,
    location: input.territory.id,
    plane: input.plane,
    crossPlaneAttackDecisive: input.crossPlaneAttack && margin >= 3,
    legendaryDuelOccurred: hasLegendaryDuel(input.attacker, input.defender),
  });

  // 17. Record in Weave
  const battleEntry = recordBattleOutcome(
    {
      ...input,
      victor,
      margin,
      attackerResult: { roll: attackerRoll, casualties: attackerCasualties },
      defenderResult: { roll: defenderRoll, casualties: defenderCasualties },
      heroicDeeds,
      controlChanged: territoryChange.controlChanged,
    },
    gameState
  );

  // 18. Check for triggered Weave threads
  const triggeredThreads = checkTriggeredThreads(
    gameState.weave,
    battleEntry,
    heroicDeeds
  );

  return {
    victor,
    margin,
    attackerResult: {
      dicePoolUsed: attackerPool,
      roll: attackerRoll,
      casualties: attackerCasualties,
      retreatResult: attackerRetreat,
    },
    defenderResult: {
      dicePoolUsed: defenderPool,
      roll: defenderRoll,
      casualties: defenderCasualties,
      retreatResult: defenderRetreat,
    },
    territoryChange,
    weaveEntries: [battleEntry],
    heroicDeeds,
    activeThreadsTriggered: triggeredThreads,
  };
}
```

---

## 6. Combat UI/UX Considerations

### 6.1 Combat Preview

Before combat resolves, players should see a preview:

```typescript
interface CombatPreview {
  // Dice pools
  attackerEstimatedPool: DicePoolBreakdown;
  defenderEstimatedPool: DicePoolBreakdown;

  // Success probability
  attackerWinProbability: number;
  defenderWinProbability: number;
  drawProbability: number;

  // Expected casualties
  attackerExpectedCasualties: CasualtyRange;
  defenderExpectedCasualties: CasualtyRange;

  // Special considerations
  warnings: CombatWarning[];
  opportunities: CombatOpportunity[];
}

interface DicePoolBreakdown {
  base: number;
  planeModifiers: number;
  synergyBonus: number;
  compositionBonus: number;
  terrainModifier: number;
  weaveModifiers: number;
  crossPlanePenalty: number;
  total: number;
}

interface CombatWarning {
  severity: 'info' | 'warning' | 'danger';
  message: string;
}

interface CombatOpportunity {
  type: string;
  bonus: string;
  condition: string;
}
```

### 6.2 Combat Log Display

```typescript
interface CombatLogEntry {
  timestamp: Date;
  phase: CombatPhase;
  description: string;
  diceRolls?: {
    attacker: number[];
    defender: number[];
  };
  outcome?: string;
  highlight?: boolean;
}

type CombatPhase =
  | 'setup'
  | 'modifier_calculation'
  | 'dice_roll'
  | 'echo_resolution'
  | 'damage_calculation'
  | 'casualty_application'
  | 'retreat_check'
  | 'territory_control'
  | 'weave_recording'
  | 'complete';
```

---

## Appendix A: Combat Modifier Reference Table

| Source           | Modifier Type  | Value Range | Notes                  |
| ---------------- | -------------- | ----------- | ---------------------- |
| Superior Numbers | Attack/Defense | +1 to +4    | Per 25% advantage      |
| Fortification    | Defense only   | +1 to +8    | Based on fort level    |
| Terrain          | Attack/Defense | -2 to +3    | See terrain table      |
| Commander        | Attack/Defense | +1 to +3    | Based on rating        |
| Flanking         | Attack only    | +2 to +4    | Multiple directions    |
| Supply Status    | Universal      | -1 to -2    | Foraging/Starving      |
| Ley Line         | Resonance      | +1 to +4    | Per connection         |
| Power Node       | Resonance      | +2          | Controlling node       |
| Veil Density     | Resonance      | +1 to +3    | Local Veil strength    |
| Essence Spent    | Resonance      | +1 to +4    | 5 Essence per die      |
| Entropy Level    | Void           | +1 to +4    | Local entropy          |
| Corruption Align | Void           | +2          | Void-aligned factions  |
| Ambush           | Void           | +3          | From Hidden Passage    |
| Dual-Plane       | Synergy        | +2          | Control 2 planes       |
| Full Dominion    | Synergy        | +4          | Control all 3 planes   |
| Revenge Thread   | Weave          | +1 to +4    | Active revenge         |
| Homeground       | Weave          | +2          | Defender held 5+ turns |
| Old Enemy        | Weave          | +1 to +3    | 5+ previous battles    |
| Cross-Plane      | Penalty        | -1 to -4    | Attacking other plane  |
| Arcane Disrupt   | Penalty        | -2          | Under disruption       |
| Reality Anchor   | Void penalty   | -3          | Anti-Void effect       |

---

## Appendix B: Implementation Checklist

- [ ] Extend dice.ts with plane-specific modifiers
- [ ] Create cross-plane attack resolution module
- [ ] Implement synergy chain bonus calculations
- [ ] Build unit stacking validation system
- [ ] Create army composition analyzer
- [ ] Implement retreat mechanics
- [ ] Add terrain modifier lookup system
- [ ] Build siege resolution system
- [ ] Create mobility unit movement handlers
- [ ] Implement combat-to-Weave recording
- [ ] Add heroic deed extraction
- [ ] Build casualty narrative generation
- [ ] Create combat preview calculator
- [ ] Implement combat log display system
- [ ] Add tests for all combat edge cases

---

_Document created as part of The Veil War (Mode 1) game design for Veilborn
Chronicles._
