# Ability System — End-to-End Flow Reference This document maps the full lifecycle of abilities in SOR, from data definition through server processing to client targeting and visual feedback. Line numbers reference the codebase as of 2026-05-20. --- ## Table of Contents 1. [Ability Data Model](#1-ability-data-model) 2. [Ability Types](#2-ability-types) 3. [Server Entry Points by Ability Type](#3-server-entry-points-by-ability-type) 4. [Active Ability Flow](#4-active-ability-flow) 5. [Triggered Ability Flow](#5-triggered-ability-flow) 6. [Passive Ability Flow](#6-passive-ability-flow) 7. [Aura Ability Flow](#7-aura-ability-flow) 8. [Ruin Ability Flow](#8-ruin-ability-flow) 9. [ActionGroup Resolution](#9-actiongroup-resolution) 10. [Target Resolution](#10-target-resolution) 11. [Effect Execution](#11-effect-execution) 12. [Interactive Pause States](#12-interactive-pause-states) 13. [Cost Handling](#13-cost-handling) 14. [Duration and Effect Tracking](#14-duration-and-effect-tracking) 15. [Condition System](#15-condition-system) 16. [Filter System](#16-filter-system) 17. [Trigger System](#17-trigger-system) 18. [Network Message Flow](#18-network-message-flow) 19. [Client-Side Targeting](#19-client-side-targeting) 20. [Client Visual Effects](#20-client-visual-effects) 21. [Resume Paths (Paused Abilities)](#21-resume-paths-paused-abilities) 22. [Key Cross-File Connections](#22-key-cross-file-connections) 23. [Failure and Error Paths](#23-failure-and-error-paths) 24. [State Version and Delta Sync](#24-state-version-and-delta-sync) 25. [Trigger Re-entrancy and Ordering](#25-trigger-re-entrancy-and-ordering) 26. [Cost Atomicity and Rollback Semantics](#26-cost-atomicity-and-rollback-semantics) 27. [Known Caveats and Gotchas](#27-known-caveats-and-gotchas) 28. [Minimal JSON Examples](#28-minimal-json-examples) --- ## 1. Ability Data Model ### `AbilityDefinition` **File:** `Server/src/SOR.Game/Abilities/Models/AbilityDefinition.cs` lines 23–126 Root object stored as JSONB in `CardDefinition.AbilitiesJson` (array). All abilities on a card are parsed from this array at runtime. ```csharp // AbilityDefinition.cs line 23 public class AbilityDefinition { public AbilityType Type { get; init; } // Active | Passive | Aura | Triggered public ActionGroup? ActionGroup { get; init; } // line 31 — recursive AND/OR/XOR tree public Action[]? Actions { get; init; } // line 35 — legacy flat list (backward compat) public CostGroup? CostGroup { get; init; } // line 42 — AND/OR/XOR cost tree public CostEntry[]? Cost { get; init; } // line 46 — legacy flat costs public AbilityRange? Range { get; init; } // line 47 — min/max/LOS/linear constraints public int UsesPerTurn { get; init; } // line 49 — default 1 public int? AuraRange { get; init; } // line 52 — radius for Aura type public bool ClearOnLeave { get; init; } // line 58 — revert on leaving aura range public DurationModel? LingerDuration { get; init; } // line 63 — override when leaving public Action[]? OnEnterAuraActions { get; init; } // line 69 — fires per unit entering aura public Action[]? OnLeaveAuraActions { get; init; } // line 74 — fires per unit leaving aura public TriggerEvent? TriggerEvent { get; init; } // line 78 — which event fires this ability public int? TriggerLimitPerTurn { get; init; } // line 84 — max fires per turn public int? TriggerLimitPerGame { get; init; } // line 90 — max fires per game public string[]? SourceZoneGate { get; init; } // line 98 — zones source must be in (null = battlefield) public string Name { get; init; } // line 104 public string Description { get; init; } // line 110 public DurationModel? Duration { get; init; } // line 119 — ability-level duration override public AbilityAnimationDefinition? Animation { get; init; } // line 125 — client VFX metadata } ``` ### `AbilityType` enum **File:** `Models/AbilityDefinition.cs` lines 5–13 ```csharp public enum AbilityType { Active, Passive, Aura, Triggered } ``` ### `Action` **File:** `Server/src/SOR.Game/Abilities/Models/Action.cs` lines 82–95 Atomic targeting + effect unit. All effects in an action share the same target and duration. ```csharp public class Action { public TargetSelector Target { get; init; } public Condition[]? Conditions { get; init; } // Subject=="Target" → per-target filter; else → gate whole action public Effect[] Effects { get; init; } public DurationModel? Duration { get; init; } public ChooseOne? ChooseOne { get; init; } // when set, replaces Effects with branch selection } ``` ### `TargetSelector` **File:** `Models/Action.cs` lines 57–71 ```csharp public class TargetSelector { public string Scope { get; init; } // Hand | Deck | Discard | Battlefield | Player | AnyZone public string Type { get; init; } // Unit | ArchSpirit | Spirit | SpiritToken | Ruin | Tile | Card | Player public string Ownership { get; init; } // Self | ExactSelf | Owner | Ally | Enemy | Any | Random | Target public string? Chooser { get; init; } // Self | Opponent | Ally | Random — who picks from valid pool public TargetCount Count { get; init; } // { N, UpTo, All } public Filter[]? Filters { get; init; } } ``` ### `ActionGroup` **File:** `Models/Action.cs` lines 135–148 Recursive group allowing branching ability structures. ```csharp public class ActionGroup { public string Logic { get; init; } // And | Or | Xor public string? ChooserRole { get; init; } // Self | Opponent | Random (for Or/Xor) public ActionGroup[]? Groups { get; init; } // nested sub-groups public Action[]? Actions { get; init; } // leaf actions } ``` ### `AbilityRange` **File:** `Models/Action.cs` lines 231–245 ```csharp public class AbilityRange { public int Min { get; init; } public int Max { get; init; } public bool RequiresLos { get; init; } // line-of-sight check via LineOfSight.HasLos public bool LinearOnly { get; init; } // only cardinal/diagonal straight lines } ``` ### `CostEntry` / `CostGroup` **File:** `Models/Action.cs` lines 186–227 `CostType` values: `SpiritPoints`, `SacrificeTokens`, `DiscardFromHand`, `MillTopOfDeck`, `MillBottomOfDeck`, `SendSpiritFromBattlefieldToDiscard`, `DealDamageToOwnArchSpirit`, `DealDamageToOwnSpirit` `CostPickMode`: `Random`, `SelfPick`, `EnemySeePick`, `EnemyRandomPick`, `EnemyPick` --- ## 2. Ability Types | Type | Activation | Cost | Usage Tracking | |---|---|---|---| | `Active` | Player manually activates; checks `IsExhausted`, `CanUseAbility`, `AbilityUsesThisTurn` | SP / ST / card costs paid on activation | `AbilityUsesThisTurn` dictionary keyed by `abilityIndex` | | `Passive` | Applied automatically when unit enters battlefield; reverted on leave | None | `ActiveEffects` with `WhileSourceOnBattlefield` duration | | `Aura` | Always-on; re-evaluated on unit move/enter/leave events | None | `ActiveEffects` tracks buffs; `ClearOnLeave` / `LingerDuration` govern expiry | | `Triggered` | Fires inline when matching `TriggerEvent` occurs via `FireTrigger()` | None | `_triggerCountsPerTurn` / `_triggerCountsPerGame` static dicts keyed by `(instanceId, abilityName, turn)` | --- ## 3. Server Entry Points by Ability Type | Ability Type | Entry Point | File | Line | |---|---|---|---| | Active | `AbilitySystem.ActivateAbility()` | `AbilitySystem.cs` | 85 | | Active (card effect) | `AbilitySystem.FireCardEffects()` | `AbilitySystem.cs` | 160 | | Triggered | `AbilitySystem.FireTrigger()` | `AbilitySystem.cs` | 256 | | Ruin | `AbilitySystem.FireRuinAbilities()` | `AbilitySystem.cs` | 458 | | Passive (enter) | `AbilitySystem.ApplyPassivesForSource()` | `AbilitySystem.cs` | 5090 | | Passive (new target) | `AbilitySystem.ApplyPassivesToNewTarget()` | `AbilitySystem.cs` | 5116 | | Passive (leave) | `AbilitySystem.RevokePassivesForSource()` | `AbilitySystem.cs` | 5142 | | Aura (enter) | `AbilitySystem.EvaluateAurasOnEnter()` | `AbilitySystem.cs` | 5276 | | Aura (leave) | `AbilitySystem.EvaluateAurasOnLeave()` | `AbilitySystem.cs` | 5369 | | Aura (move) | `AbilitySystem.EvaluateAuraTransitions()` | `AbilitySystem.cs` | 5221 | --- ## 4. Active Ability Flow **Handler:** `Server/src/SOR.Game/Handlers/GameActivateAbilityHandler.cs` line 35 **Engine:** `AbilitySystem.ActivateAbility()` — `AbilitySystem.cs` line 85 ### Step-by-step ``` Client → "game.activate_ability" { SourceInstanceId, AbilityIndex, Targets[] } ``` 1. **Locate source** — find unit on `player.Field` or `player.ArchSpirit` (line 90–102) 2. **Validate IsExhausted** — unit must not be exhausted (line 104) 3. **Validate CanUseAbility** — flag must be true (line 107) 4. **Parse abilities** — `ParseAbilities(source.AbilitiesJson)` (line 110) 5. **Bounds check** — `abilityIndex` within array range (line 113) 6. **Type check** — `def.Type == AbilityType.Active` (line 116) 7. **DisabledAbilities check** — ability must not be in `source.DisabledAbilities` (line 119) 8. **UsesPerTurn enforcement** — compare `AbilityUsesThisTurn[abilityIndex]` vs `def.UsesPerTurn` (line 122) 9. **Build AbilityContext** — `new AbilityContext(state, actorId, source)` (line 128) 10. **`ValidateSourceActivationConditions()`** — non-Target conditions gate activation (line 131) 11. **`PreValidateClientTileTargets()`** — validate tile picks before paying cost (lines 203–249) 12. **Increment AbilityUsesThisTurn** — `AbilityUsesThisTurn[abilityIndex]++` (line 138) 13. **`GetEffectiveActions()`** — resolve ActionGroup or fall back to legacy Actions; returns `null` when paused for OR/XOR pick (line 141) 14. **`PayCostGroup()` / `PayCosts()`** — pay ability cost; may pause for interactive cost pick (line 144) 15. **`ExecuteActions()`** — full execution pipeline (line 152) ### After execution ``` → SaveStateAsync() + PushStateToPlayersAsync() → PushPendingPromptsAsync() (GameHandlerBase.cs line 400) → Server broadcasts "game.activate_ability.ack" { GameStateDto } ``` If `ability.Animation?.AssetUrl` is null/empty, `GameActivateAbilityHandler` (lines 63–88) computes `AbilityPlaceholderVisualPush` with `TargetMode` and broadcasts `"game.visual.ability_placeholder"`. --- ## 5. Triggered Ability Flow **Entry:** `AbilitySystem.FireTrigger(GameState state, TriggerOccurrence occurrence)` — `AbilitySystem.cs` line 256 `FireTrigger` is called inline by game engine methods whenever a relevant game event occurs (unit death, damage dealt, card channeled, etc.). ### Per-card, per-ability loop ``` For each player → For each card on battlefield (+ SourceZoneGate zones): ``` 1. **`CanUseAbility == false`** → skip (line 270) 2. **`TriggerMatches()`** — match event kind, ownership constraints, filters (line 275) 3. **Ruin double-fire guard** — skip source Ruin on `RuinActivation` (lines 303–309) 4. **`ActivationConditions` check** (line 312) 5. **TriggerLimitPerTurn** — dict key: `(instanceId, abilityName, turnNumber)` (line 318) 6. **TriggerLimitPerGame** — dict key: `(instanceId, abilityName)` (line 330) 7. **`GetEffectiveActions()`** — resolve ActionGroup (line 340) 8. **`ActionNeedsClientTargets()`** — if true, store `PendingTriggeredTarget` and return immediately (lines 350–360) 9. **`ExecuteActions()`** — direct execution for auto-resolved abilities (line 365) 10. **`PendingDeferredEffects`** processing — apply `ApplyOnEventEffect` deferreds (lines 387–435) ### `TriggerOccurrence` **File:** `AbilityContext.cs` line 119 ```csharp public record TriggerOccurrence( TriggerEventKind Kind, string ActorId, // unit/player that caused the event object? Data, // event-specific payload string? UnitType, CardType? CardType ); ``` ### `TriggerEventKind` enum **File:** `AbilityContext.cs` line 84 — 24 values mirroring the Trigger model types. --- ## 6. Passive Ability Flow ### On unit enter battlefield ``` EvaluateAurasOnEnter() (line 5276) ApplyPassivesForSource() (line 5090) ← all passive abilities from new unit → all existing units ApplyPassivesToNewTarget() (line 5116) ← all existing units' passives → new unit only ``` **`ApplyPassivesForSource()`** — line 5090: - Executes all `AbilityType.Passive` abilities from the source against all battlefield units - Duration: `WhileSourceOnBattlefield` (or `def.Duration` if overridden) **`ApplyPassivesToNewTarget()`** — line 5116: - All other battlefield units' passives applied with `restrictTargets = [newUnit]` ### On unit leave battlefield **`RevokePassivesForSource()`** — line 5142: - Finds all `WhileSourceOnBattlefield` effects where `SourceInstanceId` matches the departing unit - Calls `ApplyReversal()` for each tracked effect ### Re-evaluation (conditional passives) **`ReEvaluateConditionalPassives()`** — line 5173: - Full revoke-then-reapply for units with `ActivationConditions` on their passives - Called after: unit moves, affinity changes, ability activations — anything that could invalidate conditions --- ## 7. Aura Ability Flow ### On unit move **`EvaluateAuraTransitions()`** — line 5221: - Part 1: stationary aura sources — compare moving unit's old vs. new position against each aura source's radius - Part 2: moving unit's own auras — compare each stationary unit against old vs. new aura radius - Calls `FireAuraTransition(wasIn, isIn)` for each state change ### On unit enter battlefield **`EvaluateAurasOnEnter()`** — line 5276: - Check all existing aura sources: is new unit within range? → `FireAuraTransition(false, true)` - Check new unit's own auras: is each existing unit within range? → `FireAuraTransition(false, true)` ### On unit leave battlefield **`EvaluateAurasOnLeave()`** — line 5369: - Before removal: fire `FireAuraTransition(wasIn: true, isIn: false)` for all in-range aura sources ### `ApplyAuraEffects()` — line 5416 Executes aura's action list on a target unit with `WhileSourceOnBattlefield` duration (or `def.Duration`). `restrictTargets` = the entering unit only. ### `ClearOnLeave` / `LingerDuration` - `ClearOnLeave == true` (default): aura effects reverted immediately when unit leaves range - `LingerDuration`: instead of immediate revoke, the tracked effect's duration is switched to `LingerDuration` ### `ReapplyAurasAtTurnStart()` — line 5326 - Strips stale tracked effects for active-player units **without** reversal (stats already reset by turn-start) - Re-applies fresh aura effects for all currently in-range units --- ## 8. Ruin Ability Flow **`FireRuinAbilities()`** — `AbilitySystem.cs` line 458 Called at start of each turn. Steps: 1. For each Ruin with an occupant (Spirit / ArchSpirit / SpiritToken): - Find all eligible `OnRuinActivationTrigger` abilities on the occupant - Pick **one at random** from eligible abilities - Execute that ability via `ExecuteActions()` 2. `FireTrigger(TriggerEventKind.RuinActivation)` — notify observer cards of the ruin activation The double-fire guard in `FireTrigger` (lines 303–309) prevents the source Ruin from re-triggering its own activation. --- ## 9. ActionGroup Resolution **`GetEffectiveActions()`** — `AbilitySystem.cs` line 981 (entry point) Resolves the `ActionGroup` tree into a flat list of `Action` objects. Returns `null` when paused waiting for player input. ``` GetEffectiveActions() → if def.ActionGroup != null: ResolveActionGroup(def.ActionGroup, ctx) → else: return def.Actions (legacy flat list) ``` **`ResolveActionGroup()`** — line 999: ``` AND group: → flatten all leaf Actions from each child → recurse into nested ActionGroups → return combined list OR/XOR + Random chooser: → server picks one child at random → return that child's actions OR/XOR + Self/Opponent chooser: → store PendingActionGroupPick on GameState → return null (execution paused) ``` **`ResumeActionGroupPick()`** — line 1081: - Called by `GameActionGroupPickHandler` when player responds - Validates player choice index; retrieves chosen group's actions - Continues `ExecuteActions()` with resolved action list --- ## 10. Target Resolution **`ResolveTargets()`** — `AbilitySystem.cs` line 1924 Converts `TargetSelector` + client-provided target IDs into a concrete list of `TargetRef` objects. ### Player targets (line 1928) Direct ownership lookup — `Owner`, `Enemy`, or `Target` (relay from prior action's resolved target). ### Tile targets (line 1940) - `All == true` → enumerate entire board - Otherwise → client-provided coordinates ### Unit targets (line 1950+) ``` BuildCandidates() (line 2125) → expand by TargetScope, filter by TargetType ↓ Apply ExactSelf restriction ↓ Apply restrictTargets (passive/aura re-evaluation path) ↓ Apply Filter[] (per-filter evaluation) ↓ Random chooser path → server selects random from candidates ↓ Client-provided IDs → validate each against candidates ↓ FilterTargetsByAbilityRange() (line 2067) → Manhattan distance + LinearOnly + LOS ↓ Count enforcement → exactly N, up-to N, or all ``` **`BuildCandidates()`** — line 2125: - Expands by `TargetScope` across owner IDs (Self / Ally / Enemy / Any) - Filters by `TargetType` (Unit / ArchSpirit / Spirit / SpiritToken / Ruin) **`FilterTargetsByAbilityRange()`** — line 2067: - Manhattan distance check: `source.Coord.ManhattanDistance(target.Coord)` within `[Min, Max]` - `LinearOnly`: validates target lies on same row, column, or diagonal - `RequiresLos`: calls `LineOfSight.HasLos(source.Coord, target.Coord, board)` **`IsTargetInAbilityRange()`** — line 2083: - Per-target check used for individual validation --- ## 11. Effect Execution **`ExecuteActions()`** — `AbilitySystem.cs` line 1659 (private) ``` _sequenceDepth++ for each action in actions: ExecuteSingleAction(action, ctx) if state.HasPendingInteraction() → break immediately _sequenceDepth-- if _sequenceDepth == 0: ExpireEndOfSequenceEffects() ``` **`ExecuteSingleAction()`** — line 1691 (private): ``` 1. Handle ChooseOne (random/opponent-pause/client-index) 2. Evaluate source-level Conditions (Subject != "Target") 3. Detect Opponent/Ally Chooser with no client targets → store PendingTargetPick, return 4. ResolveTargets() → build candidate list 5. Per-target: filter Conditions where Subject == "Target" 6. For each effect in action.Effects: ExecuteEffect(effect, target, duration, ctx) if HasPendingInteraction() → stop ``` **`ExecuteEffect()`** dispatches on `effect` type. The complete switch covers 60+ effect subtypes defined in `Models/Effects.cs`. ### Effect categories | Category | Examples | Lines in Effects.cs | |---|---|---| | Stat modification | `ModifyHealthEffect`, `ModifyDefenseEffect`, `ModifyDamageEffect`, `ModifyMPEffect` | 139–151 | | Flag modification (unit) | `SetCanMove`, `SetCanAttack`, `SetCanDefend`, `SetCanBeAttacked`, `SetCanUseAbility` | 155–165 | | Flag modification (player) | `SetCanDrawCards`, `SetAccumulatesSP`, `SetCanChannelSpirit`, `SetCanAscendArchSpirit` | 166–177 | | Ability modification | `AddAbilityEffect`, `RemoveAbilityEffect`, `EnableAbilityEffect`, `DisableAbilityEffect` | 182–185 | | Genus / SP / ST | `AddGenusEffect`, `ModifySPEffect`, `ModifySTEffect`, `ModifySPAccumulationEffect` | 189–197 | | Tile modification | `SetBaseAffinity1Effect`, `PushAffinityEffect`, `PushFinalAffinityEffect` | 201–204 | | Zone / card operations | `DrawCardsEffect`, `DiscardCardsEffect`, `ReturnToHandEffect`, `SearchDeckEffect`, `PlaceOnDeckEffect` | 208–232 | | Combat / damage | `DealDamageEffect`, `HealEffect`, `DOTEffect`, `HOTEffect`, `PreventDeathEffect`, `PreventNextDamageEffect` | 236–256 | | Displacement | `PushUnitEffect`, `PullUnitEffect`, `DisplaceUnitEffect`, `RepositionUnitEffect` | 260–288 | | Control / token / summoning | `TakeControlEffect`, `SummonTokenEffect`, `CloneSpiritAsTokenEffect`, `DestroyTokenEffect` | 292–330 | | Misc / complex | `ApplyOnEventEffect`, `StackDeckEffect`, `SkipTurnEffect`, `ChangeAttackTypeEffect`, `RelocateRuinEffect` | 334–458 | --- ## 12. Interactive Pause States All pause states are fields on `GameState` (`GameState.cs` lines 94–169). **`HasPendingInteraction()`** — `GameState.cs` line 161: returns `true` if any pending field is non-null. Checked at every iteration of `ExecuteActions()` and `ExecuteSingleAction()` — stops execution immediately when set. | Pending State | File | Cause | Resume Handler | |---|---|---|---| | `PendingTriggeredTarget` | `Models/PendingTriggeredTarget.cs` | Triggered ability needs client target picks | `GameTriggeredTargetHandler` | | `PendingTargetPick` | `Models/PendingTargetPick.cs` | Opponent/Ally chooser needs to pick targets | `GameTargetPickHandler` | | `PendingActionGroupPick` | `Models/PendingActionGroupPick.cs` | OR/XOR ActionGroup needs player choice | `GameActionGroupPickHandler` | | `PendingBranchPick` | `Models/PendingBranchPick.cs` | ChooseOne branch selection | `GameBranchPickHandler` | | `PendingCostPick` | `Models/PendingCostPick.cs` | Interactive cost selection | `GameCostPickHandler` | | `PendingCostGroupPick` | `Models/PendingCostGroupPick.cs` | OR/XOR cost group choice | `GameCostGroupPickHandler` | | `PendingTilePick` | `Models/PendingTilePick.cs` | Tile destination pick | `GameTilePickHandler` | | `PendingPlayerPick` | `Models/PendingPlayerPick.cs` | Player selection | `GamePlayerPickHandler` | | `PendingRevealChoicePick` | `Models/PendingRevealChoicePick.cs` | StackDeck ordering | `GameRevealChoicePickHandler` | --- ## 13. Cost Handling **`PayCostGroup()`** — `AbilitySystem.cs` — handles AND/OR/XOR cost trees; may pause via `PendingCostGroupPick`. **`PayCosts()`** — handles flat `CostEntry[]`; may pause via `PendingCostPick` when `CostPickMode` requires player input. ### CostType behaviors | CostType | What happens | |---|---| | `SpiritPoints` | Deduct SP from activating player | | `SacrificeTokens` | Remove spirit tokens from battlefield | | `DiscardFromHand` | Player discards N cards from hand | | `MillTopOfDeck` | Remove N cards from top of deck | | `MillBottomOfDeck` | Remove N cards from bottom of deck | | `SendSpiritFromBattlefieldToDiscard` | Move spirit to discard zone | | `DealDamageToOwnArchSpirit` | Deal N damage to own ArchSpirit | | `DealDamageToOwnSpirit` | Deal N damage to own spirit | ### CostPickMode | Mode | Who selects | |---|---| | `Random` | Server picks randomly | | `SelfPick` | Activating player picks | | `EnemySeePick` | Enemy picks (activating player can see) | | `EnemyRandomPick` | Enemy picks randomly | | `EnemyPick` | Enemy picks (blind) | --- ## 14. Duration and Effect Tracking ### `DurationType` enum **File:** `Models/DurationModel.cs` lines 7–29 | Value | When the effect expires | |---|---| | `Instant` | Never tracked; applied once, not tracked | | `UntilEndOfTurn` | End of current turn | | `UntilStartOfOwnerTurn` | Start of the affected unit's owner's turn | | `UntilStartOfSourceOwnerTurn` | Start of the ability source owner's turn | | `ForNTurns` | After N full turns | | `UntilEndOfSequence` | When `_sequenceDepth` returns to 0 | | `WhileCondition` | While a named condition evaluates true | | `WhileSourceOnBattlefield` | While the source unit is on the battlefield | | `PermanentInMatch` | Never expires during the match | ### `TrackEffect()` — `AbilitySystem.cs` line 4764 Stores reversal as an `ActiveEffect` in `state.ActiveEffects`: - `SourceInstanceId`, `TargetRef`, `EffectJson` (reversal effect), `DurationJson` (TrackedDuration) - No-op for `Instant` or `PermanentInMatch` (not tracked) ### `TrackTick()` — line 4792 Stores DOT/HOT as an `ActiveEffect` with `IsTick = true`. Ticks fire on each turn boundary. ### `ApplyReversal()` — line 5038 Calls `ExecuteEffect(reversalEffect, target, duration: null, ctx)` to undo the tracked effect. ### `ExpireEndOfSequenceEffects()` — line 5008 Runs when `_sequenceDepth` reaches 0 — cleans up all `UntilEndOfSequence` tracked effects. ### `LabelFromReversal()` — line 4821 Generates human-readable display labels (e.g. `"ATK +2"`, `"Rooted"`) shown on the client's active effects HUD. --- ## 15. Condition System **File:** `Server/src/SOR.Game/Abilities/Models/Conditions.cs` Abstract base `Condition` with `Subject` property (`"Self"` or `"Target"`) — line 68–76. Conditions with `Subject == "Target"` are evaluated per-target in `ExecuteSingleAction()`. All others gate the entire action. ### Composite `AndCondition`, `OrCondition`, `XorCondition`, `NotCondition` ### Unit conditions `HealthBelowCondition`, `HealthAboveCondition`, `DefenseIsCondition`, `HasGenusCondition`, `HasAbilityCondition`, `IsOnTileWithAffinityCondition`, `IsAdjacentToCondition`, `WithinRangeOfCondition`, `MovementTypeIsCondition`, `DestinationTileAffinityIsCondition`, `PreviousTileAffinityIsCondition`, `MovedFromOrIntoAffinityCondition`, `IsAdjacentToTileWithAffinityCondition`, `IsOnOrAdjacentToTileWithAffinityCondition`, `IsCurrentlyMovingCondition` ### Player conditions `SPAtLeastCondition`, `SPAtMostCondition`, `STAtLeast/AtMostCondition`, `HandSizeAtLeast/AtMostCondition`, `DeckSizeAtLeastCondition`, `DiscardSizeAtLeastCondition` ### Tile conditions `TileAffinityMatchesCondition`, `TileIsOccupiedCondition`, `TileIsUnoccupiedCondition` ### Turn / timing conditions `IsOwnTurnCondition`, `IsOpponentTurnCondition`, `IsAllyTurnCondition`, `IsActivePlayerTurnCondition` ### Battlefield conditions `UnitCountOnBattlefieldCondition`, `CardInZoneCondition`, `ControlledTileCountWithAffinityCondition` ### Extended unit conditions `UnitTypeIsCondition`, `OwnershipIsCondition`, `IsThisCardCondition`, `UnitPropertyCompareCondition`, `PlayerPropertyCompareCondition`, `HandContainsCountCondition`, `CardDefinitionCountInZoneCondition`, `IsInRangeOfUnitCondition`, `TileOccupantCondition`, `SurroundingTileCondition`, `SPAccumulationCompareCondition`, `CostOfCardsInHandCondition` --- ## 16. Filter System **File:** `Server/src/SOR.Game/Abilities/Models/Filters.cs` Abstract base `Filter` — line 42. Used in `TargetSelector.Filters`, `CostEntry.Filters`, and many effect fields (e.g. `RepositionUnitEffect.TileFilters`). ### Unit / card filters `GenusContainsFilter`, `AffinityMatchesFilter`, `HealthBelowFilter`, `HealthAboveFilter`, `DamageRangeFilter`, `DefenseRangeFilter`, `MPRangeFilter`, `HasFlagFilter`, `TierIsFilter`, `IsAdjacentToSourceFilter`, `CardTypeIsFilter`, `CardSPCostRangeFilter`, `CardSTCostRangeFilter`, `WithinRangeFilter`, `IsSelfFilter`, `IsExactSelfFilter`, `IsAdjacentToUnitMatchingFilter`, `IsAdjacentToTileMatchingFilter` ### Tile filters `TileAffinityMatchesFilter`, `TileIsOccupiedFilter`, `TileIsUnoccupiedFilter`, `TileWithinRangeFilter`, `TileIsAdjacentToUnitFilter`, `TileIsOnPlayerSideFilter`, `TileIsInArchSpiritChannelRangeFilter` ### Generic filters `OwnershipFilter`, `UnitPropertyFilter` (PropertyName + Comparator + Value), `TileOccupancyFilter` (UnitType + Ownership + nested UnitFilters) --- ## 17. Trigger System **File:** `Server/src/SOR.Game/Abilities/Models/Triggers.cs` Abstract base `TriggerEvent` — line 64. All matched via `TriggerMatches()` in `AbilitySystem.cs`. ### Trigger categories | Category | Trigger Types | |---|---| | Turn phase | `OnTurnStartTrigger`, `OnTurnEndTrigger` | | Channeling | `OnChanneledTrigger` (CardType, Ownership, CardDefinitionId) | | ArchSpirit tiers | `OnAscendTrigger`, `OnTransitionTrigger` | | Unit actions | `OnUnitMoveTrigger`, `OnUnitAttackTrigger`, `OnUnitAbilityActivatedTrigger`, `OnUnitMPSpentTrigger` | | Damage | `OnDamageDealtTrigger`, `OnDamagePreventedTrigger`, `OnHealedTrigger`, `BeforeUnitDeathTrigger`, `BeforeDamageAppliedTrigger` | | Unit lifecycle | `OnUnitEnterBattlefieldTrigger`, `OnUnitLeaveBattlefieldTrigger`, `OnUnitDeathTrigger`, `OnUnitSentToDiscardTrigger`, `OnSpiritSacrificedTrigger`, `OnTokenSummonedTrigger` | | State changes | `OnStatModifiedTrigger`, `OnAbilityAddedTrigger`, `OnAbilityRemovedTrigger`, `OnGenusChangedTrigger` | | Ruin | `OnRuinActivationTrigger`, `OnUnitOccupyRuinTrigger` | | Tile | `OnTileAffinityChangedTrigger` | | Resources | `OnSPGainedTrigger`, `OnSPSpentTrigger`, `OnSTGainedTrigger`, `OnSTSpentTrigger` | | Card zone | `OnCardDrawnTrigger`, `OnCardDiscardedTrigger`, `OnCardReturnedToHandTrigger`, `OnCardReturnedToDeckTrigger`, `OnDeckShuffledTrigger`, `OnCardsRevealedTrigger` | | Effect lifecycle | `OnTargetedByAbilityTrigger`, `OnEffectAppliedTrigger`, `OnEnterAuraRangeTrigger`, `OnLeaveAuraRangeTrigger` | --- ## 18. Network Message Flow ### Active ability activation ``` Client → server: "game.activate_ability" Payload: { SessionId, SourceInstanceId, AbilityIndex, Targets[] } GameActivateAbilityHandler.HandleAsync() (GameActivateAbilityHandler.cs line 35) → GameEngine.ActivateAbility() → AbilitySystem.ActivateAbility() (AbilitySystem.cs line 85) → [execute or pause with Pending* field] → SaveStateAsync() + PushStateToPlayersAsync() → PushPendingPromptsAsync() (GameHandlerBase.cs line 400) Server → client: "game.activate_ability.ack" Payload: { GameStateDto } Optional: "game.visual.ability_placeholder" (when no custom animation asset) Payload: { SourceId, TargetMode, TargetCoords, AffinityColor } ``` ### Triggered ability needing targets ``` Server → client: "game.ability.triggered_target_request" Payload: { RequestId, SourceInstanceId, AbilityName, ActionJson, RangeJson } Client → server: "game.triggered_target" Payload: { SessionId, RequestId, Targets[] } GameTriggeredTargetHandler.HandleAsync() (GameTriggeredTargetHandler.cs line 37) → AbilitySystem.ResumeTriggeredAbility() (AbilitySystem.cs line 1874) Server → client: "game.triggered_target.ack" + full state push ``` ### Interactive prompts pushed by `PushPendingPromptsAsync()` — `GameHandlerBase.cs` line 400 | Pending State | Message sent to client | |---|---| | `PendingTriggeredTarget` | `"game.ability.triggered_target_request"` | | `PendingCostPick` | `"game.ability.cost_pick_request"` | | `PendingCostGroupPick` | `"game.ability.cost_group_pick_request"` | | `PendingActionGroupPick` | `"game.ability.action_group_pick_request"` | | `PendingBranchPick` | `"game.ability.branch_pick_request"` | | `PendingTargetPick` | `"game.ability.target_pick_request"` | | `PendingTilePick` | `"game.ability.tile_pick_request"` | | `PendingPlayerPick` | `"game.ability.player_pick_request"` | | `PendingRevealChoicePick` | `"game.ability.reveal_choice_pick_request"` | --- ## 19. Client-Side Targeting **File:** `Client/origin-client/scenes/game/components/selection/ability_targeting.gd` ### State variables (lines 30–56) ```gdscript var ability_unit_id # source unit ID var ability_idx # ability index on source unit var ability_def # normalized action array from parsed JSON var ability_range # { min, max, linearonly, requireslos } var ability_targets # collected AbilityTarget dicts to send to server var ability_cur_action_idx # current action index being targeted var is_triggered_target # triggered ability path var triggered_request_id var is_target_pick # server-driven target pick path var is_tile_pick var pending_req_id ``` ### Key methods **`show_ability_panel(unit_id, unit)`** — line 74: - Parses `abilitiesJson`, collects Active abilities - Adds ArchSpirit actions (Sacrifice / Ascend / Transition) if applicable - Builds `PanelContainer` with buttons; checks `abilityUsesThisTurn` vs `usesPerTurn` to grey out exhausted abilities **`start_ability_targeting()`** — line 261: Entry point after user clicks an ability button. Walks actions sequentially: ``` for each action in ability_def.actions: if ChooseOne → show_branch_panel() elif scope in ["Player","Hand","Deck","Discard","AnyZone"] → show_player_panel() elif ownership in [Self, ExactSelf, Random, Target] or All==true → skip, advance else → board selection mode: highlight_ability_targets(action) wait for user click ``` **`highlight_ability_targets(action)`** — line 326: ``` Tile type: for each tile on board: check TileFilter (incl. SummonToken.tileFilter) check range, LOS → emit highlight_add_requested Unit type: collect enemy/friendly units filter by: type, ownership, filter[], range, LOS → emit highlights ``` **`is_valid_board_target(coord, unit_id)`** — line 407: - Validates a specific click against the current action's constraints - Checks: type match, ownership, filters, range (Manhattan + LinearOnly + LOS), count limits **`send_ability()`** — line 679: - Triggered path → `Game.send_triggered_target_response(rid, targets)` - Target pick path → `Game.send_target_pick_response(rid, targets)` - Card play → `Game.send_play_card_with_targets(card_id, targets)` - Normal ability → `Game.send_activate_ability(unit_id, idx, targets)` **`on_triggered_target_request(req)`** — line 699: - Handles server push for triggered abilities needing targets - Normalizes action JSON; calls `start_ability_targeting()` **`get_ability_actions(ab)`** — line 856: - Extracts flat action list from legacy `actions` or `actiongroup` - Flattens AND groups via `flatten_and_group()` **`normalize_keys(value)`** — line 841: - Recursively lowercases all Dictionary keys - Handles case inconsistencies from server JSON serialization ### Client targeting flow ``` Player clicks unit → show_ability_panel() display ability buttons with availability Player clicks ability button → start_ability_targeting() walk actions, determine target mode For board-targeted actions: → highlight_ability_targets() highlight valid cells Player clicks a cell/unit → is_valid_board_target() validate click → collect into ability_targets → advance to next action or send_ability() For zone-targeted actions: → show_player_panel() show hand/deck/discard UI Player selects card → collect into ability_targets → advance to next action or send_ability() send_ability() → Game.send_activate_ability(unit_id, idx, targets) → server processes; state pushed back ``` --- ## 20. Client Visual Effects **File:** `Client/origin-client/scenes/game/components/effects/ability_placeholder_fx.gd` Triggered when server sends `"game.visual.ability_placeholder"` (no custom animation asset present). Dispatches by `targetMode` field: | targetMode | Effect | |---|---| | `"Self"` / `"None"` | `_play_self_burst()` — expanding rings + radial motes at source position | | `"Unit"` | `_spawn_projectile()` — orb travels from source to target unit's body position | | `"Tile"` | `_spawn_projectile()` — orb travels to tile world coordinate | | `"PlayerZone"` | `_spawn_projectile()` — orb travels to target player's ArchSpirit | Visual details: - Uses affinity color from `GameConstants.AFFINITY_COLORS` - Uses player team color for differentiation - All meshes created procedurally: `SphereMesh` orbs, `TorusMesh` rings - Materials: emissive `StandardMaterial3D` --- ## 21. Resume Paths (Paused Abilities) When `HasPendingInteraction()` is true, execution is suspended. The corresponding handler resumes it after client responds. | Handler File | Server Resume Method | Line | Resumes | |---|---|---|---| | `GameTriggeredTargetHandler.cs` | `ResumeTriggeredAbility()` | 1874 | `PendingTriggeredTarget` | | `GameTargetPickHandler.cs` | `ResumeTargetPick()` | 1610 | `PendingTargetPick` | | `GameActionGroupPickHandler.cs` | `ResumeActionGroupPick()` | 1081 | `PendingActionGroupPick` | | `GameBranchPickHandler.cs` | `ResumeBranchPick()` | 933 | `PendingBranchPick` | | `GameCostPickHandler.cs` | `ResumeCostPick()` | 822 | `PendingCostPick` | | `GameCostGroupPickHandler.cs` | `ResumeCostGroupPick()` | 686 | `PendingCostGroupPick` | | `GameTilePickHandler.cs` | `ResumeTilePick()` | 1280 | `PendingTilePick` | | `GamePlayerPickHandler.cs` | `ResumePlayerPick()` | 1434 | `PendingPlayerPick` | | `GameRevealChoicePickHandler.cs` | `ResumeRevealChoicePick()` | 1199 | `PendingRevealChoicePick` | All resume methods follow the same pattern: 1. Validate the `RequestId` matches the stored pending state 2. Validate player identity (only the correct player can respond) 3. Apply the player's choice to `AbilityContext` / `GameState` 4. Clear the `Pending*` field 5. Re-enter `ExecuteActions()` with remaining actions --- ## 22. Key Cross-File Connections ``` GameActivateAbilityHandler (Handlers/) → GameEngine.ActivateAbility() → AbilitySystem.ActivateAbility() (AbilitySystem.cs:85) AbilitySystem.ActivateAbility() → ValidateSourceActivationConditions() → PreValidateClientTileTargets() → GetEffectiveActions() → ResolveActionGroup() → PayCostGroup() / PayCosts() → ExecuteActions() → ExecuteSingleAction() → ResolveTargets() → BuildCandidates() → FilterTargetsByAbilityRange() → ExecuteEffect() (per effect type) → TrackEffect() (non-instant/non-permanent) GameHandlerBase.PushPendingPromptsAsync() ← called after EVERY state mutation → pushes interactive prompts to clients for all Pending* fields GameState.HasPendingInteraction() ← checked at every loop iteration in ExecuteActions() → stops execution when any Pending* field is set Passive/Aura enter sequence (always in this order): EvaluateAurasOnEnter() (AbilitySystem.cs:5276) ApplyPassivesForSource() (AbilitySystem.cs:5090) ApplyPassivesToNewTarget()(AbilitySystem.cs:5116) ActiveEffects list on GameState ← persistence layer for all non-Instant, non-Permanent tracked effects ← decremented/expired during EndTurn processing AbilityContext (AbilityContext.cs) ← shared runtime carrier throughout entire execution chain Fields: State, ActorId, Source, ResolvedTargets, EventData, ContinuationActions, ActivationRange ``` --- ## File Index | File | Role | |---|---| | `Server/src/SOR.Game/Abilities/AbilitySystem.cs` | Core engine — all ability parsing, execution, targeting, effect application (~5500+ lines) | | `Server/src/SOR.Game/Abilities/AbilityContext.cs` | Runtime context; `TriggerEventData`; `TriggerEventKind` enum | | `Server/src/SOR.Game/Abilities/Models/AbilityDefinition.cs` | Top-level data model | | `Server/src/SOR.Game/Abilities/Models/Action.cs` | `Action`, `TargetSelector`, `ActionGroup`, `CostEntry`, `CostGroup`, `AbilityRange`, `ValueExpr` | | `Server/src/SOR.Game/Abilities/Models/Effects.cs` | All 60+ concrete `Effect` subclasses | | `Server/src/SOR.Game/Abilities/Models/Conditions.cs` | All `Condition` subclasses (~35 types) | | `Server/src/SOR.Game/Abilities/Models/Triggers.cs` | All `TriggerEvent` subclasses (~40 types) | | `Server/src/SOR.Game/Abilities/Models/Filters.cs` | All `Filter` subclasses (~25 types) | | `Server/src/SOR.Game/Abilities/Models/DurationModel.cs` | `DurationType` enum + `DurationModel` class | | `Server/src/SOR.Game/Abilities/EffectPolymorphicConverter.cs` | JSON polymorphic deserializer for `Effect` | | `Server/src/SOR.Game/Handlers/GameActivateAbilityHandler.cs` | `game.activate_ability` message handler | | `Server/src/SOR.Game/Handlers/GameTriggeredTargetHandler.cs` | `game.triggered_target` message handler | | `Server/src/SOR.Game/Handlers/GameTargetPickHandler.cs` | `game.target_pick` message handler | | `Server/src/SOR.Game/Handlers/GameHandlerBase.cs` | Shared handler infrastructure + `PushPendingPromptsAsync` | | `Server/src/SOR.Game/GameState.cs` | `GameState` (all pending pause fields), `PlayerState`, `CardInstance` | | `Client/origin-client/scenes/game/components/selection/ability_targeting.gd` | Full client targeting UI state machine | | `Client/origin-client/scenes/game/components/effects/ability_placeholder_fx.gd` | VFX for abilities without custom animations | | `Client/origin-client/scenes/collection/components/ability_row.gd` | UI row for displaying ability info in collection | --- ## 23. Failure and Error Paths All server-side validation failures throw `GameException(string code)` — a plain `Exception` subclass defined in `GameEngine.cs:1740–1743` with an `ErrorCode` string property. ### Exception propagation to client `GameException` propagates up through the handler into `NatsMessageRpcResponder.DispatchAsync` (line 206), which catches all exceptions generically and returns: ```json { "errorCode": "INTERNAL_ERROR", "message": "An internal error occurred." } ``` **The specific `ErrorCode` is NOT forwarded to the client.** It is only logged server-side. The Gateway delivers this as `ServerMessage.Error(seq, errorCode, message)` over WebSocket. `GameActivateAbilityHandler` has no try/catch of its own — it relies entirely on this outer layer. ### Active ability activation errors | Check | Line | Error Code | |---|---|---| | `source.IsExhausted` | 100–101 | `UNIT_EXHAUSTED` | | `!source.CanUseAbility` | 103–104 | `UNIT_CANNOT_USE_ABILITY` | | `abilityIndex` out of bounds | 107–108 | `ABILITY_INDEX_OUT_OF_RANGE` | | `def.Type != Active` | 113 | `ABILITY_NOT_ACTIVE` | | ability in `DisabledAbilities` | 116 | `ABILITY_DISABLED` | | `AbilityUsesThisTurn >= UsesPerTurn` | 121 | `ABILITY_USES_EXHAUSTED` | | source-level conditions not met | 127 | `ABILITY_CONDITION_NOT_MET` | ### Target validation errors | Check | Line | Error Code | |---|---|---| | Client-picked target outside ability range | 2041 | `TARGET_OUT_OF_RANGE` | | Not enough candidates after filtering | 2059 | `INSUFFICIENT_TARGETS` | | Invalid tile for summon/placement effects | 231, 235, 245, 1315, 1364, 2901 | `INVALID_TILE` | ### Resume handler errors (stale / mismatched RequestId) All resume methods follow the same guard pattern — check pending state exists, then check RequestId matches, then check actor identity: | Resume Method | Line | Error Codes (in order) | |---|---|---| | `ResumeTriggeredAbility` | 1880–1884 | `NO_PENDING_TRIGGER` → `REQUEST_ID_MISMATCH` → `NOT_YOUR_TRIGGER` | | `ResumeTargetPick` | 1616–1626 | `NO_PENDING_TARGET_PICK` → `REQUEST_ID_MISMATCH` → `NOT_YOUR_TARGET_PICK` | | `ResumeActionGroupPick` | 1087–1094 | `NO_PENDING_ACTION_GROUP_PICK` → `REQUEST_ID_MISMATCH` → `NOT_YOUR_ACTION_GROUP_PICK` | | `ResumeCostPick` | 828–832 | `NO_PENDING_COST_PICK` → `REQUEST_ID_MISMATCH` | | `ResumeCostGroupPick` | 692–696 | `NO_PENDING_COST_GROUP_PICK` → `REQUEST_ID_MISMATCH` | | `ResumeBranchPick` | 939–943 | `NO_PENDING_BRANCH_PICK` → `REQUEST_ID_MISMATCH` | --- ## 24. State Version and Delta Sync **File:** `Server/src/SOR.Game/Handlers/GameHandlerBase.cs` lines 78, 291–393 **File:** `Client/origin-client/autoloads/Game.gd` lines 104, 717–755 ### Sequence number Before every state save, the sequence number is incremented (`GameHandlerBase.cs:78`): ```csharp var seqNum = state.NextActionSequence++; ``` This is embedded in `stateVersion` on both full-state DTOs and delta payloads. ### Full state vs delta decision — `PushStateToPlayersAsync` (line 291) `prevStateJson` is captured from `session.StateJson` **before** the engine call. After execution: ``` if prevStateJson != null: GameStateDiffer.ComputeDelta(prevState, state, pid) per player if ANY player's delta IsEmpty → push full game.state_update to ALL players else → push per-player game.state_delta if prevStateJson == null (reconnect / initial connect): always push full game.state_update ``` After the state push, `PushPendingPromptsAsync` is always called unconditionally (line 392) — this re-sends any `Pending*` pick requests to the correct player(s). ### Acting player always gets full state `GameActivateAbilityHandler` sends the full `GameStateDto` back in the `game.activate_ability.ack` reply to the acting player. The opponent receives either a delta or a full push from `PushStateToPlayersAsync` depending on the differ result. ### Client-side version tracking — `Game.gd` ``` _state_version tracked at line 104, initialized to -1 On game.state_update: replace entire state, update _state_version (lines 717–734) On game.state_delta: check delta.stateVersion vs _state_version (lines 739–755) v <= _state_version → silently ignore (acting player already got full state in ACK) v > _state_version+1 → version gap detected → call _fetch_state() for full resync v == _state_version+1 → call _apply_delta(delta) ``` **`_fetch_state()`** (line 313): sends `game.get_state`, receives and applies a full state payload. ### Paused ability flows and state pushes When execution pauses with a `Pending*` field set, `PushStateToPlayersAsync` still runs (with the paused state), and `PushPendingPromptsAsync` immediately pushes the interactive prompt. The client receives both the updated state (showing any effects already applied before the pause) and the pick request in the same handler cycle. --- ## 25. Trigger Re-entrancy and Ordering **File:** `AbilitySystem.cs`, `FireTrigger` at line 256 ### Re-entrancy `FireTrigger` is a plain synchronous static method with **no re-entry guard, no `_triggerDepth` counter, and no recursion limit**. It is called directly and synchronously from within: - `ApplyDamageToUnit` — which can be called from within `ExecuteActions` for a triggered ability's effects - `KillUnit`, `SummonTokenEffect`, move effects, etc. This means **fully nested trigger chains are supported** by design. Example: `OnUnitDeath` trigger fires → its actions deal damage → `BeforeDamageApplied` and `OnDamageDealt` triggers fire → their actions can fire further triggers. ### Ordering guarantees When multiple cards respond to the same event, `FireTrigger` iterates in this fixed order: 1. Players — in `state.Players` dictionary insertion order 2. Per player — `Field` cards first, then `Hand`, `Discard`, `Deck` (lines 264–271) 3. Per card — ability array index order (ability 0 before ability 1) There is **no explicit priority system**. Trigger order is entirely determined by player order, then field position, then ability index. ### Anti-loop protection The only protection against infinite trigger loops is the opt-in per-ability rate limiters: - **`TriggerLimitPerTurn`** — `_triggerCountsPerTurn` dict keyed by `(sourceInstanceId, abilityKey, turnNumber)`, checked at lines 323–332 - **`TriggerLimitPerGame`** — `_triggerCountsPerGame` dict keyed by `(sessionId:sourceInstanceId, abilityKey)`, checked at lines 335–343 If a triggered ability definition has **neither limit set**, there is no hard loop guard. An ability that fires on `OnUnitDeath`, kills another unit, and has no `TriggerLimitPerTurn` could recurse indefinitely — protection is entirely a data/design responsibility. ### One-at-a-time for client-pick triggers When any trigger needs a human target pick, `PendingTriggeredTarget` is set (line 364) and `FireTrigger` returns immediately (line 379). Only one pending trigger request can exist at a time — the rest of the trigger scan is abandoned and will not re-run when the pending trigger resumes. --- ## 26. Cost Atomicity and Rollback Semantics **File:** `AbilitySystem.cs` lines 133–153 ### Timing: costs always before effects ```csharp // line 133 — use-count increment first source.AbilityUsesThisTurn[abilityIndex] = usedThisTurn + 1; // line 139–150 — pay costs before ExecuteActions if (def.CostGroup is { } cg) PayCostGroup(cg, ctx, ...); else if (def.Cost is { Length: > 0 }) PayCosts(def.Cost, ctx, ...); // line 152 — effects only after costs are fully paid ExecuteActions(effectiveActions, ctx, ...); ``` The use-count increment and all cost payments are applied before any ability effects execute. This is a strict invariant. ### Interactive cost pause When a cost requires player input (e.g. `DiscardFromHand` with `SelfPick`), `PayCosts` stores `PendingCostPick` and returns early. At this point: - Any costs paid **before** the interactive cost in the same `CostEntry[]` are already applied and **cannot be undone** - The interactive cost itself is not yet applied — it waits for `ResumeCostPick` - `ExecuteActions` has not been called yet — no effects have fired When the player responds, `ResumeCostPick` (line 822) pays the remaining costs and then calls `ExecuteActions`. ### No rollback There is **no rollback mechanism** in the codebase: - `PaySingleCost`, `PayCosts`, and `PayCostGroup` contain no exception handling - There is no try/finally that un-pays costs on exception - There is no "refund" path anywhere - If `ExecuteActions` throws after costs are paid, the in-memory state is partially mutated — but `SaveStateAsync` at the handler level is not reached on exception, so the DB transaction is not committed. The in-memory session state may be inconsistent until the next full state push. **For QA / designers:** if an ability's cost-then-effect sequence is interrupted by an unhandled server error, costs are logically consumed but effects don't fire. This can only be observed as a transient state; the persisted state reverts to pre-activation. Test any ability with interactive costs carefully under network interruption conditions. --- ## 27. Known Caveats and Gotchas ### Line numbers drift Line numbers in this document reference `AbilitySystem.cs` as of 2026-05-20. `AbilitySystem.cs` is ~5500+ lines and actively developed — line numbers drift with every feature addition. When in doubt, search by method name rather than jumping to a line directly. ### `ActionGroup` vs `Actions` — mutually exclusive `GetEffectiveActions()` (line 981–992) uses an **exclusive** check: ```csharp if (def.ActionGroup is { } ag) return ResolveActionGroup(ag, ...); return def.Actions; // only reached if ActionGroup is null ``` If `ActionGroup` is non-null, `def.Actions` is **completely ignored** — there is no merge or fallback. This means a card row that has both fields populated will silently discard `Actions`. The same exclusive logic applies in `GameHandlerBase.GetFirstAction` and `PreValidateClientTileTargets`. When migrating legacy cards to `ActionGroup`, ensure `Actions` is nulled out. ### `ChooserRole` semantics in mixed branches In an OR/XOR `ActionGroup`, `ChooserRole` determines who picks the branch: - **`Random`** — server picks at random, **no client prompt**, execution continues synchronously - **`Self`** — acting player's client receives `game.ability.action_group_pick_request`, execution pauses - **`Opponent`** — opponent's client receives the request, execution pauses An OR group without `ChooserRole` set defaults to `null`, which the server treats as `Random`. This can be surprising if a player-choice was intended. ### `TriggerLimitPerTurn` is the only loop guard As documented in §25, there is no hard recursion limit on trigger chains. A triggered ability with no `TriggerLimitPerTurn` set that can trigger its own event is a potential infinite loop. The limit must be set in the ability data. ### Stale error codes never reach the client All `GameException` error codes (e.g. `UNIT_EXHAUSTED`, `REQUEST_ID_MISMATCH`) are swallowed by `NatsMessageRpcResponder` and replaced with the generic `"INTERNAL_ERROR"` code. The client has no way to distinguish failure reasons from the network layer alone. Server logs are the only source of the specific error code. ### Cost interactivity can partially apply costs As documented in §26, costs in a `CostEntry[]` before an interactive cost entry are applied before the pause. If a designer places a non-interactive cost (e.g. SP deduction) before an interactive cost (e.g. `DiscardFromHand` with `SelfPick`) in the same `CostGroup`, the SP is spent before the player selects their discard. This is by design but can be counterintuitive. ### `SourceZoneGate` is null-guarded as battlefield-only If `SourceZoneGate` is null on a Triggered ability, `FireTrigger` only scans `Field` (the battlefield). To allow a trigger to fire while the card is in Hand/Discard/Deck, `SourceZoneGate` must be explicitly set to those zone names. ### Client `normalize_keys()` is mandatory The client's `ability_targeting.gd:normalize_keys()` (line 841) recursively lowercases all dictionary keys. This exists because server JSON serialization is not guaranteed to be consistent in casing across all code paths (some go through `JsonSerializerOptions` with camelCase, others with PascalCase). If a new action/effect type is added server-side and the client needs to read its JSON fields, those fields must be referenced in lowercase on the client side. --- ## 28. Minimal JSON Examples All ability data is stored exclusively in the PostgreSQL database (managed via the Admin AbilityBuilder UI). No static JSON files exist on disk. The following examples use the canonical wire format — the same structure parsed by `AbilitySystem.ParseAbilities()`. ### Simple Active ability (single SP cost, damages one enemy unit) ```json [{ "Type": "Active", "Name": "Searing Strike", "Description": "Deal 3 damage to a target enemy unit.", "UsesPerTurn": 1, "Range": { "Min": 1, "Max": 3, "RequiresLos": true, "LinearOnly": false }, "CostGroup": { "LogicOp": "And", "ChooserRole": "Self", "Entries": [{ "Type": "SpiritPoints", "Amount": 2 }], "Groups": [] }, "ActionGroup": { "LogicOp": "And", "ChooserRole": "Self", "Actions": [{ "Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Chooser": "Self", "Count": { "N": 1 } }, "Effects": [{ "$type": "DealDamage", "Amount": { "Value": 3 }, "BypassDefense": false }] }], "Groups": [] } }] ``` ### Triggered ability — fires on unit death, needs client target pick Triggers when any allied unit dies. The acting player must then choose one enemy unit to receive a buff. Because `Chooser: "Self"` with a non-trivial pool is used, `ActionNeedsClientTargets()` returns true and execution pauses with `PendingTriggeredTarget`. ```json [{ "Type": "Triggered", "Name": "Vengeful Surge", "Description": "When an allied unit dies, give a target enemy unit -2 ATK until end of turn.", "TriggerLimitPerTurn": 1, "TriggerEvent": { "$type": "OnUnitDeath", "Ownership": "Ally" }, "ActionGroup": { "LogicOp": "And", "ChooserRole": "Self", "Actions": [{ "Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Chooser": "Self", "Count": { "N": 1 } }, "Duration": { "Type": "UntilEndOfTurn" }, "Effects": [{ "$type": "ModifyDamage", "Amount": { "Value": 2 }, "Operator": "Subtract", "StatTarget": "Current" }] }], "Groups": [] } }] ``` ### OR ActionGroup — Self chooser picks one branch (pauses for client input) The acting player is prompted to choose between two effects. Execution pauses with `PendingActionGroupPick` until they respond. The unchosen branch is discarded entirely. ```json [{ "Type": "Active", "Name": "Divergent Path", "Description": "Choose: draw 2 cards, OR gain 3 SP.", "UsesPerTurn": 1, "CostGroup": { "LogicOp": "And", "ChooserRole": "Self", "Entries": [{ "Type": "SpiritPoints", "Amount": 1 }], "Groups": [] }, "ActionGroup": { "LogicOp": "Or", "ChooserRole": "Self", "Actions": [], "Groups": [ { "LogicOp": "And", "ChooserRole": "Self", "Actions": [{ "Target": { "Scope": "Player", "Type": "Player", "Ownership": "Self", "Count": { "N": 1 } }, "Effects": [{ "$type": "DrawCards", "Amount": { "Value": 2 } }] }], "Groups": [] }, { "LogicOp": "And", "ChooserRole": "Self", "Actions": [{ "Target": { "Scope": "Player", "Type": "Player", "Ownership": "Self", "Count": { "N": 1 } }, "Effects": [{ "$type": "ModifySP", "Amount": { "Value": 3 }, "Operator": "Add" }] }], "Groups": [] } ] } }] ```