13 KiB
AbilitySystem-R2-Shard
Purpose
Implementation plan for a full R2 revamp of:
- Ability engine/schema,
- Admin New Card Flow + Ability Builder,
- Runtime client prompt/response loop,
- 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
- ArchSpirit:
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: ActionGrouplimits(perTurn,perGame,cooldownsif needed)- metadata: animation/sound hooks
3.3 Shared primitives
LogicGroup<T>withAND|OR|XORComparator(> >= == != <= <)ValueExpr(fixed|ref)TypedFilter { type, params }TargetSelectorDurationPolicySourceZoneGate(Battlefield|Hand|Discard|Deck)
3.4 Trigger contract
eventTypesourceZoneGate[](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) removeOnSourceLeavepolicy
- 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,timestampactor,subject,source,sourceZoneamount?contextmap 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:
- Cost selection (choose one cost branch)
- Card selection from hidden/private zone
- Target selection when multiple legal options
- Order/placement choices (top/bottom/random/manual order)
- Optional effects / choose-one effects
- 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
gameStateVersionwith 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:
- Identity/core fields
- Type-specific fields
- Combat/stats/tags/bools
- Ability summary and add/edit
- 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:
- user prompt text
- parser/LLM generates Draft AST + confidence/warnings
- deterministic normalizer maps Draft AST to canonical JSON
- validation pass + unresolved-slot checklist
- 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
AbilityR2SchemaAbilityBuilderGraphModeAbilityBuilderEnglishModeRuntimeInteractivePromptV2
10.3 Rollout phases
- Schema + engine primitives
- Admin form parity (no data loss)
- Prompt protocol + client handlers
- Graph mode
- English mode
- Migrate existing cards and enable by default
11) Detailed backlog (suggested epics)
Epic A — Schema/Foundation
- Define
AbilityDefinitionR2and 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
- Exact enum lists and naming (avoid future migrations for casing drift).
- Whether XOR in action groups means “exactly one” or “odd parity” (recommend exactly one).
- Hidden information policy for prompts (what opponent can see in each mode).
- Timeout/default behavior for unresolved prompts.
- Hard caps for complexity (max nodes, max nested groups) for performance safety.
13) Suggested immediate next 5 tasks
- Freeze R2 canonical schema draft (
AbilityDefinitionR2JSON schema file). - Implement typed filter registry and remove type-only filter save path.
- Add trigger
sourceZoneGateend-to-end (builder + runtime). - Build prompt envelope/response contracts in shared DTO package.
- 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.