From Ruin-IssueResolution.md -- four fixes in priority order: 6-D (highest): stop double OnRuinActivation execution -- source Ruin's abilities fire once via FireRuinAbilities; FireTrigger must skip source unit to prevent the same abilities re-firing through the general trigger pipeline. Note: new ActivateRuinAbilityEffect (Phase 1.8/5.7) must use the same guard. 6-C: server enforce tile.RuinId == null in candidate set + NO_VALID_RUIN_TILE error code 6-B: client preflight -- compute valid no-ruin tiles before showing confirm dialog; block and show message if none available 6-A: client confirm dialog before channeling a Ruin card Delivery note: Phase 6-D must land before Phase 5.7 so the source-skip guard is in place before ActivateRuinAbilityEffect can trigger through the pipeline. Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude <noreply@anthropic.com> Co-Authored-By: Happy <yesreply@happy.engineering>
43 KiB
NewCard + Ability System Revamp -- Implementation Plan
Status: Planning Target branch: feature/newcard-ability-revamp Files to delete before starting: AbilityBuilderR2-Draft.razor, AbilityBuilderR3.razor
Overview
Three workstreams that feed into each other:
- Ability Model Expansion -- fill gaps in C# domain models so the engine can represent every ability in the spec.
- Card Editor Revamp -- replace the current tabbed form with a mobile-friendly, type-contextual flow.
- Visual Ability Builder -- replace the raw-JSON AbilityBuilder.razor with a drag-and-drop node canvas.
Database migrations sit between 1 and 2/3 and must land first.
Design Axioms (locked, not negotiable)
A. The Ability System Is Fully Recursive
Every layer nests arbitrarily:
- CostGroup contains CostEntry leaves and/or child CostGroup nodes (AND/OR/XOR).
- ConditionGroup (AND/OR/XOR/NOT) contains leaf conditions and/or child groups.
- ActionGroup contains leaf Action nodes and/or child ActionGroup nodes (AND/OR/XOR). The ability-level action sequence is therefore not a flat list but an ActionGroup tree.
- A leaf Action may additionally carry a ChooseOne, which branches the effects within that single action step. ChooseOne branches each contain their own Action[].
- Action[] inside a ChooseOne branch can contain further ChooseOne nodes -- no depth limit.
- SearchDeckEffect.ThenAction and ApplyOnEventEffect.Effects are recursive trees.
ActionGroup vs ChooseOne -- these are distinct and complementary: ActionGroup (ability level): groups multiple top-level action steps with AND/OR/XOR. AND -- all steps execute sequentially. OR -- chooser picks one step (or one group) to execute. XOR -- exactly one step executes, mutually exclusive. ChooseOne (action level): within a single action step (shared target already resolved), the chooser picks one effect branch. Suitable for "deal damage OR push" on the same target. Not suitable for "target an ally and heal them OR target an enemy and damage them" -- that requires two leaf Actions inside an OR ActionGroup.
The engine processes all of this via recursive descent.
B. Every Client Decision Must Be Prompted
Wherever the server needs a human choice it cannot auto-resolve, execution pauses and the appropriate Pending* state is persisted to GameState. The client receives a typed prompt and must respond before the ability continues. No silent auto-picks when a human should be choosing.
Prompt categories and their Pending* types:
| Decision | Pending* Type | Chooser field |
|---|---|---|
| Which OR/XOR action group to execute | PendingActionGroupPick | ActionGroup.ChooserRole (NEW) |
| Which OR/XOR cost branch to pay | PendingCostGroupPick | CostGroup.ChooserRole |
| Which specific cards satisfy a cost | PendingCostPick (exist) | CostEntry.PickMode |
| Which ChooseOne branch to take | PendingBranchPick | ChooseOne.ChooserRole |
| Which target(s) to assign to an action | PendingTargetPick | TargetSelector.Chooser (NEW) |
| Which tile for token/reposition | PendingTilePick | effect-level |
| Which player for UnderControlOf: Choice | PendingPlayerPick | effect-level |
| Reveal-and-choose | PendingRevealChoicePick | effect-level |
All Pending* types share a common envelope:
PendingInteraction { AbilityInstanceId : Guid -- which ability instance is paused StepId : string -- echoed back by client in response Type : string -- matches Pending* discriminator above Payload : object -- type-specific (options, filters, count, etc.) Chooser : string -- "Self" | "Opponent" | "Ally" | "Random" TimeoutMs : int -- server enforces; Random-fallback on expiry }
GameState must be fully serializable mid-resolution so the server survives restarts.
C. ActionGroup, ChooseOne, and CostGroup All Have a ChooserRole
"Self" -- the ability's controlling player chooses "Opponent" -- the opposing player chooses "Random" -- server picks immediately, no client prompt
D. Target Ownership != Target Chooser
TargetSelector currently conflates "whose entities qualify" with "who picks the target." These are separate:
Ownership (TargetOwnership enum) -- filters the valid target pool Self | ExactSelf | Owner | Ally | Enemy | Any | Random | Target
Chooser (TargetChooser -- NEW field on TargetSelector) -- who makes the selection Self | Opponent | Ally | Random
Examples: "Opponent picks one of your own Spirits to sacrifice" -> Ownership=Owner, Chooser=Opponent
"You choose any enemy unit" -> Ownership=Enemy, Chooser=Self
"Random enemy unit" -> Ownership=Enemy, Chooser=Random (no PendingTargetPick emitted)
When Chooser resolves to a human (Self or Opponent or Ally), a PendingTargetPick is emitted. When Chooser=Random, the server resolves immediately from the filtered pool.
Resolved Decisions
| Decision | Resolution
--|-------------------------|------------------------------------------------------- 1 | SpiritToken storage | CardType.SpiritToken added as a full CardDefinition row. | | SummonTokenEffect gains CardDefinitionId?. | | Tokens cannot be added to decks or granted to collections. | | Enforced at deck-build validator and collection-grant endpoints. 2 | OR/XOR client protocol | Full PendingCostGroupPick + PendingBranchPick protocol (Axiom B). 3 | Drag-and-drop | Custom CSS/Blazor approach first. No external library. 4 | EffectsJson migration | Hard cutover. No backwards-compat shim. | | Migration tool converts all ~100+ cards; column is then dropped. | | See Phase 2.2. 5 | ChooseOne.ChooserRole | Confirmed. Added in Phase 1.4. 6 | RequiresLOS source | For Repentance/Instinct, LOS origin = the controlling player's | | active ArchSpirit (card is not on the battlefield).
Phase 0 -- Cleanup
0.1 Delete AbilityBuilderR2-Draft.razor and AbilityBuilderR3.razor 0.2 Verify no NavMenu or router references point to deleted pages 0.3 Create feature branch feature/newcard-ability-revamp
Phase 1 -- Ability Model Expansion (C# only, no DB change)
1.1 -- Active Ability Fields
AbilityDefinition already has Type, Name, Description, Cost, Actions. The following Active-specific fields must be present (add if missing, verify if present):
| Field | Type | Notes |
|---|---|---|
| Range.Min | int | Minimum tiles from source to target. |
| Range.Max | int | Maximum tiles from source to target. |
| Range.RequiresLos | bool | LOS check between source and target. |
| Range.LinearOnly | bool | Target must be on a cardinal/diagonal line. |
| UsesPerTurn | int = 1 | How many times per turn this may activate. |
| CostGroup | CostGroup? | Replaces Cost: CostEntry[] (see 1.2). |
AbilityRange already exists as a class with Min, Max, RequiresLos, LinearOnly. AbilityDefinition.Range is already typed AbilityRange?. AbilityDefinition.UsesPerTurn already exists (default 1).
Action: verify all four fields are populated correctly in the admin builder and serialized to JSON. The canvas AbilityMeta node for Active abilities must expose all four Range fields and UsesPerTurn (see Phase 4.5).
1.2 -- Cost Groups (AND / OR / XOR)
Current state: AbilityDefinition.Cost is CostEntry[] -- all entries paid simultaneously (implicit AND). Gap: spec requires OR/XOR so the player chooses between payment options.
New type in Action.cs:
CostGroup { LogicOp: And | Or | Xor ChooserRole: string = "Self" -- for Or/Xor: who picks the branch Entries: CostEntry[] -- leaf costs in this group Groups: CostGroup[] -- nested child groups }
AbilityDefinition change:
// Replace: public CostEntry[]? Cost { get; set; } // With: public CostGroup? CostGroup { get; set; } [Obsolete] public CostEntry[]? Cost { get; set; } // kept for EffectsJson cutover reader only
CostEntry already supports:
- Type: CostType enum (SpiritPoints, SacrificeTokens, DiscardFromHand, MillTopOfDeck, MillBottomOfDeck, SendSpiritFromBattlefieldToDiscard, DealDamageToOwnArchSpirit, DealDamageToOwnSpirit)
- Amount: int
- Filters: Filter[]? -- e.g. "discard a Spirit card" uses a CardType filter
- PickMode: CostPickMode? (Random | SelfPick | EnemySeePick | EnemyRandomPick | EnemyPick)
No changes needed to CostEntry itself. The PickMode and Filters fields already cover all interactive cost scenarios from the spec.
1.3 -- Action Groups (AND / OR / XOR)
Current state: AbilityDefinition.Actions is Action[] -- all actions execute sequentially (implicit AND). There is no ability-level grouping with OR or XOR semantics.
Gap: the spec requires AND/OR/XOR grouping for the top-level action sequence, with control over who selects which group executes.
New type in Action.cs (mirrors CostGroup structure):
ActionGroup { LogicOp: ActionGroupLogicOp -- And | Or | Xor ChooserRole: string = "Self" -- for Or/Xor: who picks which group(s) execute Actions: Action[] -- leaf actions in this group Groups: ActionGroup[] -- nested child groups }
enum ActionGroupLogicOp { And, Or, Xor }
Execution semantics: And -- all leaf Actions and all child Groups execute in order. Or -- the chooser (ChooserRole) picks exactly one leaf Action or one child Group to execute. Emits PendingActionGroupPick to the appropriate client. Xor -- same as Or; the "exclusive" intent is that only one fires and the choices are truly mutually exclusive (engine enforces; semantically equivalent to Or from a resolution standpoint).
AbilityDefinition change:
// Replace: public Action[] Actions { get; set; } = []; // With: public ActionGroup? ActionGroup { get; set; } [Obsolete] public Action[] Actions { get; set; } = []; // Backwards-compat read: if ActionGroup is null and Actions is non-empty, the // EffectsJson cutover reader wraps Actions in an ActionGroup { LogicOp=And }.
ChooserRole=Random: server picks one leaf Action or child Group immediately, no prompt. ChooserRole=Self/Opponent: emit PendingActionGroupPick to the appropriate client with the list of available choices (labels derived from Action/Group descriptions).
Relationship to ChooseOne: ActionGroup (this section): groups multiple independent action steps that may each have their own distinct targets. "Heal an ally AND draw a card" or "Heal an ally OR damage an enemy" are ActionGroup expressions. ChooseOne (existing, on Action): branches the effects within a single action step after the target is already resolved. "Deal damage OR push" to the same resolved target is a ChooseOne expression. No model change to ChooseOne needed.
1.4 -- Target Selector: Add Chooser Field
In Action.cs, add to TargetSelector:
public TargetChooser Chooser { get; set; } = TargetChooser.Self;
New enum:
public enum TargetChooser { Self, Opponent, Ally, Random }
Chooser=Random: engine resolves from the filtered pool immediately (no PendingTargetPick). Chooser=Self/Opponent/Ally: engine emits PendingTargetPick to the appropriate client.
1.5 -- ChooseOne: Add ChooserRole
In Action.cs, add to ChooseOne:
public string ChooserRole { get; set; } = "Self";
Values: "Self" | "Opponent" | "Random"
1.6 -- Trigger Event Coverage
All 40 trigger events from the spec are already present in Triggers.cs. Full list:
| Category | Type string | Status |
|---|---|---|
| Turn phase | OnTurnStart | exists |
| Turn phase | OnTurnEnd | exists |
| Channeling | OnChanneled | exists |
| ArchSpirit | OnAscend | exists |
| ArchSpirit | OnTransition | exists |
| Unit actions | OnUnitMove | exists |
| Unit actions | OnUnitAttack | exists |
| Unit actions | OnUnitAbilityActivated | exists |
| Unit actions | OnUnitMPSpent | exists |
| Damage/heal | OnDamageDealt | exists |
| Damage/heal | OnDamagePrevented | exists |
| Damage/heal | OnHealed | exists |
| Damage/heal | BeforeDamageApplied | exists |
| Damage/heal | BeforeUnitDeath | exists |
| Unit lifecycle | OnUnitEnterBattlefield | exists |
| Unit lifecycle | OnUnitLeaveBattlefield | exists |
| Unit lifecycle | OnUnitDeath | exists |
| Unit lifecycle | OnUnitSentToDiscard | exists |
| Unit lifecycle | OnSpiritSacrificed | exists |
| Unit lifecycle | OnTokenSummoned | exists |
| Unit state | OnStatModified | exists |
| Unit state | OnAbilityAdded | exists |
| Unit state | OnAbilityRemoved | exists |
| Unit state | OnGenusChanged | exists |
| Ruin | OnRuinActivation | exists |
| Ruin | OnUnitOccupyRuin | exists |
| Tile | OnTileAffinityChanged | exists |
| Player resource | OnSPGained | exists |
| Player resource | OnSPSpent | exists |
| Player resource | OnSTGained | exists |
| Player resource | OnSTSpent | exists |
| Card zone | OnCardDrawn | exists |
| Card zone | OnCardDiscarded | exists |
| Card zone | OnCardReturnedToHand | exists |
| Card zone | OnCardReturnedToDeck | exists |
| Card zone | OnDeckShuffled | exists |
| Card zone | OnCardsRevealed | exists |
| Effect/targeting | OnTargetedByAbility | exists |
| Effect/targeting | OnEffectApplied | exists |
| Aura | OnEnterAuraRange | exists |
| Aura | OnLeaveAuraRange | exists |
Enrichments needed (not new types, just new fields on existing types):
| Trigger | Enrichment |
|---|---|
| All unit-event triggers | Add Filter[]? UnitFilters -- "unit with N properties |
| op Y value" per spec (add if not already present) | |
| OnChanneledTrigger | Add Guid? CardDefinitionId for specific-card matching |
| OnRuinActivationTrigger | Add Filter[]? OccupantFilters |
| OnUnitOccupyRuinTrigger | Add Filter[]? OccupantFilters |
| OnDamageDealt/Prevented/Healed | Verify AmountComparator + Amount fields exist; |
| BeforeDamageApplied | add if missing |
| OnUnitMPSpentTrigger | Verify AmountComparator + Amount fields exist |
Trigger limit fields already exist: TriggerLimitPerTurn, TriggerLimitPerGame. SourceZoneGate already exists.
1.7 -- Condition Additions
New conditions to add to Conditions.cs:
| Name | Purpose |
|---|---|
| UnitTypeIsCondition | Subject unit type is Spirit/ArchSpirit/SpiritToken |
| OwnershipIsCondition | Subject owned by Self/Ally/Opponent |
| IsThisCardCondition | Subject is the exact source card instance |
| UnitPropertyCompareCondition | PropertyName + Comparator + ValueExpr (Damage, Defense, |
| HP, MP, AttackRange, ChannelRange -- generic) | |
| PlayerPropertyCompareCondition | Resource (SP/ST/SPAccumulation/HandSize/DeckSize/ |
| DiscardSize) + Comparator + ValueExpr | |
| HandContainsCountCondition | N cards of CardType/Affinity in hand op value |
| CardDefinitionCountInZoneCondition | X copies of this definition in Zone of Ownership |
| IsInRangeOfUnitCondition | Source within [Min,Max] of unit matching Type+Ownership |
| + optional UnitFilters | |
| TileOccupantCondition | Tile occupied by unit matching type/ownership/properties |
| SurroundingTileCondition | >= N surrounding tiles within [Min,Max] match filters |
| SPAccumulationCompareCondition | SP-per-turn vs Comparator vs value |
| CostOfCardsInHandCondition | Aggregate card cost (by type/affinity) meets comparator |
Existing composites AND/OR/XOR/NOT already exist -- no changes needed. Existing Comparator enum already has: Equal, NotEqual, LessThan, LessThanOrEqual, GreaterThan, GreaterThanOrEqual -- covers all op values from spec.
1.8 -- Effect Additions
New effects to add to Effects.cs:
| Effect | Category | Key fields |
|---|---|---|
| CloneSpiritAsTokenEffect | Token | DestinationScope: NeighborTile/RandomInChannelRange/TargetTile |
| AscendFromZoneEffect | ArchSpirit | Zone: Hand/Deck/Discard; IgnoreCost: bool |
| TransitionFromZoneEffect | ArchSpirit | Zone: Hand/Deck/Discard; IgnoreCost: bool |
| ModifyChannelRangeEffect | ArchSpirit | MinDelta: int; MaxDelta: int |
| RelocateRuinEffect | Ruin | (target from Action.Target = Tile) |
| ActivateRuinAbilityEffect | Ruin | AbilityRef: string?; Random: bool; ChooseAllTargets: bool |
| DisableRuinForDurationEffect | Ruin | Duration: DurationModel |
| ChannelCardFromZoneEffect | Zone | Zone, UnderControlOf, IgnoreChannelCost, |
| IgnoreTurnConstraint, IgnoreChannelRange, | ||
| IgnoreAffinity, KeepInZone, TargetTile, | ||
| InOwnChannelRange, InTargetChannelRange | ||
| ModifySacrificeTokenReturn | Control | (override ST returned on Spirit sacrifice) |
| DestroyTokenEffect | Token | (target from Action.Target = SpiritToken) |
| SkipTurnEffect | Player | (target from Action.Target = Player) |
| ModifyCardsDrawnThisTurnEffect | Player | Amount: ValueExpr |
| StackDeckEffect | Zone | Count: int; Chooser: string |
| SearchAndPlaceEffect | Zone | Filters, Count, Destination, ShuffleAfter |
| ChangeAttackTypeEffect | Unit | AttackType enum value |
| ObstructMovementTypeEffect | Unit | MovementType: treated as obstacle for |
| Walk/Fly etc.; Duration: DurationModel |
Existing effects needing additions: PreventNextDamageEffect -- add Times: int = 1 PreventDeathEffect -- add DamageTakenSetToHp: int?; DamageIgnored: bool
Existing minimal ChannelCardEffect: mark [Obsolete]. The builder emits ChannelCardFromZoneEffect. Old type stays deserializable for the EffectsJson cutover reader.
1.9 -- Filter Additions
Audit Filters.cs and add any missing:
CardTypeFilter -- filter Hand/Deck/Discard by CardType AffinityFilter -- filter by card/unit Affinity CostRangeFilter -- filter by SP and/or ST cost range GenusFilter -- filter by genus tag presence OwnershipFilter -- filter by unit ownership UnitPropertyFilter -- generic: PropertyName + Comparator + ValueExpr TileAffinityFilter -- filter tiles by Base1, Base2, or Resolved affinity TileOccupancyFilter -- filter tiles by occupant type/ownership/properties RangeFilter -- target within [Min,Max] tiles of source
1.10 -- AbilityDefinition Additions
// Aura -- per-unit entry/exit action lists (new) public Action[]? OnEnterAuraActions { get; set; } public Action[]? OnLeaveAuraActions { get; set; }
// Cost (replaces CostEntry[]) public CostGroup? CostGroup { get; set; }
// Action sequence (replaces Action[]) public ActionGroup? ActionGroup { get; set; } [Obsolete] public Action[] Actions { get; set; } = []; // Read rule: if ActionGroup is null and Actions is non-empty, wrap Actions in // ActionGroup { LogicOp=And } at read time. Cutover tool converts all existing data.
// Existing verified fields (no change needed): // Active: Range (AbilityRange with Min/Max/RequiresLos/LinearOnly) // UsesPerTurn (int = 1) // Aura: AuraRange, ClearOnLeave, LingerDuration // Triggered: TriggerEvent, TriggerLimitPerTurn, TriggerLimitPerGame, SourceZoneGate // All: Name, Description, Duration, Animation (AbilityAnimationDefinition) // ActivationConditions (Condition[])
// Animation -- already exists: // AbilityAnimationDefinition { AnimationTrackName, CastSoundCdnUrl, ImpactSoundCdnUrl } // AbilityDefinition.Animation: AbilityAnimationDefinition? -- already present // No model changes needed; builder must expose these fields (see Phase 4.5).
Phase 2 -- Database Migration
2.1 Add CardType.SpiritToken enum value EF migration + Postgres enum ALTER TYPE. Deck-build validator and collection-grant endpoint reject SpiritToken cards.
2.2 Hard cutover: EffectsJson -> AbilitiesJson Write SOR.Tools/Migrations/EffectsJsonCutover.cs -- standalone console app. For every card where effects_json IS NOT NULL AND abilities_json IS NULL: - Deserialize the old Action[] (or AbilityDefinition[] if mixed) - Wrap in AbilityDefinition[] with appropriate type (Active/Triggered) - Write to abilities_json After verification run: ALTER TABLE card_definitions DROP COLUMN effects_json; Remove EffectsJson from CardDefinition.cs, CardEditor.razor, AbilitySystem.cs. No dual-read shim left in place. Migration tool is idempotent and logs each card + any parse failures.
2.3 RequiresLos for Repentance/Instinct Field already exists on CardDefinition. No DB change. Engine: LOS origin = controlling player's active ArchSpirit (Resolved Decision #6). UI: add checkbox to Phase 3 editor for these card types.
2.4 OtherCostsJson audit Verify whether this column is used independently of ability CostGroup. If unused: drop in this migration. If used: document the distinction before touching.
EF migration file: Migrations/20260420_AbilityRevamp.cs DefinitionVersion trigger covers all card row updates automatically.
Phase 3 -- Card Editor Revamp (CardEditor.razor)
Design principles:
- Mobile-first: single column by default, two-column on md+
- Type-contextual: fields and sections appear/hide reactively on CardType change
- Progressive disclosure: sections collapsible; expand on demand
- Accordion layout replaces tabs so all sections visible on scroll
3.1 -- Core Info (all card types)
Name Card Type (select) -- changes CardType rerenders all conditional sections Affinity Description (art visualization textarea) SP Cost / ST Cost
3.2 -- Type-Specific Stats
If CardType == ArchSpirit: Min/Max Channel Range Tier (1-5) Previous Tier autocomplete (ArchSpirit exactly one tier lower) -- keep existing impl
If CardType is ArchSpirit or Spirit or SpiritToken: Combat: Attack Type (None / Melee / Ranged) If Ranged: Min Attack Range / Max Attack Range Damage, Health Points, Defense Movement: Movement Type Movement Points Capability flags (checkbox grid): CanAttack, CanDefend, CanBeAttacked, CanBeBlocked CanMove, CanBeObstructed, CanUseAbility, RequiresLOS CanBeSacrificed (Spirit and SpiritToken only) Genus Tags: typeahead + free create (keep existing impl)
If CardType == Terramorpha: TerramorphaMode
If CardType is Repentance or Instinct: RequiresLOS checkbox (Note: LOS is evaluated using the controlling ArchSpirit as origin -- see Resolved #6) No other stats shown for these types.
3.3 -- Abilities
The Abilities section embeds the visual builder (Phase 4).
Allowed ability types per CardType: Spirit, ArchSpirit, SpiritToken, Ruin -- Active, Triggered, Aura, Passive Instinct, Repentance -- Exactly one ability; type Active or Triggered only; ability Name is locked to card Name (not editable) Terramorpha -- Active, Triggered
Repentance/Instinct rule: these card types ARE the ability. The card has exactly one ability. Its Name property is always equal to the card Name. The Name field is read-only in the builder when editing these card types. There are no "additional" abilities.
3.4 -- Assets
No change. Keep existing CDN picker, model viewer, animation binding table.
3.5 -- Implementation Notes
Replace string[] _tabs with a collapsible accordion. Each section header shows a green check when all required fields are filled. CDN picker modal unchanged.
Phase 4 -- Visual Ability Builder
4.1 -- Architecture
AbilityBuilder.razor:
- Accepts AbilitiesJson: string (in) + AbilitiesJsonChanged: EventCallback (out)
- Same interface as today; CardEditor.razor swap is a one-line component reference change
- Internally holds List that compiles to JSON on every meaningful change
- Canvas: div position:relative / overflow:auto; nodes are div position:absolute
- No WebGL, no external library; pure CSS + Blazor + small JS shim
4.2 -- Node Types
| Node type | Color token | Purpose |
|---|---|---|
| Meta | blue | Ability name, description, type badge |
| Range | teal | RangeMin, RangeMax, RequiresLOS, LinearOnly |
| (Active only; also UsesPerTurn) | ||
| Cost | amber | CostGroup recursive builder (AND/OR/XOR) |
| Trigger | purple | TriggerEvent type + all event-specific fields |
| Condition | yellow | ConditionGroup recursive builder (AND/OR/XOR/NOT) |
| ActionGroup | green-dark | LogicOp (AND/OR/XOR) + ChooserRole; contains Action nodes |
| and/or nested ActionGroup nodes; replaces flat Action[] | ||
| Action | green | Leaf action: TargetSelector (Scope/Type/Ownership/Chooser/ |
| Count/Filters) + Duration + action-level Conditions | ||
| + ChooseOne toggle (for within-action effect branching) | ||
| Effect | red | Specific effect type + parameters (one node per effect) |
| AuraRange | teal | AuraRange Min/Max (Aura only) |
| OnEnter | green-dim | OnEnterAuraActions sub-graph (Aura only) |
| OnLeave | red-dim | OnLeaveAuraActions sub-graph (Aura only) |
| Animation | grey | AbilityAnimationDefinition: track name, cast sound URL, |
| impact sound URL (expandable section on Meta node, not | ||
| a separate draggable node) |
4.3 -- Node Layout Per Ability Type
Active ability (left to right):
[Meta + Range + UsesPerTurn] --> [Cost?] --> [ActivationCondition?] --> [ActionGroup]
|
[AND/OR/XOR header]
/
[Action 1] [Action 2]
| |
[Effect 1..N] [Effect 1..N]
Triggered ability:
[Meta] --> [Trigger] --> [TriggerCondition?] --> [ActionGroup]
|
[AND/OR/XOR header]
/
[Action 1] [Action N]
|
[Effect 1..N]
Passive ability: [Meta] --> [ActivationCondition?] --> [ActionGroup] | [AND header (implicit)] | [Action 1..N]
Aura ability: [Meta] --> [AuraRange] --> [ActivationCondition?] --> [ActionGroup (while in range)] [OnEnter ActionGroup] [OnLeave ActionGroup]
ActionGroup visual representation: The ActionGroup node renders as a bordered container with:
- A header bar showing LogicOp (AND / OR / XOR) and ChooserRole
- Child Action nodes and nested ActionGroup nodes inside the container
- An "Add Action" button and an "Add Group" button in the footer
- Connections between ActionGroup and its children are shown as containment (dashed border), not as separate edge lines, to distinguish from targeting connections
The Meta node for Active abilities includes Range and UsesPerTurn inline (not a separate node) to reduce visual noise for simple abilities. An "Expand Range" toggle reveals the full Range sub-form when needed.
4.4 -- Canvas Mechanics
Node drag: onmousedown on node header -> store (nodeId, offsetX, offsetY) in component state onmousemove on canvas -> update node.X / node.Y onmouseup -> clear drag state Touch: ontouchstart/move/end equivalents
Connection lines: SVG overlay element covering the canvas Each connection is a with cubic bezier from right-port to left-port of next node Recalculated on StateHasChanged
Zoom + pan: Canvas content wrapped in div with CSS transform: scale(zoom) translate(panX, panY) wheel event -> adjust zoom (via ability-builder.js interop) Pinch gesture -> adjust zoom (touch distance delta via ability-builder.js) Middle-mouse drag -> pan
ability-builder.js responsibilities (minimal):
- wheel / pinch zoom math
- port hit-test for connection dragging
- nothing else; all state lives in Blazor component
4.5 -- Right Panel: Property Inspector
Clicking a node selects it and opens the right panel. The panel renders a @switch on the selected node type.
Meta node fields:
- Type (select): Active / Passive / Aura / Triggered (filtered by card type)
- Name (text; read-only if Repentance or Instinct)
- Description (textarea)
- Animation sub-section (expandable): AnimationTrackName (text) CastSoundCdnUrl (text) ImpactSoundCdnUrl (text)
- For Active: Range.Min, Range.Max, Range.RequiresLos (bool), Range.LinearOnly (bool), UsesPerTurn (number, min 1)
Trigger node fields:
- TriggerEvent type picker (grouped by category matching the 40-event table in §1.5)
- Event-specific fields rendered below the picker (dynamic @switch on event type)
- TriggerLimitPerTurn (number, 0 = unlimited)
- TriggerLimitPerGame (number, 0 = unlimited)
- SourceZoneGate (multi-select: Battlefield, Hand, Deck, Discard)
Cost node (recursive CostGroupEditor component):
- LogicOp selector: AND / OR / XOR
- For OR/XOR: ChooserRole: Self / Opponent / Random
- List of CostEntry rows (Type, Amount, PickMode, Filters)
- "Add Cost" button (adds leaf CostEntry)
- "Add Group" button (nests a child CostGroup)
ActionGroup node fields (recursive ActionGroupEditor component):
- LogicOp selector: AND / OR / XOR
- For OR/XOR: ChooserRole: Self / Opponent / Random
- Child list: each child is either a leaf Action or a nested ActionGroup
- "Add Action" button (adds leaf Action)
- "Add Group" button (nests a child ActionGroup)
Action node fields (leaf; always lives inside an ActionGroup):
- Label (optional, shown as the choice text when parent ActionGroup is OR/XOR)
- Target: Scope -> Type -> Ownership -> Chooser -> Count (N / UpTo / All) -> Filters
- Duration picker
- Conditions (ConditionGroupEditor component)
- ChooseOne toggle (within-action effect branching): Off: direct Effect list On: branch list; each branch has Label + nested Action list (recursive) ChooserRole: Self / Opponent / Random
Effect node fields:
- Effect type picker (grouped by category)
- Type-specific parameter form (dynamic @switch)
- ValueExpr fields: two-mode toggle Fixed (number input) vs Ref (string input)
Condition group editor (ConditionGroupEditor component, recursive):
- LogicOp: AND / OR / XOR / NOT
- Each child: leaf condition type + parameters, or nested ConditionGroupEditor
4.6 -- Left Panel
- Ability list for this card (click to focus that ability's canvas)
- "Add Ability" button -> Choose Type modal (filtered by card type)
- Node palette grouped by category (drag to canvas or click to add)
4.7 -- Bottom Bar
- Collapsible JSON preview (read-only textarea, compiled output for current ability)
- Validation errors listed inline below JSON
4.8 -- Mobile Layout
- Narrow screens (< 768px): left and right panels collapse to a bottom sheet
- Canvas fills full width; node dimensions increase for touch targets (min 44px tap area)
- "Add node" FAB opens node palette as modal bottom sheet
- Long-press on node = select; drag from node header
Phase 5 -- AbilitySystem.cs Engine Updates
Each item is independently mergeable after Phase 1 lands.
5.1 Full interactive resolution protocol Add PendingActionGroupPick, PendingCostGroupPick, PendingBranchPick, PendingTilePick, PendingPlayerPick, PendingRevealChoicePick. All Pending* states serializable as part of GameState. Enforce TimeoutMs with server-side Random fallback. Wire TargetSelector.Chooser into PendingTargetPick emission logic.
5.1a ActionGroup resolution Replace flat Action[] iteration with recursive ActionGroup descent. AND: execute all children sequentially. OR/XOR: emit PendingActionGroupPick (ChooserRole=Self/Opponent) or pick randomly (ChooserRole=Random); resume after client responds. Backwards-compat: if ActionGroup is null, wrap Actions[] in And group.
5.2 ChooseOne.ChooserRole resolution Opponent -> emit PendingBranchPick to opponent client Random -> server picks immediately Self -> existing flow
5.3 TargetSelector.Chooser (new field) Update target resolution loop to check Chooser before emitting PendingTargetPick.
5.4 Implement CloneSpiritAsTokenEffect Reuse SummonToken infrastructure; copy stats from Spirit target.
5.5 Implement AscendFromZoneEffect / TransitionFromZoneEffect Reuse ArchSpirit tier logic; zone lookup before ascend.
5.6 Implement ModifyChannelRangeEffect Apply Min/Max delta to unit's runtime channel range state.
5.7 Implement Ruin effects RelocateRuinEffect, ActivateRuinAbilityEffect, DisableRuinForDurationEffect.
5.8 Implement ChannelCardFromZoneEffect with all flags Mark old ChannelCardEffect [Obsolete]; engine dispatches new version for all new JSON.
5.9 Implement new Condition types from §1.6 Add cases to ConditionEvaluator.cs switch.
5.10 Implement new Filter types from §1.8 Add cases to FilterResolver.cs.
5.11 OnEnterAuraActions / OnLeaveAuraActions Fire respective action lists when a unit enters or leaves aura range.
5.12 New unit/player effects from §1.7 SkipTurnEffect, ChangeAttackTypeEffect, ObstructMovementTypeEffect, ModifyCardsDrawnThisTurnEffect, StackDeckEffect, SearchAndPlaceEffect, ModifySacrificeTokenReturn, DestroyTokenEffect.
5.13 Trigger enrichments from §1.5 UnitFilters on unit-event triggers; OccupantFilters on Ruin triggers; AmountComparator on damage/heal triggers.
5.14 SpiritToken as full CardType Handle in channeling, combat, targeting, and zone-move paths.
5.15 RequiresLos for Repentance/Instinct LOS origin = controlling player's active ArchSpirit.
5.16 PreventNextDamageEffect.Times and PreventDeathEffect additions
Phase 6 -- Ruin Bug Fixes
Full detail in Ruin-IssueResolution.md. Summarized here for sequencing alongside the ability system work.
These fixes are largely independent of Phases 1-5 and can land before or alongside the model expansion. Recommended order within this phase: D -> C -> B -> A.
6-D -- Server: Stop double execution of OnRuinActivation abilities (HIGHEST PRIORITY)
File: SOR.Game/Abilities/AbilitySystem.cs
Root cause: FireRuinAbilities selects one eligible OnRuinActivation ability at random and executes it, then emits a RuinActivation trigger event. FireTrigger then scans all field cards for OnRuinActivationTrigger matches, which includes the source Ruin itself, causing its other OnRuinActivation abilities to also fire via the general trigger path.
Fix (minimal-risk): in FireTrigger, when occurrence.Kind == TriggerEventKind.RuinActivation, skip OnRuinActivationTrigger abilities on the source Ruin (where unit.InstanceId == occurrence.Data?.SourceId). Non-source observer cards continue to receive the event normally.
Interaction with Phase 1 model work: The new ActivateRuinAbilityEffect (Phase 1.8) programmatically fires a Ruin ability from an effect. It must use the same source-skip guard so it does not also double-fire through the trigger pipeline when it emits its activation event.
Acceptance criteria:
- Exactly one of the source Ruin's eligible OnRuinActivation abilities executes per tick.
- Observer cards with OnRuinActivation triggers still react to the event.
- No regression on other trigger kinds.
6-C -- Server: Enforce no-ruin tile placement
File: SOR.Game/GameEngine.cs (Ruin branch in ChannelCard)
Fix: change candidate tile set from "affinity-valid" to "affinity-valid AND tile.RuinId == null". Keep random selection among filtered candidates. Return NO_VALID_RUIN_TILE error code if filtered set is empty (distinct from generic NO_VALID_TILE for clearer client handling).
Acceptance criteria:
- A Ruin is never placed on a tile already containing another Ruin.
- Existing Ruins on the board are never overwritten by new Ruin channels.
6-B -- Client: Preflight check before sending play_card for a Ruin
File: Client/origin-client/scenes/game/game_screen.gd
Before showing the confirmation dialog (6-A), compute candidate tiles locally:
- Affinity-valid for the Ruin card
- tile.ruinId is null/empty
If no candidates: do not proceed to confirmation. Show user-facing message: "No valid tile available for this Ruin."
This is UX protection only. Server (6-C) remains authoritative.
Acceptance criteria:
- Client blocks channel attempt when zero valid no-ruin tiles exist.
- User receives a clear reason message.
6-A -- Client: Confirmation prompt before channeling a Ruin
File: Client/origin-client/scenes/game/game_screen.gd
In _on_hand_card_clicked, under cardType == "Ruin", replace the immediate send with a confirm dialog: Title: Channel Ruin? Body: Ruin placement is random. Continue? Buttons: Cancel / Channel
Only call Game.send_play_card(iid, 0, 0) on explicit Channel confirmation.
Acceptance criteria:
- Clicking a Ruin card does not instantly channel.
- Cancel does nothing.
- Confirm channels exactly once.
6 -- Test Plan
Server unit tests:
- Ruin candidate filtering: board where all affinity-valid tiles have existing Ruins returns NO_VALID_RUIN_TILE.
- Mixed board: selected tile never has RuinId set.
- Single-ability execution: Ruin with 3 eligible OnRuinActivation abilities; run turn-start activation; assert exactly 1 executes for the source Ruin.
- Observer behavior: another card's OnRuinActivation trigger still fires when the source Ruin activates.
Integration tests:
- Play Ruin from hand in a live session; confirm dialog shown; Cancel sends no request; Confirm sends request once.
- Simulate board with no valid no-ruin tiles; verify client preflight blocks send.
- Multi-turn simulation confirms one source Ruin effect per activation tick.
Phased Delivery Order
Phase 0 (cleanup) | Phase 1 (model expansion -- pure C#) | Phase 2 (DB migration) | Phase 3 (Card Editor revamp) <-- depends on Phase 2 Phase 4 (Visual Ability Builder) <-- depends on Phase 1 Phase 6 (Ruin bug fixes) <-- independent; can land any time; D before C before B before A | Phase 5 (Engine updates) <-- depends on Phase 1 + Phase 2
Phases 3, 4, and 6 run concurrently after their respective dependencies. Phase 5 sub-items are independently mergeable once Phase 1 is in. Phase 6-D should land before Phase 5.7 (ActivateRuinAbilityEffect) to ensure the source-skip guard is in place before the new effect type can trigger through it.
Files Created / Modified
| File | Action |
|---|---|
| SOR.Game/Abilities/Models/Action.cs | Add ActionGroup, ActionGroupLogicOp, CostGroup, |
| TargetChooser, ChooseOne.ChooserRole | |
| SOR.Game/Abilities/Models/AbilityDefinition.cs | Add ActionGroup, CostGroup, OnEnterAuraActions, |
| OnLeaveAuraActions; verify Range/UsesPerTurn exist; | |
| mark Actions [Obsolete] | |
| SOR.Game/Abilities/Models/Conditions.cs | Add 12 new condition types (s1.6) |
| SOR.Game/Abilities/Models/Triggers.cs | Add UnitFilters, OccupantFilters, |
| CardDefinitionId, AmountComparator fields (s1.5) | |
| SOR.Game/Abilities/Models/Effects.cs | Add 16 new effect types (s1.7) |
| SOR.Game/Abilities/Models/Filters.cs | Add 9 filter types (s1.8) |
| SOR.Database/Entities/Catalog/CardDefinition.cs | Remove EffectsJson, audit OtherCostsJson |
| SOR.Database/Enums/CardType.cs | Add SpiritToken value |
| SOR.Database/Migrations/ | EF migration 20260420_AbilityRevamp |
| SOR.Tools/Migrations/EffectsJsonCutover.cs | New: one-time migration console app (~100 cards) |
| SOR.Admin/Components/Pages/Cards/CardEditor.razor | Accordion layout revamp (Phase 3) |
| SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor | Replace with visual node builder (Phase 4) |
| SOR.Admin/wwwroot/js/ability-builder.js | New: zoom/pan/port hit-test JS interop |
| SOR.Game/Abilities/AbilitySystem.cs | Phase 5 engine updates + Phase 6-D source-skip fix |
| SOR.Game/GameEngine.cs | Phase 6-C: no-ruin tile filter + NO_VALID_RUIN_TILE error |
| Client/origin-client/scenes/game/game_screen.gd | Phase 6-A/B: Ruin confirm dialog + preflight check |
| DELETE AbilityBuilderR2-Draft.razor | Phase 0 |
| DELETE AbilityBuilderR3.razor | Phase 0 |