Files
sor/SOR.Abilities-Review-and-solutions.md
T
2026-07-02 13:09:05 -04:00

341 lines
39 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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 `ActionGroup` via new `GetStaticActions` (AbilitySystem).
> - **C2 fixed** — `AllBattlefieldUnits` / `FindUnitAnywhere` helpers; ArchSpirit now included in
> FireTrigger scans, passive application (incl. `ReEvaluateConditionalPassives`), aura-on-enter,
> `OwnershipIs`, occupant lookups, and **all** `Resume*` 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 use
> `FindUnitAnywhere`; `ResumeCostPick`/`ResumeCostGroupPick` no longer drop paid abilities.
> - **C5 fixed** — full `ActionsJson` pushed for triggered-target prompts (indices now align).
> - **C6 fixed** — `"Base"` removed from the builder (healed to `"Current"` on load);
> `ParseAbilities` catches `JsonException` per card.
> - **C7 fixed** — `ChannelCard`, `SetStatModMultiplier`, `ModifySacrificeTokenReturn` delisted.
> - **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`/`DamageIgnored` and 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 honours `CanDrawCards`
> and `Both`/`Any`; CloneSpiritAsToken wires passives + TokenSummoned.
> - **H6 fixed** — team-aware Ally/Enemy pools, `Ownership=Random` shuffles, `Ownership=Target`
> chains to the prior action's targets, `PreValidateClientTileTargets` flattens 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).
>
> **Deferred** (see §7): validation-on-save endpoint (Phase 2.9), remaining H5 effects
> (SearchAndPlace→Battlefield, RevealCards N/ToOwnership, ChannelCardFromZone Filters/range flags,
> TakeControl duration reversal), H8 duration edge cases, H9 builder round-trip preservation,
> Phase 3 builder fields, Phase 4 client parity items (zone-scope card picking, prompt resilience,
> filter parity, OR-group UX), Phase 5 hygiene.
**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)
1. **Authoring** — `AbilityBuilder.razor` edits `AbilityDefinition[]` JSON stored on `CardDefinition.AbilitiesJson`. It always emits the modern `ActionGroup` shape (`Compile()`, line ~2843) and reads both `ActionGroup` and legacy `Actions` on load.
2. **Resolution** — `AbilitySystem` (static class) parses AbilitiesJson per call. Entry points:
- `ActivateAbility` (player-activated Active on a unit),
- `FireCardEffects` (Repentance/Instinct on channel — runs their `Active` defs),
- `FireTrigger` (Triggered defs, scanned from Battlefield + Hand/Discard/Deck when `SourceZoneGate` set),
- `ApplyPassivesForSource` / `ApplyPassivesToNewTarget` (Passive),
- Aura evaluation (`EvaluateAuras*`, `ApplyAuraEffects`),
- `FireRuinAbilities` (turn-start Ruin activation).
Interactive pauses are stored on `GameState` as `Pending*` records and resumed by `Resume*` methods; `GameHandlerBase.PushPendingPromptsAsync` pushes them to the chooser client. State is only persisted on handler success (exception ⇒ in-memory mutation discarded).
3. **Client** — `ability_targeting.gd` walks the flattened action list collecting `{actionIndex, instanceId|coord|branchIndex}` targets before sending `activate_ability` / `play_card_with_targets`; `server_prompt_handler.gd` renders the eight server-driven `Pending*` prompts.
---
## 3. Critical findings (break correctness now)
### C1 — Passive abilities authored in the builder never execute
- `ApplyPassivesForSource` (AbilitySystem.cs:5170) and `ApplyPassivesToNewTarget` (:5196) call `ExecuteActions(def.Actions, …)` — the `[Obsolete]` flat array.
- The builder **always** writes `ActionGroup` and never writes `Actions` (AbilityBuilder.razor `Compile()`, ~line 2843), so `def.Actions` is `[]` 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:
```csharp
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 fires `BeforeDamageApplied` and `DamagePrevented` but never `DamageDealt`; combat in GameEngine doesn't either)
- `OnUnitLeaveBattlefield`
- `OnSPGained`, `OnSPSpent`, `OnSTGained`, `OnSTSpent` (neither SP/ST costs in `PaySingleCost` nor `ModifySP/ST` effects nor turn accumulation fire them)
- `OnCardDrawn` (`DrawCards` helper :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):**
1. Short term — remove Tier C/D triggers from `TriggerTypesList` (or badge them "NOT IMPLEMENTED") so designers can't author dead cards.
2. Engine work — per trigger: add the `TriggerEventKind` member, the `TriggerMatches` case, and the `FireTrigger` call at the mutation site (e.g. `OnHealed` inside `HealEffect`/HOT tick; `OnCardDrawn` inside `DrawCards`; `OnDamageDealt` at the end of `ApplyDamageToUnit` and the engine combat path; `OnUnitLeaveBattlefield` in `KillUnit`/`ReturnToHand`/`SendToDiscard`; `OnTileAffinityChanged` in the tile effects + Terramorpha channel; `OnTokenSummoned` in `SummonToken`/`CloneSpiritAsToken`).
### C4 — Resume paths lose non-battlefield sources (Repentance/Instinct, zone-gated triggers)
- `GameEngine.ChannelCard` (:441–457) pays cost, calls `FireCardEffects`, then **discards the card even if a pause was set**, and fires the `Channeled` trigger immediately.
- If any action pauses (OR-group pick, opponent target pick, `StackDeck`, `ChannelCardFromZone` TargetTile, cost group…), every `Resume*` looks the source up in `Field` → null:
- `ResumeCostGroupPick`/`ResumeCostPick`/`ResumeTriggeredAbility` **return early** — the remaining effects are silently dropped (cost already paid).
- `ResumeActionGroupPick`/`ResumeTargetPick`/`ResumeTilePick` continue with `Source = null` — source-relative filters, ranges, `DealDamageToSelf`, `Self.*` value refs all silently degrade.
- Same story for `SourceZoneGate` triggers firing from Hand/Discard/Deck: `ResumeTriggeredAbility` (:1943) can't find the hand card and drops the ability.
**Fix:**
1. Add a universal source lookup (`FindUnitAnywhere`: Field + ArchSpirit + Hand + Discard + Deck across players) used by all `Resume*` methods.
2. In `ResumeCostPick`, don't `return state` when the source is gone *after* the cost was paid — either refuse to pay (check first) or execute the actions with a null-source context.
3. In `ChannelCard`, move the discard + `Channeled` trigger into a completion callback: only discard when `!state.HasPendingInteraction()`, and let the final `Resume*` complete the discard (store `PendingChannelCompletion { cardInstanceId }` on state, or simpler: discard immediately but pass the discarded card instance into the resume context via `SourceInstanceId` + 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.gd `on_triggered_target_request`) builds `ability_def` from it and submits targets with `actionIndex = 0`.
- `ResumeTriggeredAbility` (AbilitySystem.cs:1959) replays the **entire** `pending.ActionsJson` array; `ResolveTargets` matches `t.ActionIndex == actionIndex` with the *original* index. If the pick action is at index ≥ 1, the client's `actionIndex 0` never matches → `INSUFFICIENT_TARGETS` thrown after the player already picked. (Compare `ResumeTargetPick`, which correctly replays the paused action *at index 0* — :1689–1695.)
**Fix (choose one):**
- (a) Send the **full** `ActionsJson` in `TriggeredTargetRequestPush` and 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 `PendingTriggeredTarget` and re-map client `ActionIndex 0 → storedIndex` in `ResumeTriggeredAbility`.
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). Server `StatTarget` enum has only `Current, Max` (Effects.cs:128). `"Base"` → `JsonException` on `ParseAbilities`.
- `ParseAbilities` (AbilitySystem.cs:77) has no error isolation. It is called for every card in `FireTrigger`'s scan — one malformed card breaks **every** trigger evaluation and any activation of that card, throwing out of engine mutation paths.
**Fix:**
1. Remove `"Base"` from the dropdown (map existing saved `"Base"` → `"Current"` on parse).
2. Make `ParseAbilities` resilient: try/catch per card returning `[]` with a logged warning (and ideally per-array-element leniency).
3. 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 by `ChannelCardFromZone` but still listed)
- `ModifySacrificeTokenReturnEffect` (offered in "Token & Deferred"; note `SetFixedSacrificeReturn` *is* 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 != Battlefield` and the submitted id matches a player accountId, treat it as "restrict pool to that player" and auto-pick/prompt within it; or emit a proper `PendingTargetPick` with a candidate card list (like `CostPickRequestPush` does).
- 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` → `UntilEndOfSequence` effects 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; `SaveStateAsync` only 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 `ActiveEffect` rows persist in state (the reversal then no-ops incorrectly / marker missing).
**Fix:** move all five into `GameState` (e.g. `Dictionary<string,int?> PreventNextDamageByUnit`, `HashSet<string> PreventDeathUnits`, `Dictionary<string,int> TriggerUsesThisTurn` keyed `"{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 to `max(cur,1)`; `DamageTakenSetToHp` and `DamageIgnored` are never read.
- ArchSpirit (leader) death eliminates the player *before* `BeforeUnitDeath` fires or `_preventDeathUnits` is consulted (:3694–3706) — a "prevent death" effect on your ArchSpirit does nothing.
**Fix:** consult prevention (and fire `BeforeUnitDeath`) 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 no `AreAllies` check — wrong in Teams/MultiTeam. Also `TargetOwnership.Enemy` includes allies.
- **`Ownership=Random` isn'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=Random` *is* shuffled — :2036–2046.)
- **`Ownership=Target` (chained) is unimplemented for card targets**: only `TargetType.Player` handles it (:1988–1992). For unit/card types it falls through to "all players' cards" and takes first-N. Chained targeting currently only works via `SearchDeck.ThenGroup` pre-seeding and `WithinRangeOf`/value `Ref`s.
- `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
- `UntilStartOfOwnerTurn` and `UntilStartOfSourceOwnerTurn` are handled identically (:5022–5029) — both use `td.OwnerAccountId` (the *ability actor*), never the source unit's owner (differs after TakeControl / opponent-cast buffs).
- `WhileCondition` only re-evaluates at turn boundaries — mid-turn state changes (movement, damage) don't expire it, unlike conditional passives which re-evaluate via `ReEvaluateConditionalPassives`.
- `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 in `DurationTypeValues`) — fine, but then the engine's `WhileCondition` machinery 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`, nested `CostGroup.Groups`
- `TargetCount.UpTo` (always compiled `false`, :2891), `Chooser=Ally`
- All but the **first** target filter, and all filter parameters (only `$type` is 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`, trigger `AmountComparator`/`Filter` objects (only SourceFilter `$type` for OnDamageDealt)
**Fix:** preserve-unknown strategy — keep the original `JsonObject` per 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. `FireTrigger` supports only **one** `PendingTriggeredTarget` at 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 `PickMode` is 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. `IsAllyTurnCondition` evaluates identically to `IsOwnTurn` (:4071); `Own()` maps `owner/self` through `AreAllies` (teammates count as "Owner") — intended for teams but contradicts the model docs; `PlayerPropertyCompareCondition` maps `ally → self` (:4184).
- M4. `HasFlagFilter` supports only 4 of the documented flags (:4317–4324; `CanDefend`, `CanBeSacrificed`, etc. always false).
- M5. `ResolveValue` supports only `Damage/Health/Defense/MP/SpCost/StCost` — no `MaxHealth`, `Tier`, player properties; `ResolveAffinity` supports only `Self.Affinity` (no `Target.Affinity` despite doc examples in AffinityExpr).
- M6. `RemoveAbilityEffect` matches by `Name` — abilities without names can't be removed/disabled; `AbilityUsesThisTurn` and trigger limits key by index/name — renaming an ability in the builder resets/breaks disable lists (`DisabledAbilities` stores names).
- M7. `FireCardEffects` runs **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 set `SourceZoneGate=Hand`).
- M8. Active ability `Range` on a Repentance/Instinct card breaks resolution: `FilterTargetsByAbilityRange` requires `ctx.Source is FieldCard` with 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 `OnRuinActivationTrigger` abilities (`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 only `TileWithinRange`/`TileAffinityMatches`/`TileIsUnoccupied`; conditions only `IsOnTileWithAffinity` (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, or `UpTo` selections silently shrink.
- M11. Prompt panels clear `pending_req_id` and hide **before** the server confirms (e.g. `finish_cost_pick` server_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 `typestr` but the normalized key is `type` → all options render "Option N" (server_prompt_handler.gd:175); action-group options read `targetType` but the key is `type` → 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 for `PendingActionGroupPick` *before* 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 for `Ownership=Ally/Any` targeting.
- 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 `CanChannelInstinct` etc.; 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)
1. **Passives use ActionGroup** — `AbilitySystem.cs:5170, 5196`: swap `def.Actions` → flattened `GetEffectiveActions`. *(C1 — one-line-ish, unblocks all authored passives)*
2. **Universal unit lookup** — add `AllBattlefieldUnits` / `FindUnitAnywhere`; apply to `FireTrigger` scan, passive methods, `EvaluateAurasOnEnter/OnLeave`, `FindCardOwner`, and all 8 `Resume*` source lookups. *(C2, C4)*
3. **Triggered-target contract** — push full `ActionsJson` in `TriggeredTargetRequestPush` (GameHandlerBase.cs:407–413). *(C5)*
4. **Deserialization hardening** — try/catch per card in `ParseAbilities`; remove `"Base"` from `StatTargetValues`. *(C6)*
5. **Delist dead content in the builder** — remove Tier C/D triggers from `TriggerTypesList` (or suffix " (coming soon)" and block Compile); remove `ChannelCard`, `SetStatModMultiplier`, `ModifySacrificeTokenReturn` from `EffectGroups` until implemented. *(C3, C7)*
6. **ResumeCostPick ordering** — verify source exists (via new lookup) *before* paying the interactive cost; execute actions with degraded context rather than returning. *(C4)*
7. **Tick scoping** — use `activePlayerId` in `TickActiveEffects`. *(H7)*
### Phase 2 — Correctness of state & validation
8. **Move static state into GameState** — prevent markers, trigger counts, sequence depth (H3). Add turn-advance cleanup for per-turn counts.
9. **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, `TokenDefJson` parse check incl. nested AbilitiesJson). Surface errors in the builder UI. *(C6/C7 prevention, M7/M8/M9 guidance)*
10. **PreventDeath completeness** — honor `DamageTakenSetToHp`/`DamageIgnored`; check prevention + fire `BeforeUnitDeath` for leaders before elimination. *(H4)*
11. **Trigger param matching** — Amount/comparator, DamageType, Filter, CardDefinitionId, OccupantFilters in `TriggerMatches`. *(H1)*
12. **Targeting fixes** — team-aware `Ally`/`Enemy` in `BuildCandidates`; shuffle for `Ownership=Random`; implement chained `Ownership=Target` for card targets (resolve to prior action's resolved targets); recurse `PreValidateClientTileTargets` into sub-groups. *(H6)*
13. **Fire the missing engine triggers** — `DamageDealt`, `CardDrawn`, `SPGained/Spent`, `STGained/Spent`, `UnitLeaveBattlefield`, then re-enable them in the builder list. Add `Healed`, `TokenSummoned`, `TileAffinityChanged` next (require new `TriggerEventKind` members + match cases). *(C3)*
14. **Effect semantics** — `ChannelCardFromZone` cost check (no negative SP) + honor `Filters`/channel-range flags; `SearchAndPlace` Battlefield destination (reuse `ReturnToBattlefieldEffect` logic); `TakeControl` duration reversal + `Board.PlaceUnit` re-own + aura/passive re-eval; `Push/Pull` BlockedDamage + per-tile stepping; `RevealCards` N/ToOwnership; `DrawCards` CanDrawCards + Both/Any; token summon passive hookup in `CloneSpiritAsToken`. *(H5)*
15. **Repentance/Instinct pause lifecycle** — defer discard + `Channeled` trigger 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)
16. **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)*
17. New UI fields, in value order: `UpTo` checkbox; multi-filter editor with parameters (reuse `ConditionGroups` pattern); cost `PickMode` + cost `Filters`; `TriggerLimitPerGame` + `SourceZoneGate` (needed for hand-triggered Instinct designs); `ChooseOne` branch editor; trigger `AmountComparator`/`Filter`; aura `OnEnter/OnLeaveAuraActions`; `Chooser=Ally`; `ReturnToDeck Position=Random`.
18. **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 `OnRuinActivation` triggered template; for ArchSpirit/Spirit: full set. (CardEditor already knows the card type — pass it as a parameter to `AbilityBuilder`.)
19. **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
20. **Zone-scope card picking** — server-mediated candidate push (like cost pick) + client card list panel. *(H2)*
21. **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)*
22. **Label fixes** — normalized-key lookups (`type`, `amount`) in cost/action group prompts; show cost amounts. *(M12)*
23. **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.
24. **OR-group UX** — skip upfront targeting for OR/XOR root groups (server prompts anyway). *(M13)*
25. **Allied targeting** — include allied players' units in highlight pools for Teams. *(M14)*
### Phase 5 — Performance / hygiene (low)
- Cache parsed `AbilityDefinition[]` per (`InstanceId`, AbilitiesJson hash) — `FireTrigger` currently JSON-parses every card in every zone on every event.
- Prune `_triggerCountsPerTurn` on 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).
- `IsAllyTurnCondition` real implementation or removal; document team semantics of `Owner`.
- Deduplicate `_jsonOpts` vs `CreateJsonOptions()`.
---
## 8. Suggested test plan
**Engine unit tests (SOR.Game):**
1. *Passive via ActionGroup*: builder-shaped JSON (ActionGroup only) Passive `+1 Damage to Self` — assert stat applied on placement, reverted on death. (Red today.)
2. *ArchSpirit triggered*: arch with `OnTurnStart → DrawCards` — assert fires. (Red today.)
3. *ArchSpirit active with SelfPick discard cost*: activate, resume cost pick — assert effects execute and cost paid exactly once. (Red today.)
4. *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.)
5. *Repentance with StackDeck (chooser Self)*: channel, resume reveal pick — assert deck reordered and card discarded exactly once. (Partially red.)
6. *Trigger matrix contract test*: reflection over `TriggerTypesList` (builder) ⇒ each must have a PolyType, a `TriggerEventKind`, a `TriggerMatches` case (assert non-`false` for a synthetic occurrence), and at least one `FireTrigger` call site (static analysis list). Keeps builder/engine in lockstep.
7. *Effect matrix contract test*: every `EffectGroups` entry has an `ExecuteEffect` case (e.g. via a test that executes each effect against a dummy target and asserts *something* observable or a known no-op whitelist).
8. *DOT in 3-player game*: assert one tick per round, not per player-turn.
9. *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".*