Commit Graph
510 Commits
Author SHA1 Message Date
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
3b711c8792 fix: AI pod ENABLED_SERVICES must include game to register AI handlers
The sor-ai deployment ran with ENABLED_SERVICES=ai, but AddAiService is
guarded by IsEnabled("game") in Program.cs. The AI handlers (GameAddAiHandler
etc.) were never registered, so game.ai.add fell through to NATS remote
dispatch, which timed out with "No internal service is available".

Fix: set ENABLED_SERVICES=game,ai so the AI pod registers AddGameService
(providing GameDbContext, IdentityDbContext, CollectionDbContext, CatalogDbContext
and all game message handlers) before AddAiService adds the AI-specific handlers
and session manager on top.

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:14:49 -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
540fa7d601 Client: Add AI opponent support to custom lobby
- CustomLobby.gd: add add_ai(difficulty, strategy) method sending
  game.ai.add; add ai_slots: Array state; handle game.ai.slots_changed
  push updating ai_slots and emitting ai_slots_changed signal; clear
  ai_slots in clear_state()
- LobbyRoomScreen.tscn: add AddAiBtn (Button, hidden by default) between
  guest ready indicator and additional players container
- lobby_room_screen.gd: wire AddAiBtn (host-only, visible when guest slot
  is empty and host is not ready); _on_add_ai_pressed() opens a dialog
  with OptionButton for difficulty (D1 Novice - D10 Mythic) and strategy
  (Balanced/Aggressive/Control/Ramp/Swarm); guest slot display renders
  AI name + difficulty when an AI occupies seat 1; _ai_slot_for_seat()
  helper; connect/disconnect ai_slots_changed -> _refresh_display

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 21:57:46 -04:00
d5a0efdb77 Implement AI Phase 5: Python neural training pipeline
- tools/train_neural.py: PyTorch MLP training script that reads JSONL from
  GameReplayExporter and exports a compliant ONNX model. Architecture is
  1024->512->256->128->1 (tanh) with LayerNorm + Dropout. AdamW optimizer
  with cosine LR annealing, gradient clipping, best-checkpoint restore.
  Post-export validation via onnxruntime confirms tensor names and shapes.
- tools/requirements.txt: pinned deps (torch 2.3.1, onnx 1.16.1,
  onnxruntime 1.18.0 matching the C# package, numpy 1.26.4)
- tools/README.md: end-to-end workflow docs covering self-play, data export,
  training options, deployment (hot-swap vs restart), ONNX contract table,
  and iterative training guidance

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 21:26:45 -04:00
06c61055d4 Implement AI Phase 4: Neural MCTS engine for tiers 9-10
- Add NeuralModelRegistry singleton: loads ONNX model from Ai:NeuralModelPath,
  hot-swap via ReloadAsync(), static Instance for engine access
- Add NeuralEvaluator: GameState → ONNX inference with heuristic fallback when
  no model is loaded (tiers 9-10 fully playable without a trained model)
- Add AiNeuralStartupService: loads model at startup, logs if not configured
- Add NeuralDecisionEngine: MCTS with neural leaf evaluation (400 sims/action,
  6-10s budget) replacing random rollouts with direct score estimation
- Set tiers 9-10 EngineType="Neural" in AiDifficultyProfiles
- Add AiModelPage (/ai/model): model status, hot-swap button, ONNX contract docs
- Register NeuralModelRegistry + NeuralDecisionEngine in SOR.Ai and SOR.Admin
- Add Microsoft.ML.OnnxRuntime 1.18.0 to central package versions

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 19:27:16 -04:00
70df0e0b33 AI picks prebuilt starter deck; admin deck-per-difficulty config
- AiDeckResolver: resolves which prebuilt deck an AI uses for a given
  difficulty. Checks AiDeckAssignment table first (admin-configured),
  then falls back to a random active starter deck. Creates/updates a real
  Deck row in CollectionDb so GameReadyHandler's standard path works unchanged.
- AiDeckAssignment entity + EF migration (ai_deck_assignments table): admin
  maps Difficulty 1-10 → PrebuiltDeckId; null = "random starter".
- GameAddAiHandler: replaced direct Deck lookup with AiDeckResolver.ResolveAsync.
- AiSeedStartupService: removed AiDeckSeeder call — decks are resolved
  per-game from prebuilt decks, not pre-seeded with placeholder cards.
- ServiceRegistration: registers AiDeckResolver as Scoped.
- Admin: new /ai/deck-config page (AiDeckConfigPage) showing a D1-D10 table
  with prebuilt deck dropdowns; saved via upsert. Added to AI nav section.

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 19:10:16 -04:00
3ba138e4cd Fix Dockerfile.admin: add SOR.Ai and SOR.Game to restore layer
SOR.Admin now references SOR.Ai (Phase 3 calibration pages), which
transitively depends on SOR.Game. Both csproj files must be copied
before dotnet restore or the layer cache miss causes NETSDK1004.

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 18:47:54 -04:00
27e1b7c8a3 Implement AI Phase 3: MCTS engine, ELO tracking, self-play, calibration
- MCTS (UCT) decision engine for difficulty tiers 6-8 (MctsNode, MctsSimulator,
  MonteCarloEngine); tiers 6-8 updated from Heuristic → MCTS in AiDifficultyProfiles
- AiEloService: separate ELO ledger for AI accounts (ai_elo_records table)
  so calibration games don't pollute the human RankScore leaderboard
- FinalizeGameAsync / FinalizeMultiPlayerGameAsync: AI accounts are now guarded
  from RankScore and OriginPoints adjustments (IsAi check)
- AiPlayerSessionManager: async GameEnded handler calls AiEloService
- SelfPlayRunner: pure in-process AI vs AI game loop (no DB, no NATS)
- SelfPlayOrchestrator: batch runner loading real decks from DB, parallel games
- FeatureExtractor: GameState → float[1024] feature vector for ML training
- GameReplayExporter: replays completed sessions → TrainingRecord JSONL
- TrainingDataWriter: async JSONL writer
- AiCalibrationJob: pairwise self-play calibration (D1vD2…D9vD10), writes
  AiCalibrationRun rows to GameDbContext
- EF migration: ai_elo_records + ai_calibration_runs tables applied to remote DB
- SOR.Admin: references SOR.Ai; new AI section in NavMenu with ELO Leaderboard
  and Calibration pages; SelfPlayOrchestrator + AiCalibrationJob 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 18:35:23 -04:00
57915ae6da Implement SOR.Ai Phase 2: decision engines, candidate generator, heuristic scoring
Phase 2.3 — Random & Heuristic engines:
- IAiDecisionEngine interface + AiAction discriminated union (Draw, PlayCard, Move, Attack, Sacrifice, Ascend, EndTurn)
- AiDifficultyProfile / AiDifficultyProfiles: in-code profiles for tiers 1–10 with timing, mistake rates, and scoring weights
- RandomDecisionEngine: picks random legal action each step (Difficulty 1 — Novice)
- HeuristicDecisionEngine: greedy loop with JSON-clone simulation + mistake injection (Difficulties 2–10)

Phase 2.4 — ActionCandidateGenerator:
- Enumerates all legal moves: Spirit/Terramorpha/Ruin/Repentance/Instinct channelings, movement (Walk/Flight/Jump/Teleport), attacks, sacrifices, ascends
- Delegates range/path/affinity logic to SOR.Game.Grid (Pathfinding, AttackSystem, AffinitySystem)

Phase 2.5 — Heuristic scoring:
- ScoringFunctions.Evaluate: material, affinity control, threat, positional, resource weights
- ThreatDetector: counts enemy units that can reach AI ArchSpirit (with move-into-range lookahead)

AiPlayerSession wired to select engine by difficulty profile, submit full action plan
with humanized think/action delays, and catch GameException gracefully per action.

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 15:53:13 -04:00
Shard bbe99d0685 deploy: add sor-ai deployment manifest 2026-04-12 19:42:41 +00:00
b79913e592 Add SOR.Ai.csproj to Dockerfile.host restore layer
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 15:22:44 -04:00
2a08c1b2c0 Add EF migrations for AI account fields and AiSlotsJson
- SorIdentityDbContext: IsAi (bool), AiDifficulty (int?), AiStrategy (string?) on Account
- GameDbContext: AiSlotsJson (string?) on CustomLobby

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 15:15:02 -04:00
139ba5fbf0 Implement SOR.Ai Phase 1: project scaffold, transport, seeding, lobby handlers, session manager
- New SOR.Ai project with AI account/deck seeding (50 accounts: 10 difficulty × 5 strategy)
- AiNoOpClientConnection + AiClientMessage: AI invokes game handlers in-process
- AiPlayerSessionManager: BackgroundService subscribing to GameStarted/AiTurnStarted/GameEnded
- AiPlayerSession: sends game.ready and executes turns (Phase 1 stub: pass immediately)
- Lobby handlers: game.ai.add, game.ai.remove, game.ai.configure
- IAiAccountRegistry in SOR.Shared to break circular dependency with SOR.Game
- GameEndTurnHandler + GameReadyHandler publish AiTurnStarted event when AI is active player
- Account entity: IsAi, AiDifficulty, AiStrategy columns
- CustomLobby entity: AiSlotsJson column

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 15:13:38 -04:00
dingo c3a39fd7a1 hmmm 2026-04-12 14:44:37 -04:00
d5fa790ccc Add SOR.Ai architecture plan
Full design document for the AI player system: project structure,
integration approach (AI as a real player through the existing handler
pipeline), 23 granular implementation phases across 5 tracks (scaffold,
turn pipeline, MCTS, neural engine, polish), difficulty/strategy system,
training data pipeline, and self-play calibration strategy.

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 13:36:37 -04:00
8f2a89d1a5 Fix card report ability check and add description columns
- HasAbilities now uses JsonDocument to check array length > 0, so
  cards with an empty [] don't incorrectly show as having abilities.
- Added Card Desc column/filter: whether the card's own Description
  field is non-empty.
- Added Ability Desc column/filter: whether at least one ability in the
  JSON array has a non-empty description field. Shows — when card has
  no abilities.

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-11 13:39:45 -04:00
dingo 4302a0f048 UI improvement start 2026-04-10 11:14:10 -04:00
f59f0af514 Add card reporting page and account deletion to admin panel
- /reports/cards: filterable report of all cards with columns for 3D
  model (+ AI badge), 2D art, abilities, SFX, and prebuilt deck membership.
  All entries link to card editor and deck detail pages.
- AccountDetail: danger-zone Delete Account section that cascades through
  collection, bazaar, chat, game lobbies/presets, and identity data.
  Requires typing DELETE to confirm; preserves game session history.
- NavMenu: Reports section wired up.

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-07 21:57:44 -04:00
d109cd7c0d Fix hex board template not being applied: include GridType and HexSides in snapshot
Both GameLobbyReadyHandler and MatchmakerService were building BoardTemplateSnapshot
without GridType/HexSides. FromTemplate checks HexSides > 0 to set IsTemplateBased,
so hex templates were silently treated as square grids.

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-07 20:02:27 -04:00
91f160806c Fix terramorpha TILES_NOT_ADJACENT on hex grids
IsOrthogonallyAdjacentTo uses Manhattan distance == 1, which only
covers the 4 square neighbours. The two hex-diagonal offsets (1,-1)
and (-1,+1) have Manhattan distance 2 and were rejected.

Now mirrors the existing server pattern: use HexGrid.Distance == 1
when board.HexSides > 0, fall back to IsOrthogonallyAdjacentTo for
square boards.

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-07 14:52:15 -04:00
232e06de6d Allow terramorpha to re-select first tile as third pick
For tri-morpha, tile 1 is adjacent to tile 2, so it must be a valid
choice for tile 3. The previous duplicate guard blocked this.

The adjacency check (_board_distance != 1) already prevents picking the
same tile back-to-back (distance 0), so the dedup was redundant and
only hurt the re-pick case. Removed both the click-handler guard and
the matching skip in the next-pick highlight 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-07 14:49:16 -04:00
aa8fa34a05 Fix hex grid support for movement, channeling range, and terramorpha
Movement (_bfs_path): was using 4 square directions for pathfinding,
causing units on hex grids to take indirect multi-step routes when a
single diagonal step exists. Now uses 6 hex dirs when grid is Hexagon.

Channeling (_valid_play_tiles Spirit): was using Manhattan distance
instead of hex cube distance, producing a diamond-shaped channel range
on hex boards. Now delegates to _board_distance for both grid types.

Terramorpha (three fixes):
- Initial valid-play highlights now filter by _tile_bodies so only
  real tiles are highlighted (not every grid position in the bbox)
- Adjacency validation for Di/Tri multi-pick now uses _board_distance
  instead of abs(dx)+abs(dy), enabling all 6 hex neighbours
- Next-pick highlight loop now uses 6 hex dirs and guards with
  _tile_bodies check, consistent with the reachability BFS

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-07 14:36:08 -04:00
4ac92d0139 Add hex stalagmite support for tile bottom models
- TileBottomModel gains a Shape column (Square/Hex, default Square)
  so admins can manage separate stalagmite pools per tile grid type
- EF migration 20260407153312_AddTileBottomModelShape adds the column
  with a default of 'Square' to preserve existing data
- Admin UI splits the Tile Bottom Models section into Square and Hex
  cards, each with their own Add/toggle/delete controls
- content.tile_bottoms response now returns squareUrls and hexUrls
  separately; handler queries each shape independently
- ContentCache splits into _tile_bottom_urls_square / _hex and
  get_random_tile_bottom_url() now takes a shape parameter
- game_screen: hex tiles with no 3D model now receive a hex stalagmite
  instead of silently skipping; 3D-model path passes shape_key through

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-07 11:34:46 -04:00
dingoandClaude Sonnet 4.6 be8b1f7765 Resolve merge conflict: wire HexSideLength into main's hex algorithm
Main already had the HexLine+flood-fill implementation. Resolution keeps
main's CartToHex/CubeRound local functions and zone logic, but switches
the sideLength source from _pendingHexRadius to _pendingHexSideLength and
adds _template.HexSideLength = L to persist the new field.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 18:20:59 -04:00
dingoandClaude Sonnet 4.6 1feda0a59c Switch hex polygon board from radius to side length
- Add HexSideLength property to BoardTemplate (tiles per edge)
- Add EF migration 20260406000000_AddBoardTemplateHexSideLength
- Replace NPolyInside (Euclidean circle test) with HexLine + flood-fill:
  * N corners placed at circumradius = (L-1)/(2·sin(π/N)) in hex-Cartesian
  * Corners snapped to nearest integer axial cell via HexRound
  * Perimeter built by hex-line lerp between adjacent corners
  * Interior determined by BFS flood-fill from center
- Auto-compute bounding hex radius from side length (max(L*2, ceil(circumR)+2))
- UI: expose Side Length input instead of Radius; canvas header shows L=n tiles/edge
- Zone tiles now walk along actual hex-line edges from each corner

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 18:16:03 -04:00
dingoandClaude Sonnet 4.6 a581b69c2a Fix N-gon board shape for all N using cube-lerp edge drawing
Replace the direction-snapping approach (which broke N>6 and N=5) with:

1. Place N corners as a true regular N-gon in Cartesian space (radius =
   sideLength), then snap each to the nearest hex via cube-coordinate
   rounding (CartToHex / CubeRound).
2. Draw each edge with cube-space lerp (HexLine): interpolate in cube
   coords and round at each step, producing the canonical hex-lattice
   line between any two tiles regardless of direction.
3. Flood-fill from (0,0) with the edge tiles as walls.
4. Mark absent all in-bounds tiles outside the filled region.

This correctly handles all N in [3,10] without direction quantisation
or bridging hacks.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 17:08:04 -04:00
dingoandClaude Sonnet 4.6 d00d7150bb Replace geometric NPolyInside test with walk-and-flood N-gon algorithm
ApplyHexConfig now:
1. Picks the closest hex direction (axial, pointy-top) to each of the N
   evenly-spaced target angles (360°/N · k).
2. Walks sideLength steps per side from pre-computed centred corners.
3. Bridges any gap between the end of one side and the start of the next
   by greedily stepping toward the target corner.
4. Flood-fills the interior from (0,0) stopping at the border ring.
5. Marks only the out-of-shape in-bounds tiles as absent; present tiles
   stay as default (no _tiles entry needed).

N=3 (triangle) and N=6 (hexagon) produce exact shapes with no bridging;
other N values approximate with minimal bridging tiles.
Zone generation updated to use the actual axial corner positions instead
of Cartesian vertex approximations.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 16:47:49 -04:00
dingo d28d02428d Merge pull request 'Revert BoardTemplateBuilderPage hex polygon changes' (#1) from claude/nifty-galileo into main
Reviewed-on: dingo/SOR#1
2026-04-06 00:28:35 +00:00
dingoandClaude Sonnet 4.6 aa0b893bb5 Revert BoardTemplateBuilderPage hex polygon changes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 20:26:56 -04:00
dingo 5b9970fe4b template hex builder fix2 2026-04-05 15:52:27 -04:00
dingo 323de3982d template hex builder fix 2026-04-05 14:30:00 -04:00
58c5778bfb Remove stale per-page Authorize(Roles) attributes
All 26 pages had @attribute [Authorize(Roles = "Admin,SuperAdmin")] which
conflicts with the Keycloak role sor-admin. The fallback policy in Program.cs
already enforces RequireRole("sor-admin") globally, making these attributes
redundant. Removing them fixes Access Denied for all admin pages.

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-04 14:00:03 -04:00
e4ddd801e3 Store DataProtection keys in Redis to fix cross-pod cookie decryption
Without shared key storage, pod A's cookies were unreadable by pod B, causing
an infinite OIDC redirect loop that appeared as access denied. Keys are now
persisted under SOR.Admin:DataProtection-Keys in the existing Redis instance.

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-04 13:34:44 -04:00
f9ec834a7a Add role-extraction diagnostic log to OnTicketReceived
Logs extracted Keycloak roles at login time to diagnose access-denied failures.

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-04 13:16:52 -04:00
33b544a404 Pin static OIDC config at startup to fix per-request discovery failures
Replaces the default ConfigurationManager with a FixedConfigurationManager
that returns the pre-fetched OpenIdConnectConfiguration synchronously, so
per-request GetConfigurationAsync can never fail due to network errors or
cancellation-token / lock-contention issues in the dynamic manager.

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-04 12:54:27 -04:00
63f25a3764 Log actual OIDC discovery failure at startup (SOR.Admin)
Eagerly fetch the Keycloak discovery document after app.Build() so any
network/DNS/SSL failure appears in startup logs with the real exception and
the exact URL being fetched, rather than surfacing later as the cryptic
"Cannot redirect to the authorization endpoint" message.

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-04 12:28:05 -04:00
d6b99a9fe5 Add anonymous /health endpoint for k8s probes (SOR.Admin)
Without it, liveness/readiness probe requests hit the fallback auth policy,
trigger an OIDC challenge, fail with 500, and restart the pod in a loop —
which is the root cause of the repeated auth instability.

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-04 12:16:39 -04:00
6fc711323b Add Keycloak:MetadataAddress override for in-cluster OIDC discovery (SOR.Admin)
The pod cannot reach auth.aeternalisgames.com from inside the cluster (DNS/
network policy), so the OIDC middleware fails to fetch the discovery document
and throws "Cannot redirect to the authorization endpoint".

Add optional Keycloak__MetadataAddress env var. When set, the middleware
fetches the discovery doc from that URL (internal k8s service, HTTP allowed)
while still validating JWT issuer against the public Authority URL.

Set in sor-config:
  Keycloak__MetadataAddress=http://<keycloak-service>.<ns>.svc.cluster.local:<port>/realms/aeternalis

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-04 12:07:41 -04:00
bea1de3eb8 Fail fast on missing Keycloak config; remove UseHttpsRedirection (SOR.Admin)
- Validate Keycloak:Authority and Keycloak:ClientId at startup with a clear
  InvalidOperationException. Previously a missing env var produced the cryptic
  "Cannot redirect to the authorization endpoint" error on every request.

- Remove app.UseHttpsRedirection(). The pod runs plain HTTP on :8080; TLS is
  terminated at the ingress. The middleware had no HTTPS port to redirect to,
  generating a warning on every request and potentially interfering with the
  OIDC flow.

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-04 11:32:13 -04:00
20e5f5f212 Fix role claim mapping: OnTicketReceived + JsonWebTokenHandler (SOR.Admin)
ctx.TokenEndpointResponse?.AccessToken in OnTokenValidated is not reliably
populated; if null the silent catch left the principal with no role claims,
causing 403 on every request despite successful Keycloak auth.

Switch to OnTicketReceived which fires after SaveTokens — access token is
guaranteed present via ctx.Properties.GetTokenValue("access_token").
Use JsonWebTokenHandler.ReadJsonWebToken() instead of manual base64 decode
to eliminate silent parse failures. Extracts both realm_access.roles and
groups claims so either Keycloak assignment style works.

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-04 11:26:24 -04:00
1b4a652e28 Extract Keycloak group membership as role claims (SOR.Admin)
realm_access.roles only contains directly-assigned realm roles. When the user
is a member of a Keycloak group (e.g. "sor-admin"), the group appears under
the groups claim as "/sor-admin". Parse both sources so group membership
satisfies RequireRole("sor-admin") the same way a realm role would.

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-04 11:02:30 -04:00
Shard 53f71db7ab fix(admin): require sor-admin Keycloak realm role 2026-04-04 14:40:05 +00:00
Shard c1c0908903 fix(admin): require air-admin Keycloak realm role 2026-04-04 14:38:23 +00:00
9f5bcf4d21 Fix Keycloak auth redirect loop in SOR.Admin (3 bugs)
1. Remove GetClaimsFromUserInfoEndpoint=true — the extra pod→Keycloak HTTPS
   call was throwing (SSL/network error from within the cluster), which hit the
   exception handler and triggered a protected /Error redirect, starting the loop.
   Roles are extracted from the access token payload instead (no HTTP call needed).

2. Set AccessDeniedPath=PathString.Empty on the cookie handler — the default
   /Account/AccessDenied path doesn't exist in this app, causing the cookie
   middleware to redirect there infinitely. Empty path returns 403 directly.

3. Replace UseExceptionHandler("/Error") with an inline handler — /Error is a
   protected Blazor route; redirecting to it while unauthenticated re-triggered
   the auth challenge, feeding the redirect loop. Inline handler returns 500
   without any redirect.

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-04 10:16:42 -04:00
Shard 2ec14ebbe2 fix(admin): inject Keycloak client secret into sor-admin deployment 2026-04-04 13:51:51 +00:00
6f4c729582 Fix Keycloak role extraction: use UserInfo endpoint (SOR.Admin)
OnTokenValidated + manual access-token base64 decode was unreliable.
Switch to GetClaimsFromUserInfoEndpoint=true and extract realm_access.roles
in OnUserInformationReceived where the UserInfo JSON is already parsed into
ctx.User (JsonDocument) — no manual JWT decoding needed.

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-04 09:36:33 -04:00
b8cf526022 Fix OIDC redirect_uri mismatch behind k8s ingress (SOR.Admin)
The admin pod runs plain HTTP; the ingress terminates TLS. Without forwarded
headers, ASP.NET Core built the redirect_uri as "http://control.aeternalisgames.com/signin-oidc"
but Keycloak only accepts the https:// variant, causing "invalid_redirect_uri".

Add UseForwardedHeaders() with XForwardedProto/Host/For before UseAuthentication
so the OIDC middleware sees the correct public https scheme and hostname when
constructing the callback URL.

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-04 09:20:37 -04:00