Server engine (SOR.Game): - Zone-scope card targets (Hand/Deck/Discard/AnyZone) pause with a server- enumerated candidates list (PendingTargetPick.CandidatesJson) instead of failing when the client submits player accountIds for hidden zones - Missing mandatory target picks now prompt (PendingTargetPick) rather than throwing INSUFFICIENT_TARGETS; all post-pick resume flows run with requireClientTargets so actions never silently auto-hit the first candidate - ChannelCardFromZone: Filters + InOwn/InTargetChannelRange enforced via shared IsWithinChannelConstraints (incl. player-picked tile validation) - TakeControl duration reversal via internal __ReturnControl effect; board occupant-owner kept in sync both ways - TrackedDuration gains SourceOwnerAccountId (UntilStartOfSourceOwnerTurn now anchors correctly) and IsAura (aura reapply no longer strips unrelated buffs) - RevealCards honours N for player targets; IsAllyTurn means teammate's turn; content-keyed ParseAbilities cache; AbilityValidator for save-time linting; duplicate PolyType attributes removed (converter reads base registry only) Admin builder (AbilityBuilder/CardEditor): - Full multi-filter editor (28 filter types with parameter fields) replacing the single param-less dropdown; raw-JSON ChooseOne editor per action - Cost PickMode, TriggerLimitPerGame, SourceZoneGate inputs - Save-time ability validation with error list (blocks invalid saves) Client (Godot): - Card-list picker for zone-scope target picks; OR/XOR-root abilities skip speculative upfront targeting; ally units included in team-aware highlight pools (Game.get_ally_units); state re-sync on rejected pick responses Tests: new SOR.Game.Tests project (21 passing) covering the regression suite from SOR.Abilities-Review-and-solutions.md §8 plus validator rules. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
45 KiB
SOR Ability System — Review & Solutions
IMPLEMENTATION STATUS (2026-07-02): Phases 1–2 plus the builder/client quick wins are implemented (server builds clean). Summary of what landed:
- C1 fixed — Passives execute
ActionGroupvia newGetStaticActions(AbilitySystem).- C2 fixed —
AllBattlefieldUnits/FindUnitAnywherehelpers; ArchSpirit now included in FireTrigger scans, passive application (incl.ReEvaluateConditionalPassives), aura-on-enter,OwnershipIs, occupant lookups, and allResume*source lookups.- C3 partly fixed — now fired AND matched:
OnUnitAbilityActivated,OnDamageDealt(ability + combat damage),OnHealed,OnTokenSummoned,OnCardDrawn(engine draw + ability draw),OnSPGained/OnSPSpent/OnSTGained/OnSTSpent(turn accumulation, costs, channel/ascend payments, ModifySP/ST),OnUnitLeaveBattlefield(kill, return-to-hand, send-to-discard). Still unimplemented and now delisted from the builder: OnUnitMPSpent, OnStatModified, OnAbilityAdded/Removed, OnGenusChanged, OnTileAffinityChanged, OnCardDiscarded, OnCardReturnedToHand/Deck, OnDeckShuffled, OnCardsRevealed, OnTargetedByAbility, OnEffectApplied.- C4 fixed — Repentance/Instinct discard before
FireCardEffects; resume paths useFindUnitAnywhere;ResumeCostPick/ResumeCostGroupPickno longer drop paid abilities.- C5 fixed — full
ActionsJsonpushed for triggered-target prompts (indices now align).- C6 fixed —
"Base"removed from the builder (healed to"Current"on load);ParseAbilitiescatchesJsonExceptionper card.- C7 fixed —
ChannelCard,SetStatModMultiplier,ModifySacrificeTokenReturndelisted.- H1 partly — Amount/AmountComparator + DamageType + OnChanneled.CardDefinitionId + OnUnitAbilityActivated.Filter now evaluated in
TriggerMatches.- H3 fixed — trigger counts, prevent markers, sequence depth moved onto
GameState.- H4 fixed — PreventDeath honours
DamageTakenSetToHp/DamageIgnoredand protects leaders.- H5 partly — Push/Pull step per-tile +
BlockedDamage; TakeControl re-owns the board tile; ChannelCardFromZone checks SP/ST sufficiency (all 3 sites); DrawCards honoursCanDrawCardsandBoth/Any; CloneSpiritAsToken wires passives + TokenSummoned.- H6 fixed — team-aware Ally/Enemy pools,
Ownership=Randomshuffles,Ownership=Targetchains to the prior action's targets,PreValidateClientTileTargetsflattens sub-groups.- H7 fixed — DOT/HOT tick only at the applying player's turn end.
- Builder — UpTo checkbox added (parsed/compiled); dead triggers/effects delisted.
- Client — cost-group / action-group prompt labels fixed (normalized keys + amounts).
Also implemented (second pass):
- Test suite — new
Server/tests/SOR.Game.Tests(added to SOR.slnx): 17 passing tests covering §8 tests 1–5 (passives-via-ActionGroup, ArchSpirit triggers, triggered pick at index 1, PreventDeath options, team-aware targeting, DOT tick gating, parse hardening, state-backed trigger limits/shields) plus 7 validator tests.- Validation-on-save (Phase 2.9) — new
SOR.Game.Abilities.AbilityValidator(engine round-trip + structural lint: dead triggers, no-op effects, Repentance/Instinct shape, Range on effect cards, OR-group Passives, TokenDefJson incl. nested abilities); wired intoCardEditor.SaveAsync, which blocks the save and lists the errors.- SearchAndPlace Destination=Battlefield — now places on a random affinity-valid empty tile (with enter-triggers/auras/passives), falling back to hand.
Also implemented (third pass):
- H9 builder round-trip preservation — every draft (ability/action/effect/condition/cost) stashes its original
JsonObject;Compile()clones it and rewrites only UI-owned keys, guarded by$typeso switching types drops stale fields. Preserved now:SourceZoneGate,TriggerLimitPerGame,OnEnter/OnLeaveAuraActions,ChooseOne, filter parameters + extra filters, costPickMode/Filters, nested cost/action groups, triggerFilterparams/CardDefinitionId/AmountComparator, unmodeled effect fields.- ChannelCardFromZone.Filters now enforced at all three resolution sites.
- Client prompt resilience (M11) — a rejected pick response triggers
_fetch_state(), which re-pushes the still-pending prompt (Game.gd_PROMPT_RESPONSE_TYPES).Also implemented (fourth pass):
- H8 duration edge cases —
UntilStartOfSourceOwnerTurnnow anchors to the source unit's owner (TrackedDuration.SourceOwnerAccountId, old records fall back to the actor);ReapplyAurasAtTurnStartstrips only aura-applied effects (TrackedDuration.IsAura, stamped viaAbilityContext.IsAuraApplication) instead of every effect from that source.- TakeControl duration reversal — internal
__ReturnControleffect tracked with the take-control duration; control (and the board occupant-owner) returns to the original owner on expiry. PermanentInMatch keeps control permanently.- ChannelCardFromZone range flags —
InOwnChannelRange/InTargetChannelRangeenforced via a sharedIsWithinChannelConstraintshelper at all three resolution sites, including validation of player-picked tiles (throwsOUT_OF_CHANNEL_RANGE, client re-prompts).- RevealCards N — a player-targeted RevealCards now reveals the top N deck cards (ToOwnership still needs a per-player visibility model — deferred).
- Builder fields — cost
PickModedropdown (pickable cost types only),TriggerLimitPerGameandSourceZoneGateinputs on Triggered abilities; all three added to the UI-owned key handling.- Client filter parity (subset) —
GenusContains,CardTypeIs,AffinityMatches,TierIs,HealthBelow/Above,DamageRange,DefenseRange,Ownership,IsSelf/IsExactSelfunit filters andTileIsOccupied/TileOccupancytile filters now enforced in targeting highlights/click validation.- Tests: 19 passing (added TakeControl reversal + source-owner expiry).
Also implemented (fifth pass):
- H2 zone-scope card picking — for Hand/Deck/Discard/AnyZone card targets on player-driven paths, the engine now pauses with a server-enumerated candidates list (
PendingTargetPick.CandidatesJson, pushed inTargetPickRequestPush); the client's player/zone panel flow feeds into a new card-list picker (_show_zone_target_panelin server_prompt_handler.gd). AccountId placeholders are auto-substituted when there is no real choice.- Prompt-instead-of-throw — a mandatory explicit pick with no submitted targets on a player-driven path now emits
PendingTargetPick(guarded by a non-empty-pool check) instead ofINSUFFICIENT_TARGETS; all post-pick resume flows (cost/cost-group/action-group/branch/tile/player/reveal) now run withrequireClientTargets: true, so "choose an enemy" actions after an OR-pick prompt rather than silently auto-hitting the first candidate.- M13 OR-group UX — the client no longer collects speculative targets for OR/XOR-root abilities (indices would misalign and be discarded); the server drives the flow.
- Hygiene —
IsAllyTurnnow means "a teammate's turn" (was identical to IsOwnTurn); content-keyedParseAbilitiescache (bounded, safe: parsed defs are engine-immutable) removes the per-event JSON parse of every card in every zone.- Tests: 21 passing (added zone-pick pause/resume + prompt-instead-of-throw).
Also implemented (sixth pass, 2026-07-03):
- Multi-filter editor — the single param-less "Target Filter" dropdown is replaced by a full filter list per action (form view + canvas inspector): 28 filter types grouped Unit/Card vs Tile, each with its parameter fields (
FilterDraft,ParseFilter,CompileFilter,RenderFilterFields). Nested-parameter filters (IsAdjacentToUnitMatching etc.) are selectable with their inner params preserved via the round-trip overlay.- ChooseOne editor (advanced) — per-action raw-JSON textarea (same pattern as AddAbility/ApplyOnEvent); parsed/compiled with fallback to the loaded value on invalid JSON. Branch abilities are now authorable.
- M14 allied pools — new
Game.get_ally_units(); highlight pools now mirror the server's team-aware semantics (Owner = own only, Ally = teammates only, Enemy = non-allies, Any = everyone).Also implemented (seventh pass, 2026-07-04):
- PolyType duplicate attributes removed from sealed condition/filter classes (the converter only reads the base-type registry — verified inert before removal).
IgnoreTurnConstraintdecided: documented as reserved/no-effect — ability-driven channels are never subject to the own-turn constraint (model doc comment updated).Remaining backlog (feature work, not defects): RevealCards
ToOwnership— blocked on a per-player card-visibility model; structured (non-JSON) ChooseOne branch editor — the raw-JSON editor covers authoring today. Everything else from this review is resolved and covered by the 21-test regression suite inServer/tests/SOR.Game.Tests.
Date: 2026-07-02 Scope reviewed:
- Server engine:
Server/src/SOR.Game/Abilities/*(AbilitySystem.cs, AbilityContext.cs, all Models),GameEngine.cs,Handlers/GameHandlerBase.cs - Admin authoring:
Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor,CardEditor.razor - Client play:
Client/origin-client/scenes/game/*(ability_targeting.gd, server_prompt_handler.gd, selection_controller.gd, game_screen.gd) - Card types considered: Spirit / ArchSpirit / Instinct / Repentance / Ruin (plus SpiritToken & Terramorpha where they interact)
1. Executive summary
The ability pipeline (Builder JSON → engine resolution → client targeting/prompts) is architecturally sound, but the three layers have drifted apart. The most damaging discrepancies:
| # | Issue | Impact |
|---|---|---|
| C1 | Builder always emits ActionGroup; the Passive path executes only the obsolete flat Actions array |
Every Passive ability authored in the admin tool does nothing in game |
| C2 | ArchSpirit lives in player.ArchSpirit, not player.Field; nearly all engine scans/lookups search Field only |
ArchSpirit Triggered abilities never fire; ArchSpirit Passives never apply; ArchSpirit Actives that pause (cost/target picks) are lost on resume |
| C3 | ~14 trigger types offered by the builder are never matched and/or never fired by the engine | Designers can author dead triggers with no warning |
| C4 | All resume paths (ResumeCostPick, ResumeTargetPick, ResumeActionGroupPick, …) look up the ability source only among battlefield FieldCards |
Repentance/Instinct effects that pause mid-resolution lose their source (the card is already discarded); costs can be paid with the effects silently dropped |
| C5 | Triggered-ability target prompt sends the client only the first pick action (client submits ActionIndex=0), but ResumeTriggeredAbility replays the full action array with original indices |
Any triggered ability whose pick action is not action 0 throws INSUFFICIENT_TARGETS after the player picks |
| C6 | Builder offers StatTarget = "Base" which does not exist in the server enum |
One bad dropdown selection makes the card's entire AbilitiesJson fail deserialization — ParseAbilities throws inside FireTrigger/ActivateAbility for that card |
| C7 | Three builder-offered effects have no runtime implementation: SetStatModMultiplier, ChannelCard, ModifySacrificeTokenReturn |
Silent no-ops in play |
Sections 3–6 give the full catalog; Section 7 is the phased fix plan with exact file/function targets.
2. How the pipeline fits together (context)
- Authoring —
AbilityBuilder.razoreditsAbilityDefinition[]JSON stored onCardDefinition.AbilitiesJson. It always emits the modernActionGroupshape (Compile(), line ~2843) and reads bothActionGroupand legacyActionson load. - Resolution —
AbilitySystem(static class) parses AbilitiesJson per call. Entry points:ActivateAbility(player-activated Active on a unit),FireCardEffects(Repentance/Instinct on channel — runs theirActivedefs),FireTrigger(Triggered defs, scanned from Battlefield + Hand/Discard/Deck whenSourceZoneGateset),ApplyPassivesForSource/ApplyPassivesToNewTarget(Passive),- Aura evaluation (
EvaluateAuras*,ApplyAuraEffects), FireRuinAbilities(turn-start Ruin activation). Interactive pauses are stored onGameStateasPending*records and resumed byResume*methods;GameHandlerBase.PushPendingPromptsAsyncpushes them to the chooser client. State is only persisted on handler success (exception ⇒ in-memory mutation discarded).
- Client —
ability_targeting.gdwalks the flattened action list collecting{actionIndex, instanceId|coord|branchIndex}targets before sendingactivate_ability/play_card_with_targets;server_prompt_handler.gdrenders the eight server-drivenPending*prompts.
3. Critical findings (break correctness now)
C1 — Passive abilities authored in the builder never execute
ApplyPassivesForSource(AbilitySystem.cs:5170) andApplyPassivesToNewTarget(:5196) callExecuteActions(def.Actions, …)— the[Obsolete]flat array.- The builder always writes
ActionGroupand never writesActions(AbilityBuilder.razorCompile(), ~line 2843), sodef.Actionsis[]for every builder-authored card. - The Aura path does this correctly via
GetEffectiveActions(:5495). Only Passives are broken.
Fix: in both passive methods, replace def.Actions with GetEffectiveActions(def, ctx, 0, null, def.Duration ?? fallback) ?? []. Note interactive OR/XOR groups make no sense for Passives — either flatten with FlattenAndGroup(def.ActionGroup) or validate/reject OR-root Passives in the builder.
C2 — ArchSpirit is invisible to most of the ability engine
player.ArchSpirit is not in player.Field (see GameEngine.PlaceArchSpirit / Ascend :508–516). Consequences:
| Path | Location | Effect |
|---|---|---|
FireTrigger scan builds candidates from Field/Hand/Discard/Deck only (:301–308) |
ArchSpirit Triggered abilities never fire | |
ApplyPassivesForSource looks up source in p.Field (:5156–5159) |
ArchSpirit Passives never apply (GameEngine.cs:581 calls it, it returns silently) | |
ApplyPassivesToNewTarget iterates player.Field sources (:5185) |
ArchSpirit passives never re-apply to newly placed units | |
EvaluateAurasOnEnter looks up the new unit in p.Field (:5342–5345) |
Placing/ascending an ArchSpirit never fires its own aura-enter (movement transitions are OK — BoardUnits includes the arch) |
|
All Resume* methods find source via SelectMany(p => p.Field) (e.g. :749, :944, :1004, :1150, :1343, :1500, :1678, :1943) |
ArchSpirit Actives that pause lose their source; worst case ResumeCostPick pays the cost then return state (:947) — cost consumed, effects never run |
|
FindCardOwner (:3879) ignores ArchSpirit |
e.g. OwnershipIsCondition on an arch subject returns false |
Fix: add one helper and use it everywhere:
private static IEnumerable<FieldCard> AllBattlefieldUnits(PlayerState p) {
if (p.ArchSpirit is not null) yield return p.ArchSpirit;
foreach (var fc in p.Field.OfType<FieldCard>()) yield return fc;
}
(BoardUnits already exists for auras — promote it/extend it and use it in FireTrigger, both passive methods, EvaluateAurasOnEnter/OnLeave, all Resume* source lookups, and FindCardOwner (or add a FindUnitAnywhere).)
C3 — Trigger support matrix has three failure tiers
The builder offers 40 trigger types (TriggerTypesList, AbilityBuilder.razor:2200). Runtime support:
Tier B — fired by engine but never matched (missing case in TriggerMatches, AbilitySystem.cs:4369):
OnUnitAbilityActivated(fired at GameEngine.cs:1152 — dead on arrival)
Tier C — matched but never fired anywhere (no FireTrigger call with that kind):
OnDamageDealt(ApplyDamageToUnit firesBeforeDamageAppliedandDamagePreventedbut neverDamageDealt; combat in GameEngine doesn't either)OnUnitLeaveBattlefieldOnSPGained,OnSPSpent,OnSTGained,OnSTSpent(neither SP/ST costs inPaySingleCostnorModifySP/STeffects nor turn accumulation fire them)OnCardDrawn(DrawCardshelper :3827 and engine draw path don't fire it)
Tier D — neither fired nor matched, and most lack a TriggerEventKind member (AbilityContext.cs:84):
OnUnitMPSpent,OnHealed,OnTokenSummoned,OnStatModified,OnAbilityAdded,OnAbilityRemoved,OnGenusChanged,OnTileAffinityChanged(kind exists, unmatched/unfired),OnCardDiscarded,OnCardReturnedToHand,OnCardReturnedToDeck,OnDeckShuffled,OnCardsRevealed,OnTargetedByAbility,OnEffectApplied
Fix (two-pronged):
- Short term — remove Tier C/D triggers from
TriggerTypesList(or badge them "NOT IMPLEMENTED") so designers can't author dead cards. - Engine work — per trigger: add the
TriggerEventKindmember, theTriggerMatchescase, and theFireTriggercall at the mutation site (e.g.OnHealedinsideHealEffect/HOT tick;OnCardDrawninsideDrawCards;OnDamageDealtat the end ofApplyDamageToUnitand the engine combat path;OnUnitLeaveBattlefieldinKillUnit/ReturnToHand/SendToDiscard;OnTileAffinityChangedin the tile effects + Terramorpha channel;OnTokenSummonedinSummonToken/CloneSpiritAsToken).
C4 — Resume paths lose non-battlefield sources (Repentance/Instinct, zone-gated triggers)
GameEngine.ChannelCard(:441–457) pays cost, callsFireCardEffects, then discards the card even if a pause was set, and fires theChanneledtrigger immediately.- If any action pauses (OR-group pick, opponent target pick,
StackDeck,ChannelCardFromZoneTargetTile, cost group…), everyResume*looks the source up inField→ null:ResumeCostGroupPick/ResumeCostPick/ResumeTriggeredAbilityreturn early — the remaining effects are silently dropped (cost already paid).ResumeActionGroupPick/ResumeTargetPick/ResumeTilePickcontinue withSource = null— source-relative filters, ranges,DealDamageToSelf,Self.*value refs all silently degrade.
- Same story for
SourceZoneGatetriggers firing from Hand/Discard/Deck:ResumeTriggeredAbility(:1943) can't find the hand card and drops the ability.
Fix:
- Add a universal source lookup (
FindUnitAnywhere: Field + ArchSpirit + Hand + Discard + Deck across players) used by allResume*methods. - In
ResumeCostPick, don'treturn statewhen the source is gone after the cost was paid — either refuse to pay (check first) or execute the actions with a null-source context. - In
ChannelCard, move the discard +Channeledtrigger into a completion callback: only discard when!state.HasPendingInteraction(), and let the finalResume*complete the discard (storePendingChannelCompletion { cardInstanceId }on state, or simpler: discard immediately but pass the discarded card instance into the resume context viaSourceInstanceId+ the universal lookup from (1)).
C5 — Triggered-target prompt index contract is broken
PushPendingPromptsAsync(GameHandlerBase.cs:405–425) extracts the first action needing a pick and sends only that one; the client (ability_targeting.gdon_triggered_target_request) buildsability_deffrom it and submits targets withactionIndex = 0.ResumeTriggeredAbility(AbilitySystem.cs:1959) replays the entirepending.ActionsJsonarray;ResolveTargetsmatchest.ActionIndex == actionIndexwith the original index. If the pick action is at index ≥ 1, the client'sactionIndex 0never matches →INSUFFICIENT_TARGETSthrown after the player already picked. (CompareResumeTargetPick, which correctly replays the paused action at index 0 — :1689–1695.)
Fix (choose one):
- (a) Send the full
ActionsJsoninTriggeredTargetRequestPushand let the client walk all actions (it already knows how — auto-skip server-resolved ones). Client change: none (it already handles an array). - (b) Keep first-action-only push, but record the original index in
PendingTriggeredTargetand re-map clientActionIndex 0 → storedIndexinResumeTriggeredAbility. Recommend (a) — it also fixes triggered abilities needing picks in multiple actions.
C6 — Builder can emit values the engine cannot deserialize; one bad ability poisons the whole card
StatTargetValues = ["Current", "Base", "Max"](AbilityBuilder.razor:2167, dropdown used at :3560). ServerStatTargetenum has onlyCurrent, Max(Effects.cs:128)."Base"→JsonExceptiononParseAbilities.ParseAbilities(AbilitySystem.cs:77) has no error isolation. It is called for every card inFireTrigger's scan — one malformed card breaks every trigger evaluation and any activation of that card, throwing out of engine mutation paths.
Fix:
- Remove
"Base"from the dropdown (map existing saved"Base"→"Current"on parse). - Make
ParseAbilitiesresilient: try/catch per card returning[]with a logged warning (and ideally per-array-element leniency). - Add a server-side validation endpoint used by CardEditor Save: round-trip the compiled JSON through
AbilitySystem.CreateJsonOptions()deserialization and refuse to save on error (see §7 Phase 2).
C7 — Builder-offered effects with no runtime implementation
No case exists in ExecuteEffect for:
SetStatModMultiplierEffect(offered in "Stat Modification")ChannelCardEffect(offered in "Zone Operations" — superseded byChannelCardFromZonebut still listed)ModifySacrificeTokenReturnEffect(offered in "Token & Deferred"; noteSetFixedSacrificeReturnis implemented)
Fix: implement or delist. Recommend: remove ChannelCard from EffectGroups (keep parse-compat), implement ModifySacrificeTokenReturn (delta version of the existing fixed override), and either implement or remove SetStatModMultiplier.
4. High findings (wrong results in real games)
H1 — Trigger parameter fields are ignored during matching
TriggerMatches checks kind + ownership only. Ignored everywhere: Amount/AmountComparator (OnDamageDealt, OnDamagePrevented, OnHealed, BeforeDamageApplied, OnUnitMPSpent, OnSP*/OnST*), DamageType (OnDamageDealt), Filter (OnUnitMove/Attack/Death/EnterBattlefield/…), CardDefinitionId (OnChanneled), OccupantFilters (Ruin triggers), Cause (OnCardDiscarded), Stat (OnStatModified). The builder happily authors all of these.
Fix: thread occurrence.Data.Amount etc. through TriggerMatches (a CompareInt(t.AmountComparator, occ.Data?.Amount ?? 0, t.Amount.Value) guard per trigger with Amount), and evaluate Filter against the acting unit (occ.Data.SourceId) the way TriggerSourceMatchesFilter already does for OnDamageDealt.
H2 — Client cannot pick cards in zone scopes; sends player accountIds instead
For Scope ∈ {Hand, Deck, Discard, AnyZone} with a card-type target, the client shows a player/zone panel and submits instanceId = accountId (ability_targeting.gd:792–831). The server filters candidates by clientIds containing card InstanceIds (AbilitySystem.cs:2048–2056) → zero matches → INSUFFICIENT_TARGETS.
Fix: two options —
- Server: when
Scope != Battlefieldand the submitted id matches a player accountId, treat it as "restrict pool to that player" and auto-pick/prompt within it; or emit a properPendingTargetPickwith a candidate card list (likeCostPickRequestPushdoes). - Client: implement a card-picker panel fed by a server-provided candidates list. Recommend the server-push route — hidden zones (Deck, opponent Hand) must not leak card lists to the client without server mediation anyway.
H3 — Static mutable state in AbilitySystem (cross-game leakage, no rollback, lost on restart)
_triggerCountsPerTurn, _triggerCountsPerGame, _preventNextDamageByUnit, _preventDeathUnits, _sequenceDepth (AbilitySystem.cs:46–57) are static process-wide:
- Two concurrent sessions share
_sequenceDepth→UntilEndOfSequenceeffects can expire early/late in the other game. - Instance IDs are 8 hex chars — collisions across sessions make shields/limits bleed between games.
- Handler exceptions roll back
GameState(state is re-loaded from JSON per action;SaveStateAsynconly on success) but not these dictionaries → a failed action can leave a phantom damage shield or a consumed trigger-limit. - Server restart loses active PreventDeath/PreventNextDamage markers even though the reversal
ActiveEffectrows persist in state (the reversal then no-ops incorrectly / marker missing). Fix: move all five intoGameState(e.g.Dictionary<string,int?> PreventNextDamageByUnit,HashSet<string> PreventDeathUnits,Dictionary<string,int> TriggerUsesThisTurnkeyed"{instanceId}:{abilityKey}"and cleared on turn advance,int SequenceDepth). They serialize with the state and roll back naturally.
H4 — PreventDeathEffect options ignored; ArchSpirit death bypasses prevention
KillUnit(:3717–3721) always sets HP tomax(cur,1);DamageTakenSetToHpandDamageIgnoredare never read.- ArchSpirit (leader) death eliminates the player before
BeforeUnitDeathfires or_preventDeathUnitsis consulted (:3694–3706) — a "prevent death" effect on your ArchSpirit does nothing. Fix: consult prevention (and fireBeforeUnitDeath) before the leader-elimination branch; honor the two option fields in the non-leader branch.
H5 — Effect semantics diverge from their models (silent partial implementations)
| Effect | Field(s) ignored / wrong | Location |
|---|---|---|
PushUnit / PullUnit |
BlockedDamage never applied; blocked displacement silently aborts; push moves diagonally in one jump instead of stepping tiles |
DisplaceUnit :3756 |
TakeControl |
Duration ignored (control is permanent, no reversal tracked); board Tile.OccupantOwner not updated (ownership filters/OwnershipIs now disagree with the board); no aura/passive re-evaluation |
:2905 |
SearchAndPlace |
Destination="Battlefield" puts the card in Discard |
:3444–3453 |
RevealCards |
N and ToOwnership ignored; just flags the single action target IsRevealed |
:2773 |
ChannelCardFromZone |
No SP/ST sufficiency check — CurrentSp/St can go negative (:3268, :1589, :1421); Filters, InOwnChannelRange, InTargetChannelRange, IgnoreTurnConstraint never evaluated |
|
DrawCards |
Ignores PlayerState.CanDrawCards; Player="Both"/"Any" (builder options) unsupported — ResolvePlayerForEffect (:3948) only knows enemy/opponent vs actor; no CardDrawn trigger |
|
DiscardCards |
Ignores the action's resolved target — always uses its own Player string; Filters picks first-N, no player choice |
|
SetHealthMinimum |
One-shot raise only; no tracked floor (later damage ignores the minimum) | :2837 |
SummonToken TokenDefJson |
Deserialized with the ability JSON options; builder writes PascalCase fields — OK today, but AbilitiesJson nested string means token abilities are never validated |
|
Heal / HOT |
No OnHealed trigger (see C3); heal past MaxHealth=null capped at int.MaxValue (fine) |
|
ModifySP/ST |
No SPGained/SPSpent/STGained/STSpent triggers (see C3) |
H6 — Targeting resolution correctness gaps
TargetOwnership.Ally≡Enemy:BuildCandidates(:2173–2179) maps both to "every other player" with noAreAlliescheck — wrong in Teams/MultiTeam. AlsoTargetOwnership.Enemyincludes allies.Ownership=Randomisn't random: it's treated as server-resolved (:2061–2065) but candidates are never shuffled —.Take(N)picks the first N deterministic entries (:2092–2105). (Chooser=Randomis shuffled — :2036–2046.)Ownership=Target(chained) is unimplemented for card targets: onlyTargetType.Playerhandles it (:1988–1992). For unit/card types it falls through to "all players' cards" and takes first-N. Chained targeting currently only works viaSearchDeck.ThenGrouppre-seeding andWithinRangeOf/valueRefs.PreValidateClientTileTargets(:250) only walks the top-level AND group's direct actions — tile targets inside nested sub-groups skip pre-validation (cost is then wasted on a bad pick because use-count/cost happen before the nested validation throws).
H7 — DOT/HOT tick multiplies with player count
TickActiveEffects(state, activePlayerId) (:4955) never uses activePlayerId — every IsTick effect ticks at every player's turn end. In a 4-player FreePlay lobby a "2 damage per turn" DOT deals 8 per round.
Fix: tick only when the tick's anchor matches (e.g. td.OwnerAccountId == activePlayerId, or better: give ticks an explicit PlayerScope).
H8 — Duration edge cases
UntilStartOfOwnerTurnandUntilStartOfSourceOwnerTurnare handled identically (:5022–5029) — both usetd.OwnerAccountId(the ability actor), never the source unit's owner (differs after TakeControl / opponent-cast buffs).WhileConditiononly re-evaluates at turn boundaries — mid-turn state changes (movement, damage) don't expire it, unlike conditional passives which re-evaluate viaReEvaluateConditionalPassives.ReapplyAurasAtTurnStart(:5390) strips all tracked effects for a source→target pair without reversal — including non-aura effects the same unit applied via an Active ability → permanent stat drift.- Builder never offers
WhileCondition(not inDurationTypeValues) — fine, but then the engine'sWhileConditionmachinery is unreachable from authored content; decide to expose or remove.
H9 — Builder round-trips lose data (silent stripping on open+save)
ParseJson/Compile drop anything the UI doesn't model. Opening a hand-authored card and saving silently deletes:
- Cost
PickMode,Filters, nestedCostGroup.Groups TargetCount.UpTo(always compiledfalse, :2891),Chooser=Ally- All but the first target filter, and all filter parameters (only
$typeis kept, :2895–2897) Action.ChooseOne(branches) — not parsed at all- Nested sub-group
Groups(compiled as empty array, :2838) TriggerLimitPerGame,SourceZoneGate,OnEnterAuraActions,OnLeaveAuraActions,Duration.PlayerScope, triggerAmountComparator/Filterobjects (only SourceFilter$typefor OnDamageDealt) Fix: preserve-unknown strategy — keep the originalJsonObjectper ability and only overwrite the fields the UI actually edits; or add explicit UI for each (see §7 Phase 3 priority list).
5. Medium findings (UX, robustness, drift)
Server
- M1.
FireTriggersupports only onePendingTriggeredTargetat a time — a second matching ability in the same occurrence is skipped entirely (returns at :416 mid-scan), not queued. Trigger limits are also incremented before the pause/execution, so an abandoned pick burns the per-turn/per-game use. - M2. Interactive
PickModeis only honored for 3 of 8 cost types (:588–592); others silently auto-resolve. Builder can't set PickMode at all (see H9) — so today all costs auto-resolve; once the builder exposes PickMode this mismatch will surface. - M3.
IsAllyTurnConditionevaluates identically toIsOwnTurn(:4071);Own()mapsowner/selfthroughAreAllies(teammates count as "Owner") — intended for teams but contradicts the model docs;PlayerPropertyCompareConditionmapsally → self(:4184). - M4.
HasFlagFiltersupports only 4 of the documented flags (:4317–4324;CanDefend,CanBeSacrificed, etc. always false). - M5.
ResolveValuesupports onlyDamage/Health/Defense/MP/SpCost/StCost— noMaxHealth,Tier, player properties;ResolveAffinitysupports onlySelf.Affinity(noTarget.Affinitydespite doc examples in AffinityExpr). - M6.
RemoveAbilityEffectmatches byName— abilities without names can't be removed/disabled;AbilityUsesThisTurnand trigger limits key by index/name — renaming an ability in the builder resets/breaks disable lists (DisabledAbilitiesstores names). - M7.
FireCardEffectsruns all Active defs on a Repentance/Instinct card against the same clientTargets; the client only collects targets for the first Active def (game_screen.gd:685–710). CardEditor's "Exactly one · Active or Triggered" badge (:358–361) is advisory only — nothing enforces it, and a Triggered def on these cards can never fire anyway (they never reach the battlefield and the builder can't setSourceZoneGate=Hand). - M8. Active ability
Rangeon a Repentance/Instinct card breaks resolution:FilterTargetsByAbilityRangerequiresctx.Source is FieldCardwith a position (:2110–2117) → empty targets →INSUFFICIENT_TARGETS. The builder shows Range for every Active ability regardless of card type. - M9. Ruin cards: engine only auto-activates
OnRuinActivationTriggerabilities (FireRuinAbilities); an Active ability on a Ruin is server-legal but unreachable from the client (ruins are excluded from unit selection — selection_controller.gd:168–178). Builder gives no guidance.
Client
- M10. Client-side filter/condition coverage is a small subset of the server's: unit filters only
WithinRange/IsAdjacentToSource; tile filters onlyTileWithinRange/TileAffinityMatches/TileIsUnoccupied; conditions onlyIsOnTileWithAffinity(ability_targeting.gd:485–581). Everything else (Genus, CardType, Tier, Health, Ownership filter, TileOccupancy, TileIsOnPlayerSide, channel-range tiles…) is not enforced in highlights → players click "valid-looking" targets that the server rejects with a generic error, orUpToselections silently shrink. - M11. Prompt panels clear
pending_req_idand hide before the server confirms (e.g.finish_cost_pickserver_prompt_handler.gd:138; tile pick selection_controller.gd:185–191). If the server rejects the pick (INVALID_TILE,INVALID_COST_PICK_SELECTION), the client has no prompt and no request id — the player is stuck until a reconnect re-push (GameGetStateHandler). Fix: keep the prompt until an ack, or re-open it from the error response. - M12. Cosmetic label bugs: cost-group options read
typestrbut the normalized key istype→ all options render "Option N" (server_prompt_handler.gd:175); action-group options readtargetTypebut the key istype→ labels show ownership only (:238). - M13. Client OR/XOR handling:
flatten_and_group(ability_targeting.gd:866) appends the OR group's leaf actions into the flat list and collects targets for them, but the server pauses forPendingActionGroupPickbefore costs and discards those targets — the player targets things twice (once speculatively, once after the pick). Consider detecting OR-root groups client-side and skipping upfront targeting. - M14. Multiplayer allies: highlight pools use
Game.get_all_enemy_units()+ own field only — allied units in Teams mode are never offered forOwnership=Ally/Anytargeting. - M15. Off-turn Instinct is supported end-to-end (client gate game_screen.gd:641, server gate GameEngine.cs:272–276) — but the ability panel/highlight paths never check
CanChannelInstinctetc.; server rejects with generic errors.
6. Card-type-specific summary
| Card type | Channel/entry path | What works | What's broken |
|---|---|---|---|
| Spirit | ChannelCard → battlefield; Actives via ActivateAbility; Triggered via battlefield scan; Passives at placement |
Active flow incl. costs, OR-groups, most effects; triggered scan; auras | Passives dead (C1); trigger param filters ignored (H1); zone-scope targeting (H2) |
| ArchSpirit | PlaceArchSpirit / Ascend / Transition; lives in player.ArchSpirit |
Active abilities until they pause; auras on movement; DOT/reversals (explicit arch lookups exist) | Triggered never fire, Passives never apply, aura-on-enter skipped at placement, paused Actives lost on resume (C2); PreventDeath ineffective on leader (H4) |
| Instinct | Hand click → first Active def targeted → ChannelCard → FireCardEffects → discard; playable off-turn |
Simple immediate effects with upfront targets | Any pausing effect loses the source & can drop remaining effects (C4); only first Active def gets targets (M7); Range breaks resolution (M8); Triggered defs unreachable (M7) |
| Repentance | Same as Instinct, but active-player-only | Same | Same as Instinct |
| Ruin | ChannelCard → random matching tile; FireRuinAbilities each turn-start picks ONE eligible OnRuinActivation ability at random |
Turn-start activation incl. conditions, disable-duration, observer triggers, source-skip guard | Active abilities unreachable from client (M9); OccupantFilters ignored (H1); ruin triggered abilities other than OnRuinActivation only fire from battlefield scan (they do — ruins are in Field — OK) |
| SpiritToken | SummonToken / CloneSpiritAsToken |
Stat cloning, aura/passive hookup on summon (SummonToken path) | CloneSpiritAsToken skips ApplyPassivesForSource/ToNewTarget (only aura enter, :3371); OnTokenSummoned never fires (C3) |
7. Solution map — phased plan
Phase 1 — Stop the bleeding (small, high-yield engine fixes)
- Passives use ActionGroup —
AbilitySystem.cs:5170, 5196: swapdef.Actions→ flattenedGetEffectiveActions. (C1 — one-line-ish, unblocks all authored passives) - Universal unit lookup — add
AllBattlefieldUnits/FindUnitAnywhere; apply toFireTriggerscan, passive methods,EvaluateAurasOnEnter/OnLeave,FindCardOwner, and all 8Resume*source lookups. (C2, C4) - Triggered-target contract — push full
ActionsJsoninTriggeredTargetRequestPush(GameHandlerBase.cs:407–413). (C5) - Deserialization hardening — try/catch per card in
ParseAbilities; remove"Base"fromStatTargetValues. (C6) - Delist dead content in the builder — remove Tier C/D triggers from
TriggerTypesList(or suffix " (coming soon)" and block Compile); removeChannelCard,SetStatModMultiplier,ModifySacrificeTokenReturnfromEffectGroupsuntil implemented. (C3, C7) - ResumeCostPick ordering — verify source exists (via new lookup) before paying the interactive cost; execute actions with degraded context rather than returning. (C4)
- Tick scoping — use
activePlayerIdinTickActiveEffects. (H7)
Phase 2 — Correctness of state & validation
- Move static state into GameState — prevent markers, trigger counts, sequence depth (H3). Add turn-advance cleanup for per-turn counts.
- Server-side ability validation on save — new endpoint (or direct call in CardEditor Save): deserialize compiled JSON with engine options; walk definitions for structural lint (Passive with OR-root group, Active Range on non-unit card types, Triggered without TriggerEvent, trigger types not in the supported set, effects without runtime cases,
TokenDefJsonparse check incl. nested AbilitiesJson). Surface errors in the builder UI. (C6/C7 prevention, M7/M8/M9 guidance) - PreventDeath completeness — honor
DamageTakenSetToHp/DamageIgnored; check prevention + fireBeforeUnitDeathfor leaders before elimination. (H4) - Trigger param matching — Amount/comparator, DamageType, Filter, CardDefinitionId, OccupantFilters in
TriggerMatches. (H1) - Targeting fixes — team-aware
Ally/EnemyinBuildCandidates; shuffle forOwnership=Random; implement chainedOwnership=Targetfor card targets (resolve to prior action's resolved targets); recursePreValidateClientTileTargetsinto sub-groups. (H6) - Fire the missing engine triggers —
DamageDealt,CardDrawn,SPGained/Spent,STGained/Spent,UnitLeaveBattlefield, then re-enable them in the builder list. AddHealed,TokenSummoned,TileAffinityChangednext (require newTriggerEventKindmembers + match cases). (C3) - Effect semantics —
ChannelCardFromZonecost check (no negative SP) + honorFilters/channel-range flags;SearchAndPlaceBattlefield destination (reuseReturnToBattlefieldEffectlogic);TakeControlduration reversal +Board.PlaceUnitre-own + aura/passive re-eval;Push/PullBlockedDamage + per-tile stepping;RevealCardsN/ToOwnership;DrawCardsCanDrawCards + Both/Any; token summon passive hookup inCloneSpiritAsToken. (H5) - Repentance/Instinct pause lifecycle — defer discard +
Channeledtrigger until no pending interaction (C4.3); enforce "exactly one Active" for these card types in validation.
Phase 3 — Builder completeness (respect what the engine supports)
- Round-trip preservation — keep unedited JSON properties per ability (retain original
JsonObject, patch only UI-owned fields). (H9 — do this before adding new fields so old data stops being destroyed) - New UI fields, in value order:
UpTocheckbox; multi-filter editor with parameters (reuseConditionGroupspattern); costPickMode+ costFilters;TriggerLimitPerGame+SourceZoneGate(needed for hand-triggered Instinct designs);ChooseOnebranch editor; triggerAmountComparator/Filter; auraOnEnter/OnLeaveAuraActions;Chooser=Ally;ReturnToDeck Position=Random. - Card-type-aware authoring — when the editor hosts a Repentance/Instinct card: hide Range/UsesPerTurn/Aura/Passive options, enforce single Active; for Ruin: default to
OnRuinActivationtriggered template; for ArchSpirit/Spirit: full set. (CardEditor already knows the card type — pass it as a parameter toAbilityBuilder.) - Form-view sub-group actions — render the full action editor for sub-group actions (currently only add/remove rows, :797–811).
Phase 4 — Client alignment
- Zone-scope card picking — server-mediated candidate push (like cost pick) + client card list panel. (H2)
- Prompt resilience — don't clear
pending_req_id/panel until server ack; on error response with a pending prompt still in state, re-show it. (M11) - Label fixes — normalized-key lookups (
type,amount) in cost/action group prompts; show cost amounts. (M12) - Filter parity — port the remaining target filters/conditions used by live cards to
unit_passes_filters/tile_passes_filters(Genus, CardTypeIs, Tier, Health, Ownership, TileOccupancy, TileIsOnPlayerSide, channel-range). Consider generating a shared filter-spec (server exports a JSON schema of filter semantics) instead of double implementation. - OR-group UX — skip upfront targeting for OR/XOR root groups (server prompts anyway). (M13)
- Allied targeting — include allied players' units in highlight pools for Teams. (M14)
Phase 5 — Performance / hygiene (low)
- Cache parsed
AbilityDefinition[]per (InstanceId, AbilitiesJson hash) —FireTriggercurrently JSON-parses every card in every zone on every event. - Prune
_triggerCountsPerTurnon turn advance (moot if moved into state, Phase 2.8). - Remove duplicate
[PolyType]attributes on sealed condition/filter classes (declared on both the base and themselves). IsAllyTurnConditionreal implementation or removal; document team semantics ofOwner.- Deduplicate
_jsonOptsvsCreateJsonOptions().
8. Suggested test plan
Engine unit tests (SOR.Game):
- Passive via ActionGroup: builder-shaped JSON (ActionGroup only) Passive
+1 Damage to Self— assert stat applied on placement, reverted on death. (Red today.) - ArchSpirit triggered: arch with
OnTurnStart → DrawCards— assert fires. (Red today.) - ArchSpirit active with SelfPick discard cost: activate, resume cost pick — assert effects execute and cost paid exactly once. (Red today.)
- Triggered pick at action index 1: triggered def
[buff self, deal 2 to chosen enemy]— resume with client pick — assert no INSUFFICIENT_TARGETS. (Red today.) - Repentance with StackDeck (chooser Self): channel, resume reveal pick — assert deck reordered and card discarded exactly once. (Partially red.)
- Trigger matrix contract test: reflection over
TriggerTypesList(builder) ⇒ each must have a PolyType, aTriggerEventKind, aTriggerMatchescase (assert non-falsefor a synthetic occurrence), and at least oneFireTriggercall site (static analysis list). Keeps builder/engine in lockstep. - Effect matrix contract test: every
EffectGroupsentry has anExecuteEffectcase (e.g. via a test that executes each effect against a dummy target and asserts something observable or a known no-op whitelist). - DOT in 3-player game: assert one tick per round, not per player-turn.
- Round-trip test (Admin): for each feature-bearing sample JSON (PickMode, UpTo, ChooseOne, SourceZoneGate…),
ParseJson→Compile→ assert JSON-equivalent.
Manual/integration:
- Ruin with two OnRuinActivation abilities + occupant filter; Instinct channeled on opponent's turn with an OR cost group; aura linger duration across ascension; TakeControl across turn boundary.
Line references are to the state of the code on 2026-07-02 (branch master). All findings were verified by reading the code — none are speculative — except where marked "Consider/decide".