Files
sor/AbilitySystem-R2-Shard.md
T

13 KiB

AbilitySystem-R2-Shard

Purpose

Implementation plan for a full R2 revamp of:

  1. Ability engine/schema,
  2. Admin New Card Flow + Ability Builder,
  3. Runtime client prompt/response loop,
  4. Authoring UX in both drag/drop graph mode and plain-English mode, while preserving deterministic canonical Ability JSON consumed by AbilitySystem.

1) Product outcomes (definition of done)

  • A designer can create any supported card + ability without hand-editing JSON.
  • Mobile flow is fully usable; desktop adds graph power tools.
  • Graph mode, form mode, and English mode all map to exactly the same canonical JSON.
  • Runtime can execute abilities deterministically with complete audit/debug traces.
  • Trigger/filter/condition/action systems support high complexity without schema drift.
  • Interactive effects/costs can request player input via explicit prompt contracts.

2) Architecture overview

2.1 Core principle: one canonical representation

Use a single canonical AbilityDefinitionR2 JSON contract.

All authoring surfaces are adapters:

  • Form UI ↔ Canonical JSON
  • Graph UI ↔ Canonical JSON
  • English Draft → Parsed Draft AST → Canonical JSON

No alternate persisted format.

2.2 Layers

  • Engine layer (SOR.Game)
    • Schema models
    • Trigger evaluation
    • Condition evaluation
    • Action/effect execution
    • Prompt orchestration for interactive steps
  • Admin layer (SOR.Admin)
    • New Card Flow
    • Ability Builder (form + graph + English)
    • Validation + simulation preview
  • Client/runtime layer
    • Prompt renderer and chooser UX
    • Prompt response payloads back to server
    • Latency-safe retries / idempotency

3) Canonical schema plan (R2)

3.1 Card definition (authoring-relevant)

  • id, name, cardType, affinity, description
  • art preview metadata
  • spCost, stCost
  • type-specific sections:
    • ArchSpirit: tier, minChannelRange, maxChannelRange, previousTierCardId
    • Spirit/ArchSpirit: attack/move/stats/tags/bools
    • type gated ability allowances

3.2 Ability definition root

  • id, name, description, type (Active|Triggered|Aura|Passive)
  • activationConditions: LogicGroup<ConditionClause>
  • trigger? (for Triggered/Aura boundary events)
  • aura? (for Aura)
  • passive? (for Passive)
  • cost? (main ability activation cost)
  • actions: ActionGroup
  • limits (perTurn, perGame, cooldowns if needed)
  • metadata: animation/sound hooks

3.3 Shared primitives

  • LogicGroup<T> with AND|OR|XOR
  • Comparator (> >= == != <= <)
  • ValueExpr (fixed|ref)
  • TypedFilter { type, params }
  • TargetSelector
  • DurationPolicy
  • SourceZoneGate (Battlefield|Hand|Discard|Deck)

3.4 Trigger contract

  • eventType
  • sourceZoneGate[] (explicitly supports in-hand/discard/deck triggers)
  • ownership/source/subject filters
  • optional amount/stat/cause/causedBy filters
  • limit policy (unlimited|n/turn|n/game)

3.5 Passive / Aura contract

  • Passive:
    • continuous application while source valid
    • recheck cadence (turnStart|turnEnd|both|stateChange)
    • removeOnSourceLeave policy
  • Aura:
    • minRange, maxRange
    • enter/leave trigger hooks
    • leavePolicy (removeImmediately|persist|linger + duration)

4) Trigger/event system implementation

4.1 Event bus normalization

Implement a normalized internal event envelope:

  • eventId, eventType, turnIndex, timestamp
  • actor, subject, source, sourceZone
  • amount?
  • context map for event-specific extras

4.2 Event families

Implement by family templates to reduce bespoke code:

  • Turn/lifecycle
  • Unit combat/movement
  • Battlefield state/status
  • Ability mutation/targeting
  • Ruin/occupancy
  • Tile/affinity
  • Resource economy
  • Card movement/visibility
  • Aura boundary

4.3 Safety controls

  • Retrigger/cascade guardrails (esp. Ruin/aura loops)
  • per-ability/per-source trigger counters
  • deterministic ordering and tie-breaks

5) Conditions, targeting, and filters

5.1 Conditions engine

  • Recursive logical groups
  • short-circuit evaluation
  • debug trace of each clause result

5.2 Targeting engine

  • Resolve scope → candidate set → filter pass → chooser policy → count
  • deterministic randomization via seedable RNG

5.3 Filter strategy

  • Replace type-only filter serialization with typed parameterized filters.
  • Registry-based filter factory:
    • validate params
    • compile to runtime predicate
    • expose metadata to UI editors

6) Action/effect execution pipeline

6.1 Action group execution

  • Support AND/OR/XOR action groups.
  • Choice authority configurable (self|opponent|random|system).

6.2 Effect resolution

  • Every effect receives:
    • sourceRef
    • resolved target set
    • evaluation context refs
  • effect amount can be literal or computed from refs.

6.3 Duration + cleanup

  • Central duration scheduler for temporary effects.
  • source-leave cleanup policies for passive/aura effects.

7) Interactive prompts (client orchestration)

7.1 When server must prompt client

Any runtime branch requiring human input or hidden-zone choice emits a prompt.

Primary prompt categories:

  1. Cost selection (choose one cost branch)
  2. Card selection from hidden/private zone
  3. Target selection when multiple legal options
  4. Order/placement choices (top/bottom/random/manual order)
  5. Optional effects / choose-one effects
  6. Opponent-mediated choices (enemy chooses)

7.2 Prompt envelope (server → client)

{
  "promptId": "uuid",
  "abilityInstanceId": "uuid",
  "actionNodeId": "a3",
  "promptType": "ChooseCostBranch",
  "actorPlayerId": "p1",
  "authority": "Self|Opponent",
  "expiresAt": "2026-...Z",
  "uiHints": { "title": "Pay cost", "min": 1, "max": 1 },
  "options": [
    { "optionId": "opt1", "label": "Pay 2 SP + discard 3", "metadata": {...} },
    { "optionId": "opt2", "label": "Pay 6 SP + 1 ST", "metadata": {...} }
  ],
  "legalTargets": [...],
  "gameStateVersion": 1234
}

7.3 Prompt response (client → server)

{
  "promptId": "uuid",
  "playerId": "p1",
  "selectedOptionIds": ["opt1"],
  "selectedTargetIds": ["card-7", "card-9", "card-12"],
  "ordering": ["card-12", "card-7", "card-9"],
  "clientContext": {
    "uiVersion": "x.y.z",
    "latencyMs": 88
  },
  "gameStateVersion": 1234
}

7.4 Idempotency/replay rules

  • Prompt responses are idempotent by promptId + submission hash.
  • Reject stale gameStateVersion with retry message.
  • Server returns normalized adjudication event for client reconciliation.

7.5 Prompt-specific details required

A) DiscardFromHand

Client must send:

  • chosen cards (if self-pick / enemy-visible-pick)
  • no cards needed for random modes (server rolls)
  • if enemy picks, include picker player id

B) SendSpiritFromBattlefieldToDiscard / DealDamageToOwnSpirit

Client must send (when non-random):

  • chosen unit ids
  • confirmation when effect is self-harm/sacrifice if required by UX rules

C) Choose Action Branch (AND/OR/XOR groups with chooser)

Client must send:

  • selected branch ids in execution order
  • optional target choices per branch if immediate binding is used

D) Multi-target constrained prompts

Client must send:

  • exact chosen targets count in allowed min/max
  • optional assignment map if effect needs target-role mapping

8) Admin UI implementation (mobile-first + desktop graph)

8.1 New Card Flow (wizard)

Steps:

  1. Identity/core fields
  2. Type-specific fields
  3. Combat/stats/tags/bools
  4. Ability summary and add/edit
  5. Validation + preview + save

Mobile: stepper/cards, collapsed advanced sections, sticky validation summary.

8.2 Ability Builder Form mode

Sections:

  • ability metadata
  • type-specific (active/triggered/aura/passive)
  • activation conditions (logic group editor)
  • costs (branch/group editor)
  • actions (group + per-action target/filter/effects)
  • animation/sfx mapping

8.3 Graph mode (drag/drop bubbles)

Node types:

  • Trigger node
  • Condition group node
  • Cost group node
  • Target selector node
  • Action group node
  • Effect node
  • Duration/policy node

Edges define execution/decision flow; graph compiles into same canonical JSON.

Graph constraints

  • enforce acyclic execution graph where required
  • typed edge compatibility (cannot connect invalid node ports)
  • show live JSON preview pane

8.4 English mode (plain-English authoring)

Pipeline:

  1. user prompt text
  2. parser/LLM generates Draft AST + confidence/warnings
  3. deterministic normalizer maps Draft AST to canonical JSON
  4. validation pass + unresolved-slot checklist
  5. user confirms/fixes in form/graph

Must never save raw LLM output directly; only canonicalized validated JSON.


9) Validation, testing, and tooling

9.1 Validation layers

  • schema validation (shape/types)
  • semantic validation (gates/ranges/zone legality)
  • runtime validation (can execute deterministically)

9.2 Test matrix

  • round-trip tests: form ↔ json, graph ↔ json, english ↔ json
  • trigger correctness tests per family
  • prompt contract tests with mock clients
  • property-based tests for logic groups and filter combinations
  • migration tests for legacy abilities

9.3 Dev tooling

  • Ability simulator panel in admin:
    • inject game state snapshot
    • fire test events
    • show trigger/condition/effect trace
  • JSON diff viewer pre-save

10) Migration and rollout

10.1 Backward compatibility

  • Keep R1 parser alive behind adapter.
  • Introduce R1→R2 migration transformer.
  • Flag migrated fields that were previously lossy (e.g., filter params missing).

10.2 Feature flags

  • AbilityR2Schema
  • AbilityBuilderGraphMode
  • AbilityBuilderEnglishMode
  • RuntimeInteractivePromptV2

10.3 Rollout phases

  1. Schema + engine primitives
  2. Admin form parity (no data loss)
  3. Prompt protocol + client handlers
  4. Graph mode
  5. English mode
  6. Migrate existing cards and enable by default

11) Detailed backlog (suggested epics)

Epic A — Schema/Foundation

  • Define AbilityDefinitionR2 and shared primitives
  • Implement canonical serializer/deserializer
  • Implement migration adapter R1→R2

Epic B — Trigger/Condition Runtime

  • Event envelope normalization
  • Trigger family evaluators
  • Source-zone gate support (Battlefield/Hand/Discard/Deck)
  • Trigger limits/counters

Epic C — Target/Filter Runtime

  • Typed filter registry
  • Location/ownership/range resolver
  • deterministic random selector

Epic D — Actions/Effects Runtime

  • Action group execution logic
  • Effect executor parity pass
  • duration/cleanup manager

Epic E — Prompt Protocol + Client

  • Prompt envelope API
  • Client prompt rendering for each category
  • response validation/idempotency

Epic F — Admin Builder V2 Form

  • New card wizard updates
  • ability form with reusable editors
  • validation + simulator panel

Epic G — Graph Builder

  • node palette + edge validator
  • graph↔json compiler/decompiler
  • mobile fallback/read-only mini-map

Epic H — English Authoring

  • drafting parser
  • canonicalizer
  • ambiguity resolver UI

Epic I — Docs/QA/Operations

  • author docs + trigger matrix docs
  • migration playbook
  • telemetry dashboards (prompt failures, invalid configs)

12) Open decisions to lock

  1. Exact enum lists and naming (avoid future migrations for casing drift).
  2. Whether XOR in action groups means “exactly one” or “odd parity” (recommend exactly one).
  3. Hidden information policy for prompts (what opponent can see in each mode).
  4. Timeout/default behavior for unresolved prompts.
  5. Hard caps for complexity (max nodes, max nested groups) for performance safety.

13) Suggested immediate next 5 tasks

  1. Freeze R2 canonical schema draft (AbilityDefinitionR2 JSON schema file).
  2. Implement typed filter registry and remove type-only filter save path.
  3. Add trigger sourceZoneGate end-to-end (builder + runtime).
  4. Build prompt envelope/response contracts in shared DTO package.
  5. Add round-trip tests proving no-loss serialization across builder modes.

Appendix A — Minimal canonical JSON sketch

{
  "id": "ability-123",
  "name": "Tactical Collapse",
  "type": "Triggered",
  "activationConditions": {
    "op": "AND",
    "items": [
      { "type": "IsTurn", "owner": "Self" }
    ]
  },
  "trigger": {
    "eventType": "OnUnitDeath",
    "sourceZoneGate": ["Battlefield", "Hand", "Discard", "Deck"],
    "filters": {
      "op": "AND",
      "items": [
        { "type": "OwnershipIs", "value": "Opponent" }
      ]
    },
    "limit": { "mode": "PerTurn", "count": 1 }
  },
  "actions": {
    "op": "AND",
    "items": [
      {
        "target": {
          "scope": ["Battlefield"],
          "targetType": "Spirit",
          "chooser": "Self",
          "count": { "mode": "N", "value": 1 }
        },
        "effects": [
          { "type": "DealDamage", "amount": { "fixed": 2 } }
        ]
      }
    ]
  }
}

This document is a planning blueprint; implementation details should be locked against actual engine/runtime code before final schema freeze.