Commit Graph
328 Commits
Author SHA1 Message Date
aaab114a3e feat(website): add Dockerfile.website
Multi-stage build matching Dockerfile.admin pattern:
- Stage 1: restore only changed .csproj files (layer cache),
  then publish Release build
- Stage 2: aspnet:8.0 runtime, non-root appuser, port 8080

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>
2026-04-22 19:51:04 -04:00
c972b8687e feat(website): stand up SOR.Website public game site
Adds the complete SOR.Website ASP.NET Core Razor Pages project:

Security architecture:
- SecurityHeadersMiddleware sets strict CSP (script-src/style-src 'self',
  form-action 'self', frame-ancestors 'none', object-src 'none')
  — all XSS injection is dead on arrival
- __Host- cookie prefix on session + CSRF cookies (forces Secure, Path=/,
  no Domain — prevents subdomain-compromise cookie theft)
- Anti-forgery tokens on every POST by default (Razor Pages default)
- AuthorizeFolder("/Account") — unauthenticated access to any /account/*
  redirected to login at the routing layer, no per-page [Authorize] needed
- Rate limiting per-IP: login (10/5min), register (5/hr), reset (3/15min)
- Open redirect prevention: all returnUrl values checked with Url.IsLocalUrl
- Anti-enumeration: ForgotPassword/Register never reveal whether email exists
- Account lockout: 5 failed login attempts → 30min lockout
- ChangePasswordAsync requires current password before accepting new one
- Leaderboard only projects DisplayName + RankScore (email/ID never exposed)
- Data Protection keys in Redis (shared key ring across pods)
- ForwardedHeaders middleware for accurate IP under TLS-terminating ingress

Pages implemented:
- Public: Home, Story, How To Play, Cards (catalog + detail), Leaderboard,
  AI Assets (explanation + report), News, Support, Privacy, Terms, Webclient
- Auth: Login, Register, Logout (POST-only), ForgotPassword, ResetPassword,
  VerifyEmail — all with rate limiting and anti-enumeration controls
- Account (auth-gated): Overview, Profile (display name), Security
  (change password), Game stats

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>
2026-04-22 19:51:04 -04:00
ad82ac6a76 docs(admin): comprehensive help section update in AbilityBuilder
Rewrote the help offcanvas to cover every feature of the ability system:
- Canvas Mode usage guide (new section)
- Action Groups AND/OR/XOR with Chooser Role (new section)
- Costs with Cost Type and PickMode tables (new section)
- Conditions expanded with all types and key parameters
- Trigger-Specific Fields expanded into full reference table
- Effects Categories table grouping all effects
- Duration Types, Targeting, Filters updated/improved

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>
2026-04-22 15:34:10 -04:00
15f9b0c9a8 fix(ability-builder): add Condition palette button in canvas mode
The Conditions node only renders when count > 0, so there was no way to
add the first condition from the canvas. The "Add Node" palette now has a
Condition button that adds a blank ConditionDraft, lays out the node, and
auto-selects it so the inspector opens immediately for editing.

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>
2026-04-22 08:40:01 -04:00
e3e9ca66cf feat(ability-builder): full inspector parity with form view in canvas mode
Every canvas node now exposes all editable properties and delete actions
in the right-hand Inspector panel:

Meta node
  - Duration override (all types, ForNTurns N)
  - Aura type: AuraRangeMin/Max, On-Leave mode radios, linger duration

Trigger node
  - Trigger-specific parameter fields (RenderTriggerFields) wired in after
    the event type select; was previously missing entirely

Cost node (new)
  - CostGroup Logic Op + Chooser Role
  - Inline per-cost type select + amount input + per-entry delete button
  - Add Cost button

Conditions node (new)
  - Per-condition type, subject, parameter fields (RenderConditionFields)
  - Per-entry delete button
  - Add Condition button

Sub-group node
  - Delete Sub-Group button

Action / sg-action node
  - Target Filter dropdown
  - Action-level Conditions section (add / edit type+subject+params / delete)
  - Delete Action button

Effect / sg-effect node
  - Full effect parameter fields (RenderEffectFields) replacing the old
    "Switch to Form View" placeholder
  - SummonToken redirects to Form View (token editor is too wide for panel)
  - Delete Effect button

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>
2026-04-21 20:32:42 -04:00
2575d700f4 fix(ability): apply cost.Filters to interactive pick candidates and resume validation
PayCosts now filters rawCandidates through FiltersMatch before building
CandidatesJson, so only eligible cards are offered to the picker.

ResumeCostPick now deserialises FiltersJson, resolves the source unit early
for a complete filter context, and validates each client-selected card against
the stored filters before executing the cost — rejecting invalid selections
with INVALID_COST_PICK_SELECTION.

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>
2026-04-21 17:28:20 -04:00
7a917cf93b fix(ability-prompts): fix 3 client wiring gaps
1. JSON case normalization
   Parse CostGroupJson, ActionGroupJson, BranchesJson, RevealedCardsJson
   through _normalize_keys in game_screen.gd — server serialises these
   inner payloads with _jsonOpts (no naming policy = PascalCase), but the
   client was reading lowercase keys, producing empty option lists.

2. Cost pick candidate list
   - Add CandidatesJson to PendingCostPick; populated in AbilitySystem.PayCosts
     with the actor's eligible cards (hand for DiscardFromHand, field spirits
     for SendSpiritFromBattlefieldToDiscard / DealDamageToOwnSpirit).
   - Thread CandidatesJson through CostPickRequestPush → GameHandlerBase push.
   - Client _on_cost_pick_request now uses candidatesJson from the push instead
     of Game.get_my_player().hand, fixing opponent-pick and battlefield-cost UIs.

3. Reconnect recovery via game.get_state
   - Extract all pending-prompt pushes into static PushPendingPromptsAsync in
     GameHandlerBase (called from PushStateToPlayersAsync as before).
   - Inject IClientPush into GameGetStateHandler; call PushPendingPromptsAsync
     after building the reply so any active pause prompt is re-sent to the
     chooser on manual state sync / reconnect.

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>
2026-04-21 17:13:04 -04:00
c45db289ad feat(ability-prompts): wire all 8 pending pick types end-to-end
Server:
- GameMessages.cs: add push DTOs for CostGroupPick, ActionGroupPick,
  BranchPick, TargetPick, TilePick, PlayerPick, RevealChoicePick
- GameHandlerBase.PushStateToPlayersAsync: push all 8 pending types
  (including existing CostPick which was missing its push) to the
  chooser player after every state update and on reconnect

Client:
- Game.gd: add 8 signals, 8 send functions, 8 push routes matching
  game.ability.{cost,cost_group,action_group,branch,target,tile,player,
  reveal_choice}_pick_request
- game_screen.gd: add handlers for all 8 types:
  - cost_pick: hand-card selection panel with confirm
  - cost_group_pick / action_group_pick: option-button panels
  - branch_pick: same UI as local ChooseOne but sends game.branch_pick
  - target_pick: reuses ABILITY_TARGET mode, flag routes to game.target_pick
  - tile_pick: highlights valid tiles, click sends game.tile_pick
  - player_pick: player-button panel from server-supplied validPlayerIds
  - reveal_choice_pick: click-to-order card list, sends game.reveal_choice_pick

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>
2026-04-21 17:02:12 -04:00
9772679a2f feat(ability-builder): add delete buttons to all visual canvas nodes
Cost node rows now have per-item × buttons. Conditions node has a
clear-all × in the header. Sub-group action and sub-group effect nodes
both have × buttons in their headers.

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>
2026-04-21 12:38:21 -04:00
473e5b075e fix(abilities): nested pause during intra-action replay captures correct remainder
When ApplyIntraActionContinuation replays IntraActionStep items and a step's
effect itself pauses (emitting PendingTilePick / PendingPlayerPick /
PendingRevealChoicePick), the new pause model may already have an
IntraActionContinuationJson written by BuildIntraActionContinuationJson.
That value is wrong in the replay context because BuildIntraActionContinuationJson
assumes all remaining targets get the same homogeneous effect list, whereas
IntraActionStep items each carry their own per-step effect list.

Fix: convert ApplyIntraActionContinuation loops to indexed, set ctx position
fields (CurrentEffectIndex, CurrentActionAllEffects, CurrentActionTargets,
CurrentTargetIndex, CurrentActionDuration) per iteration for consistency, then
after any nested pause override the IntraActionContinuationJson directly via
new SetPendingIntraActionContinuation helper.  The override is built from the
precise remaining slice:
  - remaining effects on the current step's target  (effects[(ei+1)..])
  - all remaining steps as-is                       (steps[(si+1)..])
This is correct regardless of whether different steps have different effect lists.

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>
2026-04-21 11:30:01 -04:00
0b7742f724 fix(abilities): general intra-action continuation for effect-level pauses
Previously, pausing effects (CloneSpiritAsToken/TargetTile,
ChannelCardFromZone/TargetTile+Choice, StackDeck interactive) only stored
the outer action-sequence continuation. Any effects after the pausing one on
the same target, and any remaining targets in the same action, were silently
dropped on resume. This commit makes pause/resume fully general.

Mechanism:
- New IntraActionStep private class: { TargetRef, EffectsJson }
- BuildIntraActionContinuationJson(currentTarget, ctx) captures:
    • remaining effects on the paused target (effects[effectIndex+1..])
    • all effects applied to each remaining target (targets[targetIndex+1..])
- ApplyIntraActionContinuation applies those steps at resume time before
  the outer continuation actions
- FindTargetByRef / GetTargetRef round-trip any resolved target type
  (FieldCard, CardInstance, PlayerState, Coord) through a string ref

AbilityContext gains 5 per-iteration tracking fields set by ExecuteSingleAction:
  CurrentEffectIndex, CurrentTargetIndex, CurrentActionTargets,
  CurrentActionAllEffects, CurrentActionDuration

ExecuteSingleAction target/effect loops converted from foreach to indexed
for-loops so ctx position fields stay in sync with each ExecuteEffect call.

IntraActionContinuationJson added to PendingTilePick, PendingPlayerPick,
and PendingRevealChoicePick. All three pause-emitting cases (CloneSpiritAsToken,
ChannelCardFromZone x2, StackDeck) populate it. All three resume methods
(ResumeTilePick, ResumePlayerPick, ResumeRevealChoicePick) call
ApplyIntraActionContinuation before executing outer continuation.

ChannelCardFromZone player-pick-to-tile-pick chain now forwards
IntraActionContinuationJson so it survives a double-pause sequence.

The "DESIGN CONSTRAINT: pausing effects must be terminal" comment is removed
as it is no longer true.

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>
2026-04-21 11:12:57 -04:00
ac0215fab3 fix(abilities): pause/resume ordering and continuation correctness
Issue 1 — ActionGroup AND continuation ordering:
  The old code prepended `all` (preceding AND-group actions) into
  ContinuationActionsJson, so resume ran [chosen, preceding, outer] instead
  of the correct [preceding, chosen, outer].  Fix: add PrecedingActionsJson
  to PendingActionGroupPick; AND-case stores preceding there (prepending to
  any inner-group preceding); ResumeActionGroupPick reads it and uses
  preceding.Concat(chosen).Concat(continuation) for final execution.
  Nested remaining-group pauses also accumulate preceding correctly.

Issue 2 — Effect-level pause terminal contract:
  Documented as a design constraint: pausing effects (CloneSpiritAsToken
  TargetTile, ChannelCardFromZone TargetTile/Choice) must be last in their
  action's Effects list.  Remaining effects / remaining targets are silently
  dropped on pause.  No functional change; constraint is now explicit in code.

Issue 3 — StackDeck pause loses continuation:
  PendingRevealChoicePick already had ContinuationActionsJson/RangeJson/
  ForceDurationJson fields but StackDeckEffect never populated them and
  ResumeRevealChoicePick never executed them.  Both are now fixed: pause
  stores ctx.ContinuationActions + ctx.ActivationRange + duration; resume
  runs ExecuteActions on the stored continuation after ordering the deck.

Issue 4 — ResumeTargetPick ActionIndex=0 contract:
  Added a clear CONTRACT comment: the paused action replays at index 0, so
  the client must submit targets with ActionIndex=0 in its response.

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>
2026-04-21 07:43:22 -04:00
0e85441fa1 feat(phase10): ChannelCardFromZone, ObstructMovementType, and pause-model completions
- Implement ChannelCardFromZoneEffect: zone lookup, dest-player resolution
  (Self/Target/Opponent/Ally/Random/Choice), channel-range tile selection,
  affinity check, cost deduction, KeepInZone, TargetTile pause, board
  placement with aura/passive hooks and Channeled trigger
- Add PendingPlayerPick.EffectType="ChannelCardFromZone" dispatch in
  ResumePlayerPick: random-tile path + chained PendingTilePick for
  TargetTile=true
- Add ResumeTilePick case "ChannelCardFromZone": place card at chosen tile
  under DestPlayerAccountId, affinity/cost/KeepInZone-aware
- Implement ObstructMovementTypeEffect: stores ActiveEffect marker;
  ApplyReversal is no-op (duration:null guard); BuildBlockedSet extended
  via AbilitySystem.GetUnitsObstructingMovementType to honour obstructors
  for pathfinding (e.g. Walk unit blocking Flight paths)
- Add PendingTilePick.DestPlayerAccountId and .EffectJson fields
- Add PendingPlayerPick.EffectJson field
- Thread ctx.ContinuationActions + ctx.ActivationRange through
  AbilityContext so ExecuteEffect can populate pause models without an
  extra method parameter

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>
2026-04-21 07:34:17 -04:00
95c01cffb5 feat(phase9): ability system gap fixes -- pause propagation, handlers, chooser, aura actions
- Fix pause propagation: ExecuteActions for-loop breaks on HasPendingInteraction();
  effect loop in ExecuteSingleAction also stops when any pending state is set
- Add HasPendingInteraction() helper to GameState covering all 7 pending types
- Create 4 missing handlers: GameCostGroupPickHandler, GameActionGroupPickHandler,
  GameBranchPickHandler, GameRevealChoicePickHandler + register in ServiceRegistration
- Add corresponding request/response records to GameMessages.cs
- Fix ActionNeedsClientTargets: short-circuit false when Chooser == Random
- Add ChooserActorId to PendingTriggeredTarget; FireTrigger sets it to opponent/ally
  when Chooser.Opponent/Ally; GameHandlerBase pushes to ChooserActorId
- ResumeTriggeredAbility validates against ChooserActorId (falls back to ActorId)
- Fix ApplyOnEventEffect: Action[] -> ActionGroup?; PendingDeferredEffect gains
  ActionGroupJson field; deferred firing uses ResolveActionGroup + ExecuteActions
- Wire OnEnterAuraActions / OnLeaveAuraActions into FireAuraTransition (one-shot,
  restricted to the entering/leaving unit)

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>
2026-04-21 06:09:32 -04:00
80b92b17b9 feat(phase8): complete remaining 3 gaps -- pending types, StackDeck interactive, canvas builder
Pending interaction coverage:
- Add PendingTilePick model (tile-select pause for effects like CloneSpiritAsToken TargetTile)
- Add PendingPlayerPick model (player-select pause for ChannelCardFromZone UnderControlOf: Choice)
- Add PendingRevealChoicePick model (reveal-and-order pause for StackDeck interactive path)
- Add all three as nullable properties on GameState

StackDeckEffect interactive flow:
- Replace random-shuffle fallback with chooser-aware branching
- Self/Opponent chooser: remove top N from deck, emit PendingRevealChoicePick pause
- Random/empty chooser: random shuffle fallback (unchanged)
- Add ResumeRevealChoicePick(): restore deck in chooser's ordered indices; unspecified
  cards placed beneath chosen cards preserving relative order

Canvas AbilityBuilder (Phase 4 spec):
- Add @inject IJSRuntime + @implements IAsyncDisposable to AbilityBuilder.razor
- Add sorAdmin.abilityBuilder JS shim in admin.js: non-passive wheel listener (zoom),
  pinch-to-zoom via touch distance delta, cleanup on dispose
- Canvas mode toggle button in form toolbar ("Visual Canvas")
- Full canvas layout: left panel (ability list + node palette), main canvas, right inspector
- Dark canvas background (#111827), CSS transform pan+zoom (translate then scale)
- SVG bezier edge overlay connecting node flow (Meta→Range/Trigger→Cost→Cond→ActionGroup
  →Actions→Effects, ActionGroup→SubGroups→their Actions→their Effects)
- Node types: Meta (blue), Range (teal), Trigger (purple), Cost (amber), Conditions (yellow),
  ActionGroup (dark green), Action (green), Effect (red), SubGroup (dark green), SubGroupAction,
  SubGroupEffect -- each draggable, click-to-select
- Inspector panel: inline editing for all node types (type/name/desc, range fields, trigger
  event, group logic op, action target selector, effect type picker)
- AutoLayoutAbility() positions nodes on first focus; SetPos() preserves drag positions
- Zoom/pan: toolbar +/- buttons + scroll wheel (via JS) + middle-mouse drag
- OnCanvasWheel [JSInvokable] + DisposeAsync cleanup
- Form view toggle restores full form; JSON preview always visible

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>
2026-04-20 20:27:20 -04:00
1d5ae4aa20 feat(phase7): complete ability revamp gap items 1-11
- Fix [PolyType] attribute placement bug in Effects.cs (silent poly-deser failure)
- Add SpiritToken guard to BazaarBuyPrebuiltDeck and CollectionSelectStarterDeck handlers
- Wire CostGroup payment into ActivateAbility with PendingCostGroupPick pause support
- Add PendingActionGroupPick, PendingCostGroupPick, PendingBranchPick models + GameState props
- Add Phase 5 engine switch cases: ModifyChannelRange, RelocateRuin, ActivateRuinAbility,
  DisableRuinForDuration, CloneSpiritAsToken, DestroyToken, SkipTurn, ModifyCardsDrawnThisTurn,
  StackDeck, SearchAndPlace, ChangeAttackType, ObstructMovement, AscendFromZone stubs
- Add ActionGroup recursion (ResolveActionGroup AND-flatten / OR-XOR interactive pick)
- Add ResumeActionGroupPick, ResumeCostGroupPick, ResumeBranchPick methods
- Add ChooseOne ChooserRole branching + TargetSelector.Chooser (Random early-return)
- Change SearchDeckEffect.ThenAction → ThenGroup: ActionGroup?
- Change ApplyOnEventEffect.Effects → Actions: Action[]
- Add SOR.Tools console project with cutover-abilities command (EffectsJsonCutover)
- AbilityBuilder: add ActionGroupDraft, SubGroups, Compile Groups[], ParseJson Groups[],
  CompileActionNode/ParseActionNode helpers, nested sub-group UI section
- Add Tile.RuinDisabledUntilTurn, PlayerState.SkipTurnCount/CardsDrawnThisTurnBonus,
  CardInstance.AttackType nullable override
- Add SOR.Tools to solution

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>
2026-04-20 19:47:38 -04:00
178f5612a8 feat(phase5+6): engine ActionGroup compat, new conditions, Ruin bug fixes
Phase 5.1a — ActionGroup backward-compat in AbilitySystem:
- Add GetEffectiveActions(def): prefers ActionGroup.Actions (AND=sequential,
  OR/XOR=random pick); falls back to obsolete def.Actions for pre-Phase-1 rows.
- Wire all FireAbility, FireCardEffects, FireTrigger, FireRuinAbilities call
  sites to use GetEffectiveActions instead of def.Actions directly.

Phase 5.9 — 12 new EvaluateCondition cases (§6.6):
UnitTypeIs, OwnershipIs, IsThisCard, UnitPropertyCompare, PlayerPropertyCompare,
HandContainsCount, CardDefinitionCountInZone, IsInRangeOfUnit, TileOccupant,
SurroundingTile, SPAccumulationCompare, CostOfCardsInHand.
Add CompareInt(Comparator, int, int) helper to DRY up comparator switch.

Phase 6-D — Fix double-fire of source Ruin's OnRuinActivation abilities:
Insert source-skip guard in FireTrigger after TriggerMatches check:
skip OnRuinActivationTrigger on the card whose InstanceId == occurrence.Data.SourceId.
FireRuinAbilities already executed the chosen ability directly; the subsequent
FireTrigger is only for observer cards.

Phase 6-C — Ruin tile placement must not overwrite existing Ruins (GameEngine.cs):
Add `&& t.RuinId == null` to the validTiles Where clause.
Change error code NO_VALID_TILE → NO_VALID_RUIN_TILE for this path.

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>
2026-04-20 13:57:15 -04:00
da220f353d feat(phase4): ability builder revamp -- ActionGroup/CostGroup/TargetChooser + Phase 1 effects/conditions
- AbilityDraft: ActionGroupLogicOp/ChooserRole + CostGroupLogicOp/ChooserRole fields
- ActionDraft: Chooser field (Self/Opponent/Random) on TargetSelector
- EffectDraft: Zone, IgnoreCost, DestinationScope, AttackType new fields
- ConditionDraft: PropertyName, Value, CostType new fields
- Compile(): emits ActionGroup (replaces flat Actions[]) and CostGroup (replaces flat Cost[])
- ParseJson(): reads both new ActionGroup/CostGroup and legacy flat arrays
- New effects: AscendFromZone, TransitionFromZone, ModifyChannelRange, RelocateRuin,
  ActivateRuinAbility, DisableRuinForDuration, ChannelCardFromZone, CloneSpiritAsToken,
  DestroyToken, ModifySacrificeTokenReturn, SkipTurn, ModifyCardsDrawnThisTurn,
  StackDeck, SearchAndPlace, ChangeAttackType, ObstructMovementType
- New conditions: UnitTypeIs, OwnershipIs, IsThisCard, UnitPropertyCompare,
  PlayerPropertyCompare, HandContainsCount, CardDefinitionCountInZone,
  IsInRangeOfUnit, TileOccupant, SurroundingTile, SPAccumulationCompare, CostOfCardsInHand
- UI: ActionGroup LogicOp/Chooser above actions list; Chooser in each action target row;
  CostGroup LogicOp/Chooser in cost editor header

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>
2026-04-19 16:10:06 -04:00
405be9790a feat(phase3): card editor accordion revamp -- type-contextual, SpiritToken support
- Replace tab navigation with Bootstrap accordion (all sections open by default)
- Type-contextual Stats section: ArchSpirit+Spirit+SpiritToken show combat/movement/
  flags/genus; Terramorpha shows mode selector; Repentance/Instinct show RequiresLOS
  checkbox only with note about ArchSpirit LOS origin (Resolved Decision #6)
- CanBeSacrificed flag hidden for ArchSpirit (Spirit and SpiritToken only)
- Section completion badges: green check when Name filled / abilities JSON present /
  assets added
- Abilities section badge shows constraint reminder for Repentance/Instinct
- Replace _tabs string array with _openSections HashSet + ToggleSection helper
- Remove stale EffectsJson/CardType branching in save logic (already done Phase 2)

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>
2026-04-19 13:06:21 -04:00
768dfcee86 feat(phase2): ability revamp DB migration -- add SpiritToken, drop EffectsJson
- Add CardType.SpiritToken enum value (stored as text, no Postgres enum change)
- Drop catalog.card_definitions.effects column (migration 20260419170135)
  with safety-pass to copy any remaining effects -> abilities before drop
- Remove CardDefinition.EffectsJson property and CatalogDbContext mapping
- Remove CardInstance.EffectsJson snapshot from GameState/GameEngine
- Remove EffectsJson from all DTOs: UnitDelta, CardUpdateDto, ContentCardDto
- Remove EffectsJson from GameStateDiffer, ContentDtoMapper, CardEditor, CardReport
- Simplify AbilitySystem.FireCardEffects to use AbilitiesJson only (no fallback)
- Enforce SpiritToken exclusion in CollectionAddCardHandler (deck builds)
- Enforce SpiritToken exclusion in BazaarBuyBoosterPackHandler (pack draws)

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>
2026-04-19 13:02:24 -04:00
3b8de2deac feat(phase1): ability model expansion -- ActionGroup, CostGroup, new conditions/effects/filters
Action.cs:
  - TargetChooser enum (Self/Opponent/Ally/Random) + TargetSelector.Chooser field
    separates "whose entities qualify" from "who makes the selection"
  - ActionGroup { LogicOp(And/Or/Xor), ChooserRole, Actions[], Groups[] }
    replaces flat Action[] on AbilityDefinition; supports recursive AND/OR/XOR
  - ActionGroupLogicOp enum
  - CostGroup { LogicOp(And/Or/Xor), ChooserRole, Entries[], Groups[] }
    replaces flat CostEntry[] on AbilityDefinition
  - CostGroupLogicOp enum
  - ChooseOne.ChooserRole (within-action effect branching chooser)

AbilityDefinition.cs:
  - ActionGroup? (replaces Actions[]; old field kept [Obsolete] for migration reads)
  - CostGroup? (replaces Cost[]; old field kept [Obsolete] for migration reads)
  - OnEnterAuraActions / OnLeaveAuraActions (ActionGroup? each)

Triggers.cs:
  - OnChanneledTrigger.CardDefinitionId (specific card filter)
  - OnRuinActivationTrigger.OccupantFilters / OnUnitOccupyRuinTrigger.OccupantFilters
  - AmountComparator (Comparator enum) on OnDamageDealtTrigger, OnDamagePreventedTrigger,
    OnHealedTrigger, BeforeDamageAppliedTrigger, OnUnitMPSpentTrigger

Conditions.cs: 12 new condition types (UnitTypeIs, OwnershipIs, IsThisCard,
  UnitPropertyCompare, PlayerPropertyCompare, HandContainsCount,
  CardDefinitionCountInZone, IsInRangeOfUnit, TileOccupant, SurroundingTile,
  SPAccumulationCompare, CostOfCardsInHand)

Effects.cs: 16 new effect types across ArchSpirit zone ops (AscendFromZone,
  TransitionFromZone, ModifyChannelRange), Ruin ops (RelocateRuin,
  ActivateRuinAbility, DisableRuinForDuration), enhanced channeling
  (ChannelCardFromZone), token/spirit (CloneSpiritAsToken, DestroyToken,
  ModifySacrificeTokenReturn), player (SkipTurn, ModifyCardsDrawnThisTurn),
  zone (StackDeck, SearchAndPlace), unit (ChangeAttackType, ObstructMovementType).
  PreventDeathEffect + PreventNextDamageEffect extended with new fields.

Filters.cs: 3 new filter types (Ownership, UnitProperty, TileOccupancy)

AbilitySystem.cs + ActionCandidateGenerator.cs: #pragma disable CS0618 --
  authorized readers of backwards-compat obsolete fields

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>
2026-04-19 12:35:55 -04:00
2d02567baa chore(phase0): delete AbilityBuilderR2-Draft and AbilityBuilderR3 draft pages
No router or NavMenu references found. Safe removal.

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>
2026-04-19 12:01:16 -04:00
8f3911e881 feat(ability): implement AbilityBuilderR3 + engine additions
Engine:
- AbilityDefinition: add SourceZoneGate (zone-restricted triggers) and TriggerLimitPerGame
- Effects: add StatModOperator (Add/Subtract/Multiply/Divide/Percent) on all stat mod effects; reversal stored as delta
- Action/CostEntry: add CostPickMode enum (Random/SelfPick/EnemySeePick/EnemyRandomPick/EnemyPick)
- PendingCostPick: new model for interactive cost pause/resume (mirrors PendingTriggeredTarget)
- GameState: PendingCostPick field
- GameMessages: CostPickRequestPush, GameCostPickRequest, GameCostPickResponse records
- AbilitySystem: FireTrigger scans Hand/Discard/Deck when SourceZoneGate set; per-game trigger limit tracking; ApplyStatOperator helper; PayCosts/ResumeCostPick for interactive cost flow
- GameCostPickHandler + ServiceRegistration wiring

Admin:
- AbilityBuilderR3.razor: full ability builder at /cards/ability-builder-r3 (39 triggers, 69 effects, 32 conditions, form/canvas/mermaid modes, compiles to engine-native $type JSON)
- AbilityBuilderR2-Draft.razor: fix switch expression no-best-type error

Docs:
- BuilderR3.md: master plan document

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>
2026-04-18 20:15:13 -04:00
dingo abf2c1d96c AI Match fix 2026-04-15 12:51:14 -04:00
cdbcf5e2d1 feat(admin): end AI matches from admin portal
AiMatchService:
- GetActiveMatchesAsync: queries CustomLobbies joined to GameSessions
  to return all running AI vs AI sessions with display names.
- ForceEndMatchAsync: marks session Abandoned + lobby Completed; the AI
  polling loops detect the status change within ~1 s and exit cleanly.
- ActiveAiMatch DTO returned by both methods.

AiMatchPage:
- Active AI Matches section loads on page init and has a Refresh button;
  each row has an End button that calls ForceEndMatchAsync and refreshes.
- Created This Session table also gets an End button per row.
- Spinner shown on the End button while the request is in flight.

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>
2026-04-14 23:27:46 -04:00
affd251b10 feat(admin): add hex grid controls and block same-AI match creation
AiMatchPage:
- Add Grid Type dropdown (Square / Hexagon) and HexSides input (shown
  only when Hexagon selected) to the Board section, wired to GridType
  and HexSides in GameRules.
- Add SameAi computed property: true when both players share the same
  difficulty + strategy (i.e. resolve to the same account GUID).
- Show a warning banner and disable the Create button when SameAi,
  preventing the broken game state that occurs when a player is matched
  against itself.

AiMatchService:
- Server-side guard: throw ArgumentException if id1 == id2 so the
  broken state is impossible even if the UI check is bypassed.

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>
2026-04-14 20:39:31 -04:00
a814d2bdb9 fix(ai): respect TeamIndex for ally/enemy distinction
AiTurnContext.OpponentIds was everyone-except-self, so in team games the
AI would attack its own allies and score them as enemy material. The game
model already has TeamIndex on PlayerState and GameState.GetEnemyIds() /
AreAllies() helpers — the AI just never used them.

- AiTurnContext: use state.GetEnemyIds() so OpponentIds excludes allies
  (fixes attack targeting, threat detection, positional advance)
- MaterialScore: use state.AreAllies() so allied units/ArchSpirit score
  positively instead of as enemy material
- PositionalScore: skip allied players when collecting enemy positions

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>
2026-04-14 20:32:03 -04:00
dingo 7a88fd96b9 Highlighter issue 2026-04-14 13:16:47 -04:00
b4062d8179 feat: add active effects inspector to tile drawer
- Track active effects with human-readable labels in AbilitySystem
  (LabelFromReversal/LabelFromTick for stat mods, status flags, DOT/HOT)
- Add ActiveEffectDto to GameStateDto and GameStateDelta; delta now
  always includes the full effects list so clients are never stale
- Add ResolveLabelFromEffectJson fallback for effects stored before the
  Label field was introduced (old game sessions show correct labels)
- Client _append_active_effect_lines helper filters activeEffects by
  targetRef and appends formatted lines to the tile drawer for spirits,
  archspirits, spirit tokens, and ruins

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>
2026-04-14 11:52:37 -04:00
dingo d1a78e672a update 2026-04-14 09:41:52 -04:00
fa180a1673 fix(ai): score ArchSpirit stat buffs so ability activations are considered
MaterialScore only tracked the ArchSpirit's HP ratio. Permanent stat-buff
abilities (attack, defence, movement) produced no score gain after the
simulation, so they always lost to their ST cost (-8 ResourceScore) and
were never chosen.

Add per-point weights for Damage (×10), MaxDefense (×8), and MaxMp (×6)
on the ArchSpirit. Each weight exceeds the ResourceScore cost of 1 ST (8
pts), so a 1-ST buff ability now registers as a net positive and the
greedy engine will choose it when no stronger action is available.

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>
2026-04-14 08:53:11 -04:00
babf5f9821 fix(ai): prevent greedy engine from freezing after a high-value ability activation
When an ability activation raised the score baseline significantly (e.g.
bouncing a unit, dealing damage, healing), no subsequent move or attack
could beat that new baseline, so the AI ended its turn after just one
action leaving all other units idle.

Two-part fix:
1. Relax the selection threshold by NoRegressTolerance (1.0 pts) so that
   moves/attacks that are near-neutral still qualify as candidates.
2. Track serialised-state hashes for every state seen during the turn;
   candidates that would revisit a prior state are skipped, preventing
   the tolerance from enabling intra-turn cycles.

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>
2026-04-14 06:22:59 -04:00
e3df26ae07 fix(ai): use real ST return formula in SacrificeOpportunityScore
Previously assumed each sacrifice always yields +1 ST regardless of the
unit's costs or the player's running ST total. Now calls
SacrificeSystem.GetSacrificeValue / GetSTReturn exactly as the engine
does, and respects FixedSacrificeReturn overrides. The projected ST
total is accumulated unit-by-unit so the diminishing-return curve is
correctly applied.

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>
2026-04-13 17:58:25 -04:00
e26987e563 fix: send full state_update to spectators instead of state_delta
Spectators were receiving game.state_delta in the normal delta path,
but the client only handles game.state_update for spectator views.
Always push a full game.state_update to spectators so they see every
turn change without needing to reconnect.

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>
2026-04-13 17:22:21 -04:00
16521b47b9 fix: add proximity gradient to positional score to prevent AI stalemate
The old scoring only gave +15 when a unit was already adjacent to the enemy
ArchSpirit — no reward for closing distance from further away. This caused
both AIs to settle into a static local optimum far from each other and never
advance (observed at turn 171 with armies on opposite sides of the board).

Adds a continuous gradient: +20×(1-dist/maxDist) per unit toward enemy
ArchSpirit and +8×(1-dist/maxDist) toward nearest enemy unit. Each step
forward now gives a small positive score improvement, so the greedy engine
always has a reason to advance when no better action exists.

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>
2026-04-13 17:07:34 -04:00
f37828e809 feat: add full game rules configuration to AI match creation
AiMatchPage now includes all custom rule fields (opening hand, SP, board size,
shape, deck limits, timers, MP buff, etc.) matching the options available in
custom lobbies. AiMatchService.CreateMatchAsync accepts an optional GameRules
parameter. Reset to Default button restores standard ruleset.

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>
2026-04-13 14:11:07 -04:00
0cb889fea9 fix: add SOR.Networking.Nats.csproj to Dockerfile.admin restore layer
The restore stage only copies explicit .csproj files before running
dotnet restore. The new SOR.Networking.Nats project reference added to
SOR.Admin was missing, causing NETSDK1004 (assets file not found) at publish.

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>
2026-04-13 13:20:33 -04:00
6643f72c35 fix: remove GameAiMatchHandler that was deleted but not staged
The file was deleted locally but not included in the previous commit,
causing CI to fail with missing GameAiMatchRequest/GameAiMatchResponse types.

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>
2026-04-13 13:14:03 -04:00
210d423de6 refactor: move AI match creation to admin-only Blazor page
Removes game.ai.create_match WebSocket handler (no longer accessible to clients)
and replaces it with AiMatchService injected directly into a new admin Blazor
page at /ai/matches. Admin portal gains NATS publish capability (SOR.Networking.Nats
project reference + AddNats) so AiMatchService can emit GameStartedEvent to trigger
AiPlayerSessionManager. AiDeckResolver is made public for admin injection.

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>
2026-04-13 13:03:45 -04:00
f6e1086709 feat: add game.ai.create_match handler for AI-vs-AI spectatable matches
Adds GameAiMatchHandler (game.ai.create_match) that creates a spectatable
AI-vs-AI match without a human lobby. Resolves AI accounts and decks,
builds a minimal CustomLobby with AiSlotsJson, creates a GameSession, and
publishes GameStartedEvent so AiPlayerSessionManager starts both polling loops.
Client receives { sessionId, player1Name, player2Name } and sends game.spectate
to watch via the existing spectator infrastructure.

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>
2026-04-13 12:55:29 -04:00
365db851e2 feat(ai): activate Active abilities during turns
AiActivateAbilityAction: add Targets field (was a no-target stub).

ActionCandidateGenerator.ActivateAbilityCandidates (new):
- Iterates all field units incl. ArchSpirit
- Skips exhausted/CanUseAbility=false/disabled/uses-exhausted units
- Checks SP/ST/hand-size costs before emitting candidates
- For auto-resolved abilities (Random/Self/All targets): emits one
  null-target candidate — server resolves
- For single client-pick actions: emits one candidate per valid target
  in range, respecting TargetType (Unit/ArchSpirit/Spirit) and
  TargetOwnership (Enemy/Ally/Any)
- Multi-pick and ChooseOne: emits null, server handles
- Invalid candidates are discarded by the heuristic engine's try/catch

HeuristicDecisionEngine.ApplyAction: added AiActivateAbilityAction case
  → GameEngine.ActivateAbility (so simulation can score ability effects).

AiPlayerSession.ActionToMessage: added AiActivateAbilityAction case
  → game.activate_ability message with targets.

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>
2026-04-13 12:30:21 -04:00
d3db778c7f improve(ai): smarter heuristics + faster turn timing
ScoringFunctions improvements:
- AffinityControlScore: add cluster bonus (+1.5 per tile adjacent to
  another matching-affinity tile) so Terramorpha chaining near existing
  converted tiles scores higher than isolated placements
- ThreatScore: scale threat penalty with ArchSpirit HP — below 50% HP
  adds -40 per threat, below 25% adds -90 (AI retreats/defends when hurt
  instead of ignoring danger until death)
- ResourceScore: raise ST token value 5→8 (tokens are immediately fungible)
- SacrificeOpportunityScore (new): one-step lookahead that detects when
  sacrificing adjacent units would unlock an unaffordable card in hand;
  adds that card's estimated value so the greedy engine connects
  sacrifice→gain ST→play card chains rather than seeing sacrifice as a
  net loss

AiDifficultyProfiles: halved all timing delays across tiers 1–10
(think time and between-action delay) for faster gameplay during development

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>
2026-04-13 12:05:09 -04:00
4a1eb9472b fix(ai): replace event-driven turns with per-session polling loop
AiPlayerSession now drives its own execution via RunAsync():
- Sends game.ready, then polls DB state every 1 s
- IsMyTurn(): Placement = AI hasn't placed yet (simultaneous);
  Draw/Main = AI is the active player
- On turn detection: fires ExecuteTurnAsync in background,
  backs off to 10 s re-check (watchdog against silent failures)
- Interlocked guard prevents concurrent turn execution
- Exits cleanly on Completed/Abandoned session or GameOver phase

AiPlayerSessionManager starts RunAsync instead of SendReadyAsync,
and drops the AiTurnStartedEvent consumer entirely — polling is
resilient to missed events and handles placement without needing
GamePlaceArchSpiritHandler to publish a turn trigger.

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>
2026-04-13 09:53:00 -04:00
623acf357b fix(ai): draw first then re-evaluate Main phase plan
AiPlayerSession.ExecuteTurnAsync was computing the action plan while the
game state was still in Draw phase. ActionCandidateGenerator.All returns
only [AiDrawAction] during Draw, so the plan was always [draw, end_turn] —
the AI never moved, played cards, or attacked.

Fix: when state is Draw phase, invoke game.draw immediately, reload
StateJson from the DB (post-draw Main state), then compute the full plan
with the actual hand contents. ReloadStateAsync opens a fresh scope so it
sees the committed row the draw handler just wrote.

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>
2026-04-13 09:30:03 -04:00
0824f7d315 fix: AI turns racing across pods — only start AiPlayerSessionManager on AI pod
NatsEventBus.SubscribeAsync uses queueGroup=null, so every pod receives
every NATS event. AddAiService was guarded by IsEnabled("game"), meaning
ALL game pods also started AiPlayerSessionManager. On each AiTurnStartedEvent,
all 3 pods (2 game + 1 AI) would concurrently call ExecuteTurnAsync — causing
draw/action conflicts and the AI appearing to stall or do nothing.

Fix: remove AddHostedService from AddAiService; add it to Program.cs under
IsEnabled("ai") so only the dedicated AI pod (ENABLED_SERVICES=game,ai)
starts the session manager. Game pods still register AiPlayerSessionManager
as a Singleton (for potential injection) but never start its event loop.

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>
2026-04-13 08:55:09 -04:00
23dc7925e2 fix: arch spirit placement field name, rules lock, and AI indicator
AiPlayerSession.ExecutePlacementAsync — NullReferenceException:
  Sent { Coord = ... } but GamePlaceArchSpiritRequest.Position is the
  field name. Changed to { Position = ... }.

GameUpdateLobbyRulesHandler — rules locked after adding AI:
  GuestReady=true is set when AI joins so the game auto-starts when
  host readies, but that flag was also blocking rule edits via
  CANNOT_CHANGE_RULES_WHILE_READY. Fix: inject IAiAccountRegistry
  (optional) and only block when a HUMAN guest is ready.

CustomLobby.gd — AI indicator not showing / rules reset on refresh:
  add_ai: populate ai_slots immediately from the game.ai.add ACK
  response so _refresh_display sees the AI before the push arrives.
  update_rules + lobby_updated push: keep lobby["rules"] in sync so
  _refresh_display() doesn't clobber _current_rules with stale data.

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>
2026-04-13 08:29:41 -04:00
7eeb3acbf0 fix: AI deck sync concurrency error and arch spirit placement trigger
AiDeckResolver (DbUpdateConcurrencyException on re-add):
- ReplaceRange via EF navigation property was failing when the same AI
  account's deck was synced more than once (retry after a failed lobby
  attempt left EF's change-tracked xmin stale).
- Fix: use ExecuteDeleteAsync to delete old DeckCard rows directly
  (bypasses change tracker), then AddRange new ones without touching
  the navigation property. Fully idempotent.

GamePlaceArchSpiritHandler (AI never places ArchSpirit):
- Previous fix checked newState.ActivePlayerAccountId, which stays as P1
  throughout the simultaneous placement phase — so AI opponents in seat 1
  (guest) were never triggered.
- Fix: when !bothPlaced, scan all players for AI accounts that haven't
  placed yet and publish AiTurnStartedEvent for each. When bothPlaced,
  keep the existing check for the first active player in Draw/Main phase.

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>
2026-04-13 08:12:35 -04:00
17e1dc12d5 fix: AI opponent now auto-readies and places arch spirit
Two bugs prevented AI from participating after being added to a lobby:

1. GameAddAiHandler never set GuestReady=true (or IsReady in additional
   players JSON), so the all-ready check in GameLobbyReadyHandler never
   fired — the game never started when the host clicked ready.
   Fix: set GuestReady=true for 1v1, IsReady=true for multi-player.

2. GamePlaceArchSpiritHandler never published AiTurnStartedEvent.
   If the human places first, the AI placement turn was never triggered.
   Likewise, if the AI goes first in the Active phase after both players
   place, no event fired. Fix: check the new active player after each
   placement and publish AiTurnStartedEvent if it is an AI seat.

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>
2026-04-13 07:40:19 -04:00
030cdc634f Fix NATS registration: register BazaarDbContext in AddAiService
AiDeckResolver depends on BazaarDbContext to look up prebuilt decks, but
AddAiService never registered it. When NatsMessageRpcResponder.StartAsync
called GetServices<IMessageHandler>(), DI failed to instantiate
GameAddAiHandler (via AiDeckResolver → BazaarDbContext not found),
causing the entire NATS subscription startup to throw — leaving the AI
pod with no NATS listeners.

Fix: AddBazaarDatabase(configuration) is now called at the top of
AddAiService before any handlers are registered.

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>
2026-04-12 22:22:27 -04:00
955a44725c docs: update AI architecture plan with current status and training guide
- Phase Summary table: mark phases 1.1-4.4 as done (added 4.3 training
  pipeline and 4.4 client UI); mark 5.1-5.6 as TODO with status column
- Section 7.3: replace placeholder model spec with actual implemented
  ValueNet MLP (1024->512->256->128->1 tanh, ~920k params, ONNX contract)
- Section 7.4: replace stub pipeline with actual How to Train the AI
  guide (self-play -> export -> train_neural.py -> hot-swap); includes
  CLI flags table and iterative improvement workflow
- New section: Remaining Work (Phases 5.x) with full implementation
  detail for each pending phase: active abilities (5.1), triggered
  target selection (5.2), adaptive difficulty API (5.3), personality
  & display (5.4), counter-deck selection (5.5), initial model
  operational runbook (5.6)

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>
2026-04-12 22:11:31 -04:00