namespace SOR.Game.Tests; using SOR.Database.Enums; using SOR.Game; using SOR.Game.Abilities; using SOR.Game.Grid; using Xunit; /// /// Regression tests for the ability-system fixes documented in /// SOR.Abilities-Review-and-solutions.md. Each test targets a scenario that was /// broken before the 2026-07-02 remediation (tests 1–5 of the doc's §8 test plan). /// public sealed class AbilitySystemRegressionTests { private const string P1 = "11111111-1111-1111-1111-111111111111"; private const string P2 = "22222222-2222-2222-2222-222222222222"; private const string P3 = "33333333-3333-3333-3333-333333333333"; // ── Fixture helpers ─────────────────────────────────────────────────────── private static GameState NewState(params (string accountId, int teamIndex)[] players) { var state = new GameState { SessionId = Guid.NewGuid(), Phase = GamePhase.Main, TurnNumber = 3, Board = Board.Create(6, 6), ActivePlayerAccountId = players[0].accountId, PlayerOneAccountId = players[0].accountId, }; foreach (var (id, team) in players) state.Players[id] = new PlayerState { AccountId = id, TeamIndex = team, CurrentSp = 10, CurrentSt = 10, }; return state; } private static FieldCard PlaceSpirit( GameState state, string ownerId, int x, int y, string? abilitiesJson = null, string cardType = "Spirit", int hp = 10, int damage = 2) { var fc = new FieldCard { Name = $"{cardType}@{x},{y}", CardType = cardType, MaxHealth = hp, CurrentHealth = hp, MaxDefense = 0, CurrentDefense = 0, Damage = damage, AbilitiesJson = abilitiesJson, Position = new Coord(x, y), IsLeader = cardType == "ArchSpirit", }; var player = state.Players[ownerId]; if (cardType == "ArchSpirit") player.ArchSpirit = fc; else player.Field.Add(fc); state.Board!.PlaceUnit(new Coord(x, y), fc.InstanceId, ownerId); return fc; } private static CardInstance NewCard(string name = "Card", string cardType = "Spirit") => new() { Name = name, CardType = cardType }; // ── §8 Test 1 — Passive authored as ActionGroup (builder shape) applies ── [Fact] public void Passive_AuthoredWithActionGroup_AppliesAndRevokes() { // Builder-shaped JSON: ActionGroup only, empty legacy Actions. const string abilities = """ [{ "Type": "Passive", "Name": "War Cry", "ActionGroup": { "LogicOp": "And", "Actions": [{ "Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "ExactSelf", "Chooser": "Self", "Count": { "N": 1, "UpTo": false, "All": false } }, "Effects": [ { "$type": "ModifyDamage", "Amount": { "Fixed": 2 } } ] }], "Groups": [] } }] """; var state = NewState((P1, 0), (P2, 1)); var unit = PlaceSpirit(state, P1, 1, 1, abilities, damage: 2); AbilitySystem.ApplyPassivesForSource(state, unit.InstanceId, P1); Assert.Equal(4, unit.Damage); // +2 applied Assert.Single(state.ActiveEffects); // reversal tracked AbilitySystem.RevokePassivesForSource(state, unit.InstanceId); Assert.Equal(2, unit.Damage); // reverted Assert.Empty(state.ActiveEffects); } // ── §8 Test 2 — ArchSpirit triggered ability fires ──────────────────────── [Fact] public void ArchSpirit_TriggeredAbility_FiresOnTurnStart() { const string abilities = """ [{ "Type": "Triggered", "Name": "Dawn Draw", "TriggerEvent": { "$type": "OnTurnStart", "Player": "Owner" }, "ActionGroup": { "LogicOp": "And", "Actions": [{ "Target": { "Scope": "Player", "Type": "Player", "Ownership": "Owner", "Count": { "N": 1 } }, "Effects": [ { "$type": "DrawCards", "N": 1, "Player": "Owner" } ] }], "Groups": [] } }] """; var state = NewState((P1, 0), (P2, 1)); PlaceSpirit(state, P1, 0, 0, abilities, cardType: "ArchSpirit", hp: 20); state.Players[P1].Deck.Add(NewCard("Top")); AbilitySystem.FireTrigger(state, new TriggerOccurrence { Kind = TriggerEventKind.TurnStart, ActorId = P1, }); Assert.Single(state.Players[P1].Hand); Assert.Empty(state.Players[P1].Deck); } // ── §8 Test 4 — Triggered ability with pick action at index 1 ──────────── [Fact] public void TriggeredAbility_PickActionAtIndexOne_ResolvesWithOriginalIndex() { const string abilities = """ [{ "Type": "Triggered", "Name": "Snipe", "TriggerEvent": { "$type": "OnTurnStart", "Player": "Owner" }, "ActionGroup": { "LogicOp": "And", "Actions": [ { "Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "ExactSelf", "Count": { "N": 1 } }, "Effects": [ { "$type": "ModifyDamage", "Amount": { "Fixed": 1 } } ] }, { "Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Count": { "N": 1 } }, "Effects": [ { "$type": "DealDamage", "Amount": { "Fixed": 3 }, "BypassDefense": true } ] } ], "Groups": [] } }] """; var state = NewState((P1, 0), (P2, 1)); var source = PlaceSpirit(state, P1, 1, 1, abilities, damage: 2); var enemy = PlaceSpirit(state, P2, 4, 4, hp: 10); AbilitySystem.FireTrigger(state, new TriggerOccurrence { Kind = TriggerEventKind.TurnStart, ActorId = P1, }); // The Enemy-target action (index 1) needs a human pick — engine must pause. var pending = state.PendingTriggeredTarget; Assert.NotNull(pending); // Client submits the pick with the ORIGINAL action index (1). Before the fix // the prompt only carried the pick action and the resume threw INSUFFICIENT_TARGETS. AbilitySystem.ResumeTriggeredAbility(state, P1, pending!.RequestId, [new AbilityTarget(1, enemy.InstanceId)]); Assert.Equal(3, source.Damage); // action 0 auto-resolved (+1) Assert.Equal(7, enemy.CurrentHealth); // action 1 hit the picked enemy (-3) Assert.Null(state.PendingTriggeredTarget); } // ── PreventDeath options (DamageIgnored) ───────────────────────────────── [Fact] public void PreventDeath_DamageIgnored_CancelsLethalHitAndConsumesMarker() { const string abilities = """ [{ "Type": "Active", "Name": "Smite", "ActionGroup": { "LogicOp": "And", "Actions": [{ "Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Count": { "N": 1 } }, "Effects": [ { "$type": "DealDamage", "Amount": { "Fixed": 99 }, "BypassDefense": true } ] }], "Groups": [] } }] """; var state = NewState((P1, 0), (P2, 1)); var target = PlaceSpirit(state, P2, 4, 4, hp: 10); var card = NewCard("Repentance of Smiting", "Repentance"); card.AbilitiesJson = abilities; state.Players[P1].Discard.Add(card); // channel flow discards before firing state.PreventDeathMarkers[target.InstanceId] = new PreventDeathMarker { DamageIgnored = true }; AbilitySystem.FireCardEffects(state, P1, card, [new AbilityTarget(0, target.InstanceId)]); Assert.Equal(10, target.CurrentHealth); // hit fully ignored Assert.False(state.PreventDeathMarkers.ContainsKey(target.InstanceId)); // marker consumed Assert.Contains(state.Players[P2].Field, f => f.InstanceId == target.InstanceId); } [Fact] public void PreventDeath_SetHpOption_SurvivesAtConfiguredHp() { const string abilities = """ [{ "Type": "Active", "Name": "Smite", "ActionGroup": { "LogicOp": "And", "Actions": [{ "Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Count": { "N": 1 } }, "Effects": [ { "$type": "DealDamage", "Amount": { "Fixed": 99 }, "BypassDefense": true } ] }], "Groups": [] } }] """; var state = NewState((P1, 0), (P2, 1)); var target = PlaceSpirit(state, P2, 4, 4, hp: 10); var card = NewCard("Repentance of Smiting", "Repentance"); card.AbilitiesJson = abilities; state.Players[P1].Discard.Add(card); state.PreventDeathMarkers[target.InstanceId] = new PreventDeathMarker { DamageTakenSetToHp = 3 }; AbilitySystem.FireCardEffects(state, P1, card, [new AbilityTarget(0, target.InstanceId)]); Assert.Equal(3, target.CurrentHealth); // saved at the configured HP Assert.Contains(state.Players[P2].Field, f => f.InstanceId == target.InstanceId); } // ── Team-aware Enemy targeting ──────────────────────────────────────────── [Fact] public void EnemyTargeting_ExcludesTeammates() { const string abilities = """ [{ "Type": "Active", "Name": "Nova", "ActionGroup": { "LogicOp": "And", "Actions": [{ "Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Count": { "N": 1, "All": true } }, "Effects": [ { "$type": "DealDamage", "Amount": { "Fixed": 1 }, "BypassDefense": true } ] }], "Groups": [] } }] """; // P1 + P2 are teammates (team 0); P3 is the enemy (team 1). var state = NewState((P1, 0), (P2, 0), (P3, 1)); var teammate = PlaceSpirit(state, P2, 2, 2, hp: 10); var enemy = PlaceSpirit(state, P3, 4, 4, hp: 10); var card = NewCard("Nova Repentance", "Repentance"); card.AbilitiesJson = abilities; state.Players[P1].Discard.Add(card); AbilitySystem.FireCardEffects(state, P1, card, clientTargets: null); Assert.Equal(10, teammate.CurrentHealth); // ally untouched Assert.Equal(9, enemy.CurrentHealth); // enemy hit } // ── DOT ticks once per round, not per player-turn ───────────────────────── [Fact] public void DotTick_OnlyFiresOnApplyingPlayersTurnEnd() { var state = NewState((P1, 0), (P2, 1)); var target = PlaceSpirit(state, P2, 4, 4, hp: 10); state.ActiveEffects.Add(new ActiveEffect { SourceInstanceId = "src", TargetRef = target.InstanceId, EffectJson = """{ "$type": "DealDamage", "Amount": { "Fixed": 2 }, "BypassDefense": true }""", DurationJson = $$"""{ "Duration": { "Type": "ForNTurns", "N": 3 }, "OwnerAccountId": "{{P1}}", "IsTick": true }""", TurnsRemaining = 3, }); AbilitySystem.TickActiveEffects(state, P2); // not the applier's turn — no tick Assert.Equal(10, target.CurrentHealth); AbilitySystem.TickActiveEffects(state, P1); // applier's turn — tick once Assert.Equal(8, target.CurrentHealth); } // ── Parse hardening ─────────────────────────────────────────────────────── [Fact] public void ParseAbilities_MalformedJson_ReturnsEmptyInsteadOfThrowing() { // "Base" is not a valid StatTarget enum value — previously poisoned the card. const string malformed = """ [{ "Type": "Passive", "ActionGroup": { "LogicOp": "And", "Actions": [{ "Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "ExactSelf", "Count": { "N": 1 } }, "Effects": [ { "$type": "ModifyHealth", "Amount": { "Fixed": 1 }, "StatTarget": "Base" } ] }], "Groups": [] } }] """; var defs = AbilitySystem.ParseAbilities(malformed); Assert.Empty(defs); // And a card carrying malformed JSON must not break trigger scans. var state = NewState((P1, 0), (P2, 1)); PlaceSpirit(state, P1, 1, 1, malformed); var ex = Record.Exception(() => AbilitySystem.FireTrigger(state, new TriggerOccurrence { Kind = TriggerEventKind.TurnStart, ActorId = P1, })); Assert.Null(ex); } // ── Trigger limits live on GameState and survive round-trips ───────────── [Fact] public void TriggerLimitPerTurn_EnforcedViaGameState() { const string abilities = """ [{ "Type": "Triggered", "Name": "Once Only", "TriggerLimitPerTurn": 1, "TriggerEvent": { "$type": "OnCardDrawn", "Player": "Owner" }, "ActionGroup": { "LogicOp": "And", "Actions": [{ "Target": { "Scope": "Player", "Type": "Player", "Ownership": "Owner", "Count": { "N": 1 } }, "Effects": [ { "$type": "ModifySP", "Amount": { "Fixed": 1 } } ] }], "Groups": [] } }] """; var state = NewState((P1, 0), (P2, 1)); PlaceSpirit(state, P1, 1, 1, abilities); var occ = new TriggerOccurrence { Kind = TriggerEventKind.CardDrawn, ActorId = P1 }; AbilitySystem.FireTrigger(state, occ); AbilitySystem.FireTrigger(state, occ); Assert.Equal(11, state.Players[P1].CurrentSp); // fired exactly once Assert.Single(state.TriggerUsesThisTurn); // counter lives on the state } // ── TakeControl: duration-tracked, board-synced, reversed on expiry ─────── [Fact] public void TakeControl_ReturnsUnitToOriginalOwnerWhenDurationExpires() { const string abilities = """ [{ "Type": "Active", "Name": "Dominate", "ActionGroup": { "LogicOp": "And", "Actions": [{ "Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Count": { "N": 1 } }, "Effects": [ { "$type": "TakeControl", "Duration": { "Type": "UntilEndOfTurn" } } ] }], "Groups": [] } }] """; var state = NewState((P1, 0), (P2, 1)); var victim = PlaceSpirit(state, P2, 4, 4, hp: 10); var card = NewCard("Dominate", "Instinct"); card.AbilitiesJson = abilities; state.Players[P1].Discard.Add(card); AbilitySystem.FireCardEffects(state, P1, card, [new AbilityTarget(0, victim.InstanceId)]); Assert.Contains(state.Players[P1].Field, f => f.InstanceId == victim.InstanceId); Assert.DoesNotContain(state.Players[P2].Field, f => f.InstanceId == victim.InstanceId); Assert.Equal(P1, state.Board!.GetTile(new Coord(4, 4))!.OccupantOwner); Assert.Single(state.ActiveEffects); // return-control reversal tracked // End of turn: control returns to the original owner, board included. AbilitySystem.ExpireActiveEffects(state, P1, isEndOfTurn: true); Assert.Contains(state.Players[P2].Field, f => f.InstanceId == victim.InstanceId); Assert.DoesNotContain(state.Players[P1].Field, f => f.InstanceId == victim.InstanceId); Assert.Equal(P2, state.Board!.GetTile(new Coord(4, 4))!.OccupantOwner); Assert.Empty(state.ActiveEffects); } // ── UntilStartOfSourceOwnerTurn anchors to the source unit's owner ──────── [Fact] public void UntilStartOfSourceOwnerTurn_ExpiresOnSourceOwnersTurnNotActors() { var state = NewState((P1, 0), (P2, 1)); var unit = PlaceSpirit(state, P1, 1, 1, damage: 4); // buffed to 4; reversal -2 state.ActiveEffects.Add(new ActiveEffect { SourceInstanceId = "src", TargetRef = unit.InstanceId, EffectJson = """{ "$type": "ModifyDamage", "Amount": { "Fixed": -2 } }""", DurationJson = $$""" { "Duration": { "Type": "UntilStartOfSourceOwnerTurn" }, "OwnerAccountId": "{{P1}}", "SourceOwnerAccountId": "{{P2}}" } """, }); // Actor's (P1) turn start: must NOT expire — the anchor is the source owner (P2). AbilitySystem.ExpireActiveEffects(state, P1, isEndOfTurn: false); Assert.Equal(4, unit.Damage); Assert.Single(state.ActiveEffects); // Source owner's (P2) turn start: expires and reverts. AbilitySystem.ExpireActiveEffects(state, P2, isEndOfTurn: false); Assert.Equal(2, unit.Damage); Assert.Empty(state.ActiveEffects); } // ── Zone-scope card picks pause with a server-enumerated candidates list ── [Fact] public void ZoneScopeCardPick_PausesWithCandidates_ThenResumesWithCardIds() { const string abilities = """ [{ "Type": "Active", "Name": "Pilfer", "ActionGroup": { "LogicOp": "And", "Actions": [{ "Target": { "Scope": "Hand", "Type": "Card", "Ownership": "Enemy", "Count": { "N": 1 } }, "Effects": [ { "$type": "SendToDiscard" } ] }], "Groups": [] } }] """; var state = NewState((P1, 0), (P2, 1)); var source = PlaceSpirit(state, P1, 1, 1, abilities); var cardA = NewCard("A"); var cardB = NewCard("B"); state.Players[P2].Hand.AddRange([cardA, cardB]); // The client can only submit the target PLAYER's accountId for hidden zones. AbilitySystem.ActivateAbility(state, P1, source.InstanceId, 0, [new AbilityTarget(0, P2)]); var pending = state.PendingTargetPick; Assert.NotNull(pending); Assert.NotNull(pending!.CandidatesJson); Assert.Contains(cardA.InstanceId, pending.CandidatesJson); Assert.Contains(cardB.InstanceId, pending.CandidatesJson); // The chooser picks a real card; the paused action is replayed at index 0. AbilitySystem.ResumeTargetPick(state, P1, pending.RequestId, [new AbilityTarget(0, cardA.InstanceId)]); Assert.Contains(cardA, state.Players[P2].Discard); Assert.DoesNotContain(cardA, state.Players[P2].Hand); Assert.Contains(cardB, state.Players[P2].Hand); Assert.Null(state.PendingTargetPick); } // ── Missing mandatory targets prompt instead of throwing ───────────────── [Fact] public void MissingMandatoryTargets_PromptInsteadOfInsufficientTargets() { const string abilities = """ [{ "Type": "Active", "Name": "Zap", "ActionGroup": { "LogicOp": "And", "Actions": [{ "Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Count": { "N": 1 } }, "Effects": [ { "$type": "DealDamage", "Amount": { "Fixed": 2 }, "BypassDefense": true } ] }], "Groups": [] } }] """; var state = NewState((P1, 0), (P2, 1)); var source = PlaceSpirit(state, P1, 1, 1, abilities); var enemy = PlaceSpirit(state, P2, 4, 4, hp: 10); // No targets submitted (e.g. after an OR-group Random pick shifted indices). AbilitySystem.ActivateAbility(state, P1, source.InstanceId, 0, clientTargets: null); var pending = state.PendingTargetPick; Assert.NotNull(pending); // prompt, not INSUFFICIENT_TARGETS Assert.Null(pending!.CandidatesJson); // battlefield pick — client resolves visually AbilitySystem.ResumeTargetPick(state, P1, pending.RequestId, [new AbilityTarget(0, enemy.InstanceId)]); Assert.Equal(8, enemy.CurrentHealth); Assert.Null(state.PendingTargetPick); } // ── PreventNextDamage shield lives on GameState ─────────────────────────── [Fact] public void PreventNextDamage_ShieldAbsorbsViaGameState() { const string abilities = """ [{ "Type": "Active", "Name": "Bolt", "ActionGroup": { "LogicOp": "And", "Actions": [{ "Target": { "Scope": "Battlefield", "Type": "Unit", "Ownership": "Enemy", "Count": { "N": 1 } }, "Effects": [ { "$type": "DealDamage", "Amount": { "Fixed": 5 }, "BypassDefense": true } ] }], "Groups": [] } }] """; var state = NewState((P1, 0), (P2, 1)); var target = PlaceSpirit(state, P2, 4, 4, hp: 10); var card = NewCard("Bolt", "Instinct"); card.AbilitiesJson = abilities; state.Players[P1].Discard.Add(card); state.PreventNextDamageByUnit[target.InstanceId] = 3; // absorb up to 3 AbilitySystem.FireCardEffects(state, P1, card, [new AbilityTarget(0, target.InstanceId)]); Assert.Equal(8, target.CurrentHealth); // 5 - 3 absorbed = 2 through Assert.False(state.PreventNextDamageByUnit.ContainsKey(target.InstanceId)); } }