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>
This commit is contained in:
dingo
2026-04-12 15:13:38 -04:00
co-authored by Claude Happy
parent c3a39fd7a1
commit 139ba5fbf0
28 changed files with 1738 additions and 2 deletions
+1
View File
@@ -8,6 +8,7 @@
<Project Path="src/SOR.Collection/SOR.Collection.csproj" /> <Project Path="src/SOR.Collection/SOR.Collection.csproj" />
<Project Path="src/SOR.Content/SOR.Content.csproj" /> <Project Path="src/SOR.Content/SOR.Content.csproj" />
<Project Path="src/SOR.Database/SOR.Database.csproj" /> <Project Path="src/SOR.Database/SOR.Database.csproj" />
<Project Path="src/SOR.Ai/SOR.Ai.csproj" />
<Project Path="src/SOR.Game/SOR.Game.csproj" /> <Project Path="src/SOR.Game/SOR.Game.csproj" />
<Project Path="src/SOR.Gateway/SOR.Gateway.csproj" /> <Project Path="src/SOR.Gateway/SOR.Gateway.csproj" />
<Project Path="src/SOR.Host/SOR.Host.csproj" /> <Project Path="src/SOR.Host/SOR.Host.csproj" />
@@ -0,0 +1,47 @@
namespace SOR.Ai.Core;
using Microsoft.EntityFrameworkCore;
using SOR.Database.Contexts;
using SOR.Shared;
/// <summary>
/// In-memory registry of all AI account IDs.
/// Loaded at startup by AiSeedStartupService; used by GameEndTurnHandler (and others)
/// to check IsAi in O(1) without a database round-trip.
///
/// Singleton. Thread-safe after Load() is called once — the HashSet is never
/// mutated after initial population.
/// </summary>
public sealed class AiAccountRegistry : IAiAccountRegistry
{
private volatile HashSet<string> _ids = [];
/// <summary>Number of registered AI accounts.</summary>
public int Count => _ids.Count;
/// <summary>
/// Returns true if the given account ID string belongs to an AI account.
/// Safe to call from any thread after Load() completes.
/// </summary>
public bool IsAi(string accountId) => _ids.Contains(accountId);
/// <summary>
/// Returns true if the given GUID belongs to an AI account.
/// </summary>
public bool IsAi(Guid accountId) => _ids.Contains(accountId.ToString());
/// <summary>
/// Populates the registry from the database. Called once at startup.
/// Synchronous because it runs in IHostedService.StartAsync before the server
/// accepts traffic — blocking here is intentional.
/// </summary>
internal void Load(SorIdentityDbContext identityDb)
{
var ids = identityDb.Users
.Where(u => u.IsAi)
.Select(u => u.Id.ToString())
.ToHashSet();
_ids = ids;
}
}
+193
View File
@@ -0,0 +1,193 @@
namespace SOR.Ai.Core;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SOR.Ai.Transport;
using SOR.Database.Enums; // GamePhase
using SOR.Game; // GameState
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
/// <summary>
/// Manages one AI-controlled seat in a single active GameSession.
///
/// Responsibilities:
/// - Submits game.ready at startup so the game can begin.
/// - Executes the AI's turn when AiPlayerSessionManager signals it.
///
/// Phase 1 stub: ExecuteTurnAsync immediately ends the turn (pass).
/// Later phases add decision logic.
/// </summary>
internal sealed class AiPlayerSession : IAsyncDisposable
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<AiPlayerSession> _logger;
private readonly CancellationTokenSource _sessionCts = new();
public Guid SessionId { get; }
public string AiAccountId { get; }
public int Difficulty { get; }
public string Strategy { get; }
public int SeatIndex { get; }
public AiPlayerSession(
Guid sessionId,
string aiAccountId,
int difficulty,
string strategy,
int seatIndex,
IServiceScopeFactory scopeFactory,
ILogger<AiPlayerSession> logger)
{
SessionId = sessionId;
AiAccountId = aiAccountId;
Difficulty = difficulty;
Strategy = strategy;
SeatIndex = seatIndex;
_scopeFactory = scopeFactory;
_logger = logger;
}
/// <summary>
/// Sends game.ready on behalf of the AI after a short humanizing delay.
/// Called once when the game session is detected by AiPlayerSessionManager.
/// </summary>
public async Task SendReadyAsync(CancellationToken appCt)
{
using var ct = CancellationTokenSource.CreateLinkedTokenSource(appCt, _sessionCts.Token);
// Short random delay before sending ready — feels more natural.
await Task.Delay(Random.Shared.Next(300, 900), ct.Token);
_logger.LogDebug("AI {Account} sending game.ready for session {Session}.",
AiAccountId, SessionId);
await InvokeHandlerAsync("game.ready",
JsonSerializer.SerializeToUtf8Bytes(new { SessionId }),
ct.Token);
}
/// <summary>
/// Executes the AI's full turn.
/// Phase 1 stub: end turn immediately (AI passes).
/// </summary>
public async Task ExecuteTurnAsync(GameState state, CancellationToken appCt)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(appCt, _sessionCts.Token);
var ct = cts.Token;
_logger.LogDebug(
"AI {Account} (seat {Seat}) taking turn {Turn} in session {Session}.",
AiAccountId, SeatIndex, state.TurnNumber, SessionId);
// Handle Placement phase separately — must place ArchSpirit before main turn.
if (state.Phase == GamePhase.Placement)
{
await ExecutePlacementAsync(state, ct);
return;
}
// Phase 1 stub: immediately end turn with a short simulated delay.
await Task.Delay(Random.Shared.Next(800, 2000), ct);
_logger.LogDebug(
"AI {Account} ending turn (stub — no decision logic yet).",
AiAccountId);
await InvokeHandlerAsync("game.end_turn",
JsonSerializer.SerializeToUtf8Bytes(new { SessionId }),
ct);
}
/// <summary>
/// Places the AI's ArchSpirit on a random valid tile in its starting zone.
/// Called during the Placement phase.
/// </summary>
private async Task ExecutePlacementAsync(GameState state, CancellationToken ct)
{
if (!state.Players.ContainsKey(AiAccountId))
{
_logger.LogWarning("AI {Account}: PlayerState not found in Placement phase.", AiAccountId);
return;
}
// Pick a random coord from the starting zone for this seat.
if (state.Board is null ||
!state.Board.StartingZones.TryGetValue(SeatIndex, out var zone) ||
zone.Count == 0)
{
_logger.LogWarning(
"AI {Account}: no starting zone for seat {Seat}.",
AiAccountId, SeatIndex);
return;
}
var zoneList = zone.ToList();
var coord = zoneList[Random.Shared.Next(zoneList.Count)];
await Task.Delay(Random.Shared.Next(400, 1200), ct);
_logger.LogDebug(
"AI {Account} placing ArchSpirit at ({X},{Y}).",
AiAccountId, coord.X, coord.Y);
await InvokeHandlerAsync("game.place_arch_spirit",
JsonSerializer.SerializeToUtf8Bytes(new { SessionId, Coord = new { coord.X, coord.Y } }),
ct);
}
/// <summary>
/// Resolves and invokes a game message handler directly in-process,
/// as if the AI were a connected client sending that message.
/// </summary>
private async Task InvokeHandlerAsync(
string messageType,
ReadOnlyMemory<byte> payload,
CancellationToken ct)
{
using var scope = _scopeFactory.CreateScope();
var handlers = scope.ServiceProvider.GetServices<IMessageHandler>();
var handler = handlers.FirstOrDefault(h => h.MessageType == messageType);
if (handler is null)
{
_logger.LogError(
"AI {Account}: no handler found for message type '{Type}'.",
AiAccountId, messageType);
return;
}
var connection = new AuthenticatedConnection(
Connection : new AiNoOpClientConnection(AiAccountId),
UserId : AiAccountId,
DisplayName : "AI",
SessionToken : string.Empty);
var message = new AiClientMessage(messageType, payload);
try
{
await handler.HandleAsync(message, connection, ct);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// Session or app shutdown — ignore.
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"AI {Account}: handler '{Type}' threw an exception.",
AiAccountId, messageType);
}
}
public void Cancel() => _sessionCts.Cancel();
public ValueTask DisposeAsync()
{
_sessionCts.Cancel();
_sessionCts.Dispose();
return ValueTask.CompletedTask;
}
}
@@ -0,0 +1,277 @@
namespace SOR.Ai.Core;
using System.Collections.Concurrent;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SOR.Database.Contexts;
using SOR.Database.Enums;
using SOR.Game;
using SOR.Shared.Nats;
using SOR.Networking.Abstractions.EventBus;
/// <summary>
/// Singleton BackgroundService that orchestrates AI player turns across all active sessions.
///
/// On startup: subscribes to NATS GameStartedEvent and AiTurnStartedEvent.
/// On GameStartedEvent: inspects the session for AI seats and creates AiPlayerSession
/// instances, then sends game.ready on behalf of each AI seat.
/// On AiTurnStartedEvent: loads the game state and calls AiPlayerSession.ExecuteTurnAsync.
/// On GameEndedEvent: disposes AI sessions for that game.
/// </summary>
public sealed class AiPlayerSessionManager : BackgroundService
{
/// <summary>Sessions keyed by sessionId. Each session may have multiple AI seats.</summary>
private readonly ConcurrentDictionary<Guid, List<AiPlayerSession>> _sessions = new();
private readonly IServiceScopeFactory _scopeFactory;
private readonly AiAccountRegistry _registry;
private readonly IEventBus _eventBus;
private readonly ILogger<AiPlayerSessionManager> _logger;
public AiPlayerSessionManager(
IServiceScopeFactory scopeFactory,
AiAccountRegistry registry,
IEventBus eventBus,
ILogger<AiPlayerSessionManager> logger)
{
_scopeFactory = scopeFactory;
_registry = registry;
_eventBus = eventBus;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("AiPlayerSessionManager started.");
// Subscribe to all three NATS subjects concurrently.
var gameStartedTask = ConsumeGameStartedAsync(stoppingToken);
var aiTurnTask = ConsumeAiTurnStartedAsync(stoppingToken);
var gameEndedTask = ConsumeGameEndedAsync(stoppingToken);
await Task.WhenAll(gameStartedTask, aiTurnTask, gameEndedTask);
_logger.LogInformation("AiPlayerSessionManager stopped.");
}
// ── Event consumers ───────────────────────────────────────────────────────
private async Task ConsumeGameStartedAsync(CancellationToken ct)
{
try
{
await foreach (var evt in _eventBus.SubscribeAsync<GameStartedEvent>(
NatsSubjects.GameStarted, ct))
{
await OnGameStartedAsync(evt, ct);
}
}
catch (OperationCanceledException) { /* normal shutdown */ }
catch (Exception ex)
{
_logger.LogError(ex, "AiPlayerSessionManager: GameStarted consumer crashed.");
}
}
private async Task ConsumeAiTurnStartedAsync(CancellationToken ct)
{
try
{
await foreach (var evt in _eventBus.SubscribeAsync<AiTurnStartedEvent>(
NatsSubjects.AiTurnStarted, ct))
{
_ = Task.Run(() => OnAiTurnStartedAsync(evt, ct), ct);
}
}
catch (OperationCanceledException) { /* normal shutdown */ }
catch (Exception ex)
{
_logger.LogError(ex, "AiPlayerSessionManager: AiTurnStarted consumer crashed.");
}
}
private async Task ConsumeGameEndedAsync(CancellationToken ct)
{
try
{
await foreach (var evt in _eventBus.SubscribeAsync<GameEndedEvent>(
NatsSubjects.GameEnded, ct))
{
OnGameEnded(evt.GameId);
}
}
catch (OperationCanceledException) { /* normal shutdown */ }
catch (Exception ex)
{
_logger.LogError(ex, "AiPlayerSessionManager: GameEnded consumer crashed.");
}
}
// ── Handlers ──────────────────────────────────────────────────────────────
private async Task OnGameStartedAsync(GameStartedEvent evt, CancellationToken ct)
{
// Load the session to find AI seats.
await using var scope = _scopeFactory.CreateAsyncScope();
var gameDb = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var session = await gameDb.GameSessions
.AsNoTracking()
.FirstOrDefaultAsync(s => s.Id == evt.GameId, ct);
if (session is null)
return;
// Identify AI seats by checking each participant against the registry.
var aiSeats = new List<(Guid accountId, int seatIndex)>();
if (_registry.IsAi(session.PlayerOneAccountId))
aiSeats.Add((session.PlayerOneAccountId, seatIndex: 0));
if (_registry.IsAi(session.PlayerTwoAccountId))
aiSeats.Add((session.PlayerTwoAccountId, seatIndex: 1));
if (!string.IsNullOrEmpty(session.AdditionalPlayersJson))
{
try
{
var addl = JsonSerializer.Deserialize<List<AdditionalPlayerRef>>(
session.AdditionalPlayersJson,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
?? [];
foreach (var p in addl)
if (_registry.IsAi(p.AccountId))
aiSeats.Add((p.AccountId, p.SeatIndex));
}
catch (Exception ex)
{
_logger.LogWarning(ex,
"AiPlayerSessionManager: could not parse AdditionalPlayersJson for session {Id}.",
session.Id);
}
}
if (aiSeats.Count == 0)
return;
// Load difficulty/strategy from the account rows.
var aiAccountIds = aiSeats.Select(s => s.accountId).ToList();
var aiAccounts = await scope.ServiceProvider
.GetRequiredService<SorIdentityDbContext>().Users
.AsNoTracking()
.Where(u => aiAccountIds.Contains(u.Id))
.ToDictionaryAsync(u => u.Id, ct);
// Look up AI slot metadata from the CustomLobby if it exists.
var lobby = await gameDb.CustomLobbies
.AsNoTracking()
.FirstOrDefaultAsync(l => l.GameSessionId == session.Id, ct);
Dictionary<Guid, (int difficulty, string strategy)> slotMeta = [];
if (lobby?.AiSlotsJson is not null)
{
try
{
var slots = JsonSerializer.Deserialize<List<AiSlotRef>>(
lobby.AiSlotsJson,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? [];
foreach (var s in slots)
slotMeta[s.AccountId] = (s.Difficulty, s.Strategy);
}
catch { /* ignore malformed */ }
}
// Build sessions.
var sessionList = new List<AiPlayerSession>();
foreach (var (accountId, seatIndex) in aiSeats)
{
if (!aiAccounts.TryGetValue(accountId, out var acct))
continue;
var difficulty = slotMeta.TryGetValue(accountId, out var meta)
? meta.difficulty : (acct.AiDifficulty ?? 1);
var strategy = slotMeta.TryGetValue(accountId, out meta)
? meta.strategy : (acct.AiStrategy ?? "Balanced");
var aiSession = new AiPlayerSession(
sessionId : session.Id,
aiAccountId : accountId.ToString(),
difficulty : difficulty,
strategy : strategy,
seatIndex : seatIndex,
scopeFactory: _scopeFactory,
logger : scope.ServiceProvider
.GetRequiredService<ILogger<AiPlayerSession>>());
sessionList.Add(aiSession);
_logger.LogInformation(
"AiPlayerSessionManager: registered AI seat {Seat} ({Strategy} D{Diff}) " +
"for session {SessionId}.",
seatIndex, strategy, difficulty, session.Id);
}
_sessions.TryAdd(session.Id, sessionList);
// Send game.ready for each AI seat.
foreach (var aiSession in sessionList)
_ = Task.Run(() => aiSession.SendReadyAsync(ct), ct);
}
private async Task OnAiTurnStartedAsync(AiTurnStartedEvent evt, CancellationToken ct)
{
if (!_sessions.TryGetValue(evt.SessionId, out var sessionList))
return;
var aiSession = sessionList.FirstOrDefault(s => s.AiAccountId == evt.AiAccountId);
if (aiSession is null)
return;
// Load current game state from the DB.
await using var scope = _scopeFactory.CreateAsyncScope();
var gameDb = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var session = await gameDb.GameSessions
.AsNoTracking()
.FirstOrDefaultAsync(s => s.Id == evt.SessionId, ct);
if (session is null || session.Status != GameSessionStatus.Active || session.StateJson is null)
return;
var state = GameEngine.Deserialize(session.StateJson);
await aiSession.ExecuteTurnAsync(state, ct);
}
private void OnGameEnded(Guid sessionId)
{
if (_sessions.TryRemove(sessionId, out var sessionList))
{
foreach (var s in sessionList)
_ = s.DisposeAsync().AsTask();
_logger.LogDebug(
"AiPlayerSessionManager: disposed {Count} AI session(s) for {SessionId}.",
sessionList.Count, sessionId);
}
}
// ── Private DTOs ──────────────────────────────────────────────────────────
private sealed class AdditionalPlayerRef
{
public Guid AccountId { get; set; }
public int SeatIndex { get; set; }
}
private sealed class AiSlotRef
{
public Guid AccountId { get; set; }
public int Difficulty { get; set; }
public string Strategy { get; set; } = string.Empty;
}
}
+37
View File
@@ -0,0 +1,37 @@
namespace SOR.Ai.Core;
using SOR.Game;
/// <summary>
/// A snapshot of the game state from one AI player's perspective.
/// Created by AiPlayerSession before each turn; passed to IAiDecisionEngine.
/// Immutable — the engine must not mutate the State field directly.
/// </summary>
public sealed class AiTurnContext
{
public AiTurnContext(GameState state, string aiAccountId)
{
State = state;
AiAccountId = aiAccountId;
AiPlayer = state.Players[aiAccountId];
OpponentIds = state.Players.Keys
.Where(k => k != aiAccountId && !state.Players[k].IsEliminated)
.ToList();
Rules = state.Rules;
}
/// <summary>Full game state at the start of the AI's turn. Do not mutate.</summary>
public GameState State { get; }
/// <summary>This AI's account ID string.</summary>
public string AiAccountId { get; }
/// <summary>Convenience accessor for this AI's PlayerState.</summary>
public PlayerState AiPlayer { get; }
/// <summary>Account IDs of non-eliminated opponents.</summary>
public IReadOnlyList<string> OpponentIds { get; }
/// <summary>Effective rules for this game.</summary>
public GameRules Rules { get; }
}
@@ -0,0 +1,201 @@
namespace SOR.Ai.Handlers;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using SOR.Ai.Lobby;
using SOR.Ai.Seeding;
using SOR.Database.Contexts;
using SOR.Database.Enums;
using SOR.Game;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// game.ai.add — lobby host adds an AI player to an open custom lobby.
///
/// The AI account is inserted into the lobby's GuestAccountId (2-player lobby)
/// or AdditionalPlayersJson (3+ player lobby) so the existing game-start flow
/// picks it up exactly like a human guest.
/// </summary>
internal sealed class GameAddAiHandler : IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly GameDbContext _gameDb;
private readonly SorIdentityDbContext _identityDb;
private readonly CollectionDbContext _collectionDb;
private readonly IClientPush _clientPush;
private readonly AiSlotAssigner _assigner;
private readonly AiLobbyService _lobbyService;
public GameAddAiHandler(
IMessageSerializer serializer,
GameDbContext gameDb,
SorIdentityDbContext identityDb,
CollectionDbContext collectionDb,
IClientPush clientPush,
AiSlotAssigner assigner,
AiLobbyService lobbyService)
{
_serializer = serializer;
_gameDb = gameDb;
_identityDb = identityDb;
_collectionDb = collectionDb;
_clientPush = clientPush;
_assigner = assigner;
_lobbyService = lobbyService;
}
public string MessageType => "game.ai.add";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<GameAddAiRequest>(message.Payload);
var requesterId = Guid.Parse(connection.UserId);
if (req.Difficulty is < 1 or > 10)
throw new GameException("INVALID_DIFFICULTY");
if (!AiAccountSeeder.Strategies.Contains(req.Strategy))
throw new GameException("INVALID_STRATEGY");
var lobby = await _gameDb.CustomLobbies.FindAsync([req.LobbyId], ct)
?? throw new GameException("LOBBY_NOT_FOUND");
if (lobby.HostAccountId != requesterId)
throw new GameException("NOT_LOBBY_HOST");
if (lobby.Status is not (CustomLobbyStatus.Open or CustomLobbyStatus.Full))
throw new GameException("LOBBY_NOT_MODIFIABLE");
// Existing slot list and additional players.
var currentSlots = _lobbyService.GetSlots(lobby);
var addlPlayers = DeserializeAdditional(lobby.AdditionalPlayersJson);
// Total current seats = host + optional guest + additional players.
int currentCount = 1
+ (lobby.GuestAccountId.HasValue ? 1 : 0)
+ addlPlayers.Count;
if (currentCount >= lobby.MaxPlayers)
throw new GameException("LOBBY_FULL");
// Resolve the AI account and its deck.
var aiAccount = await _assigner.GetAiAccountAsync(req.Difficulty, req.Strategy, ct);
var aiId = aiAccount.Id;
var deckId = await _collectionDb.Decks
.AsNoTracking()
.Where(d => d.AccountId == aiId)
.Select(d => d.Id)
.FirstOrDefaultAsync(ct);
if (deckId == Guid.Empty)
throw new GameException("AI_DECK_NOT_FOUND");
// Assign the AI to the correct slot.
int seatIndex;
if (!lobby.GuestAccountId.HasValue && lobby.MaxPlayers == 2)
{
// Standard 1v1: AI becomes the guest.
lobby.GuestAccountId = aiId;
lobby.GuestDeckId = deckId;
lobby.Status = CustomLobbyStatus.Full;
seatIndex = 1;
}
else
{
// Multi-player: AI goes into AdditionalPlayersJson.
seatIndex = 1 + (lobby.GuestAccountId.HasValue ? 1 : 0) + addlPlayers.Count;
addlPlayers.Add(new AdditionalLobbyPlayer
{
AccountId = aiId,
DeckId = deckId,
SeatIndex = seatIndex,
TeamIndex = seatIndex % Math.Max(1, lobby.TeamCount),
});
lobby.AdditionalPlayersJson = JsonSerializer.Serialize(addlPlayers);
if (currentCount + 1 >= lobby.MaxPlayers)
lobby.Status = CustomLobbyStatus.Full;
}
// Track the AI slot so AiPlayerSessionManager identifies it after game start.
currentSlots.Add(new AiLobbySlot
{
AccountId = aiId,
Difficulty = req.Difficulty,
Strategy = req.Strategy,
SeatIndex = seatIndex,
});
_lobbyService.SetSlots(lobby, currentSlots);
await _gameDb.SaveChangesAsync(ct);
// Push updated AI slot list to all human lobby members.
var slotDtos = ToSlotDtos(currentSlots);
var push = ServerMessage.Push("game.ai.slots_changed",
new CustomLobbyAiSlotsChangedPush(lobby.Id, slotDtos));
await PushToAllMembersAsync(lobby, addlPlayers, push, ct);
var displayName = aiAccount.DisplayName ?? aiAccount.UserName ?? aiId.ToString();
return ServerMessage.Reply("game.ai.add.ack", message.Seq,
new GameAddAiResponse(aiId, displayName, seatIndex));
}
// ── Shared helpers ────────────────────────────────────────────────────────
internal static IReadOnlyList<AiSlotInfo> ToSlotDtos(List<AiLobbySlot> slots) =>
slots.Select(s => new AiSlotInfo(
s.AccountId,
AiAccountSeeder.DisplayName(s.Difficulty, s.Strategy),
s.Difficulty,
s.Strategy,
s.SeatIndex)).ToList();
internal static List<AdditionalLobbyPlayer> DeserializeAdditional(string? json)
{
if (string.IsNullOrEmpty(json)) return [];
try
{
return JsonSerializer.Deserialize<List<AdditionalLobbyPlayer>>(
json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) ?? [];
}
catch { return []; }
}
internal async Task PushToAllMembersAsync(
SOR.Database.Entities.Game.CustomLobby lobby,
List<AdditionalLobbyPlayer> additionalPlayers,
IServerMessage msg,
CancellationToken ct)
{
var tasks = new List<Task>
{
_clientPush.PushAsync(lobby.HostAccountId.ToString(), msg, ct),
};
if (lobby.GuestAccountId.HasValue)
tasks.Add(_clientPush.PushAsync(lobby.GuestAccountId.Value.ToString(), msg, ct));
foreach (var p in additionalPlayers)
tasks.Add(_clientPush.PushAsync(p.AccountId.ToString(), msg, ct));
await Task.WhenAll(tasks);
}
internal sealed class AdditionalLobbyPlayer
{
public Guid AccountId { get; set; }
public Guid DeckId { get; set; }
public int SeatIndex { get; set; }
public int TeamIndex { get; set; }
}
}
@@ -0,0 +1,129 @@
namespace SOR.Ai.Handlers;
using SOR.Ai.Lobby;
using SOR.Ai.Seeding;
using SOR.Database.Contexts;
using SOR.Database.Enums;
using SOR.Game;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// game.ai.configure — lobby host changes the difficulty or strategy of an AI slot
/// before the game starts. The underlying AI account ID may change (different account
/// per difficulty/strategy combination), but the seat index stays the same.
/// </summary>
internal sealed class GameConfigureAiHandler : IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly GameDbContext _gameDb;
private readonly SorIdentityDbContext _identityDb;
private readonly IClientPush _clientPush;
private readonly AiSlotAssigner _assigner;
private readonly AiLobbyService _lobbyService;
public GameConfigureAiHandler(
IMessageSerializer serializer,
GameDbContext gameDb,
SorIdentityDbContext identityDb,
IClientPush clientPush,
AiSlotAssigner assigner,
AiLobbyService lobbyService)
{
_serializer = serializer;
_gameDb = gameDb;
_identityDb = identityDb;
_clientPush = clientPush;
_assigner = assigner;
_lobbyService = lobbyService;
}
public string MessageType => "game.ai.configure";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<GameConfigureAiRequest>(message.Payload);
var requesterId = Guid.Parse(connection.UserId);
if (req.Difficulty is not null && req.Difficulty is < 1 or > 10)
throw new GameException("INVALID_DIFFICULTY");
if (req.Strategy is not null && !AiAccountSeeder.Strategies.Contains(req.Strategy))
throw new GameException("INVALID_STRATEGY");
var lobby = await _gameDb.CustomLobbies.FindAsync([req.LobbyId], ct)
?? throw new GameException("LOBBY_NOT_FOUND");
if (lobby.HostAccountId != requesterId)
throw new GameException("NOT_LOBBY_HOST");
if (lobby.Status is not (CustomLobbyStatus.Open or CustomLobbyStatus.Full))
throw new GameException("LOBBY_NOT_MODIFIABLE");
var currentSlots = _lobbyService.GetSlots(lobby);
var slot = currentSlots.FirstOrDefault(s => s.AccountId == req.AiAccountId)
?? throw new GameException("AI_SLOT_NOT_FOUND");
// Resolve the new difficulty / strategy (default to current if not changed).
int newDifficulty = req.Difficulty ?? slot.Difficulty;
string newStrategy = req.Strategy ?? slot.Strategy;
if (newDifficulty == slot.Difficulty && newStrategy == slot.Strategy)
// Nothing changed.
return ServerMessage.Reply("game.ai.configure.ack", message.Seq,
new GameConfigureAiResponse(true));
// The new combination may map to a different AI account ID.
var newAccount = await _assigner.GetAiAccountAsync(newDifficulty, newStrategy, ct);
var oldId = slot.AccountId;
var newId = newAccount.Id;
// Swap the account ID in the guest slot or additional players list.
if (lobby.GuestAccountId == oldId)
{
lobby.GuestAccountId = newId;
}
else
{
var addl = GameAddAiHandler.DeserializeAdditional(lobby.AdditionalPlayersJson);
var entry = addl.FirstOrDefault(p => p.AccountId == oldId);
if (entry is not null)
entry.AccountId = newId;
lobby.AdditionalPlayersJson = System.Text.Json.JsonSerializer.Serialize(addl);
}
// Update the AI slot metadata.
slot.AccountId = newId;
slot.Difficulty = newDifficulty;
slot.Strategy = newStrategy;
_lobbyService.SetSlots(lobby, currentSlots);
await _gameDb.SaveChangesAsync(ct);
// Push updated slot list to all human members.
var addlAfter = GameAddAiHandler.DeserializeAdditional(lobby.AdditionalPlayersJson);
var slotDtos = GameAddAiHandler.ToSlotDtos(currentSlots);
var push = ServerMessage.Push("game.ai.slots_changed",
new CustomLobbyAiSlotsChangedPush(lobby.Id, slotDtos));
var tasks = new List<Task>
{
_clientPush.PushAsync(lobby.HostAccountId.ToString(), push, ct),
};
if (lobby.GuestAccountId.HasValue)
tasks.Add(_clientPush.PushAsync(lobby.GuestAccountId.Value.ToString(), push, ct));
foreach (var p in addlAfter)
tasks.Add(_clientPush.PushAsync(p.AccountId.ToString(), push, ct));
await Task.WhenAll(tasks);
return ServerMessage.Reply("game.ai.configure.ack", message.Seq,
new GameConfigureAiResponse(true));
}
}
@@ -0,0 +1,107 @@
namespace SOR.Ai.Handlers;
using System.Text.Json;
using SOR.Ai.Lobby;
using SOR.Database.Contexts;
using SOR.Database.Enums;
using SOR.Game;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// game.ai.remove — lobby host removes an AI player from the lobby.
/// </summary>
internal sealed class GameRemoveAiHandler : IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly GameDbContext _gameDb;
private readonly IClientPush _clientPush;
private readonly AiLobbyService _lobbyService;
public GameRemoveAiHandler(
IMessageSerializer serializer,
GameDbContext gameDb,
IClientPush clientPush,
AiLobbyService lobbyService)
{
_serializer = serializer;
_gameDb = gameDb;
_clientPush = clientPush;
_lobbyService = lobbyService;
}
public string MessageType => "game.ai.remove";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<GameRemoveAiRequest>(message.Payload);
var requesterId = Guid.Parse(connection.UserId);
var lobby = await _gameDb.CustomLobbies.FindAsync([req.LobbyId], ct)
?? throw new GameException("LOBBY_NOT_FOUND");
if (lobby.HostAccountId != requesterId)
throw new GameException("NOT_LOBBY_HOST");
if (lobby.Status is not (CustomLobbyStatus.Open or CustomLobbyStatus.Full))
throw new GameException("LOBBY_NOT_MODIFIABLE");
var currentSlots = _lobbyService.GetSlots(lobby);
var slot = currentSlots.FirstOrDefault(s => s.AccountId == req.AiAccountId);
if (slot is null)
throw new GameException("AI_SLOT_NOT_FOUND");
// Remove from GuestAccountId or AdditionalPlayersJson.
if (lobby.GuestAccountId == req.AiAccountId)
{
lobby.GuestAccountId = null;
lobby.GuestDeckId = null;
lobby.Status = CustomLobbyStatus.Open;
}
else
{
var addl = GameAddAiHandler.DeserializeAdditional(lobby.AdditionalPlayersJson);
addl.RemoveAll(p => p.AccountId == req.AiAccountId);
lobby.AdditionalPlayersJson = addl.Count > 0
? JsonSerializer.Serialize(addl)
: null;
// Recalculate status.
int remaining = 1 + (lobby.GuestAccountId.HasValue ? 1 : 0) + addl.Count;
lobby.Status = remaining < lobby.MaxPlayers
? CustomLobbyStatus.Open
: CustomLobbyStatus.Full;
}
currentSlots.Remove(slot);
_lobbyService.SetSlots(lobby, currentSlots);
await _gameDb.SaveChangesAsync(ct);
// Push updated slot list to all remaining human members.
var addlAfter = GameAddAiHandler.DeserializeAdditional(lobby.AdditionalPlayersJson);
var slotDtos = GameAddAiHandler.ToSlotDtos(currentSlots);
var push = ServerMessage.Push("game.ai.slots_changed",
new CustomLobbyAiSlotsChangedPush(lobby.Id, slotDtos));
var tasks = new List<Task>
{
_clientPush.PushAsync(lobby.HostAccountId.ToString(), push, ct),
};
if (lobby.GuestAccountId.HasValue)
tasks.Add(_clientPush.PushAsync(lobby.GuestAccountId.Value.ToString(), push, ct));
foreach (var p in addlAfter)
tasks.Add(_clientPush.PushAsync(p.AccountId.ToString(), push, ct));
await Task.WhenAll(tasks);
return ServerMessage.Reply("game.ai.remove.ack", message.Seq,
new GameRemoveAiResponse(true));
}
}
+47
View File
@@ -0,0 +1,47 @@
namespace SOR.Ai.Lobby;
using System.Text.Json;
using SOR.Database.Entities.Game;
/// <summary>
/// Shared read/write helpers for CustomLobby.AiSlotsJson.
/// Scoped service — one instance per request scope.
/// </summary>
internal sealed class AiLobbyService
{
private static readonly JsonSerializerOptions _json =
new() { PropertyNameCaseInsensitive = true };
/// <summary>Deserializes the AI slot list from a lobby. Never returns null.</summary>
public List<AiLobbySlot> GetSlots(CustomLobby lobby)
{
if (string.IsNullOrEmpty(lobby.AiSlotsJson))
return [];
try
{
return JsonSerializer.Deserialize<List<AiLobbySlot>>(lobby.AiSlotsJson, _json) ?? [];
}
catch
{
return [];
}
}
/// <summary>Serializes and writes the slot list back to the lobby entity.</summary>
public void SetSlots(CustomLobby lobby, List<AiLobbySlot> slots)
{
lobby.AiSlotsJson = slots.Count > 0
? JsonSerializer.Serialize(slots)
: null;
}
}
/// <summary>One AI slot entry stored in CustomLobby.AiSlotsJson.</summary>
internal sealed class AiLobbySlot
{
public Guid AccountId { get; set; }
public string Strategy { get; set; } = string.Empty;
public int Difficulty { get; set; }
public int SeatIndex { get; set; }
}
+40
View File
@@ -0,0 +1,40 @@
namespace SOR.Ai.Lobby;
using Microsoft.EntityFrameworkCore;
using SOR.Ai.Seeding;
using SOR.Database.Contexts;
using SOR.Database.Entities.Identity;
/// <summary>
/// Resolves a (difficulty, strategy) request to the matching pre-seeded AI account.
/// Scoped service — one instance per request scope.
/// </summary>
internal sealed class AiSlotAssigner
{
private readonly SorIdentityDbContext _identityDb;
public AiSlotAssigner(SorIdentityDbContext identityDb)
{
_identityDb = identityDb;
}
/// <summary>
/// Returns the AI account for the given difficulty + strategy.
/// Throws if not found (seed should have created it at startup).
/// </summary>
public async Task<Account> GetAiAccountAsync(
int difficulty,
string strategy,
CancellationToken ct)
{
// Use the deterministic ID to avoid a name-based query.
var id = AiAccountSeeder.AccountId(difficulty, strategy);
return await _identityDb.Users
.AsNoTracking()
.FirstOrDefaultAsync(u => u.Id == id, ct)
?? throw new InvalidOperationException(
$"AI account not found for difficulty={difficulty} strategy={strategy}. " +
"Ensure AiSeedStartupService ran before traffic was accepted.");
}
}
+18
View File
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<!-- Required to use ASP.NET Core types (IHostedService, BackgroundService, etc.)
in a non-Web SDK project. Same pattern as all other SOR class library projects. -->
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SOR.Database\SOR.Database.csproj" />
<ProjectReference Include="..\SOR.Game\SOR.Game.csproj" />
<ProjectReference Include="..\SOR.Networking.Abstractions\SOR.Networking.Abstractions.csproj" />
<ProjectReference Include="..\SOR.Shared\SOR.Shared.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,134 @@
namespace SOR.Ai.Seeding;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using SOR.Database.Contexts;
using SOR.Database.Entities.Identity;
/// <summary>
/// Ensures all canonical AI accounts exist in the identity database.
/// Runs once at startup via AiSeedStartupService before traffic is accepted.
/// Uses deterministic GUIDs so re-running is fully idempotent (upsert by ID).
///
/// Creates 50 accounts: 10 difficulty tiers × 5 strategy archetypes.
/// Each account has IsAi=true, IsHiddenFromLeaderboard=true, RankScore=0.
/// </summary>
internal static class AiAccountSeeder
{
internal static readonly string[] Strategies = ["Aggressive", "Control", "Balanced", "Ramp", "Swarm"];
private static readonly string[] DifficultyNames =
[
"", // 0 — unused
"Novice", // 1
"Apprentice", // 2
"Journeyman", // 3
"Adept", // 4
"Expert", // 5
"Master", // 6
"Grandmaster",// 7
"Champion", // 8
"Legend", // 9
"Mythic", // 10
];
/// <summary>
/// Returns the deterministic GUID used for a given (difficulty, strategy) combination.
/// Deterministic = same inputs always produce the same GUID, so seeds are idempotent.
/// </summary>
public static Guid AccountId(int difficulty, string strategy) =>
new(GuidV5(
$"sor-ai-account:{difficulty}:{strategy.ToLowerInvariant()}"));
/// <summary>
/// Returns the display name shown in lobbies and game screens for this AI slot.
/// Format: "{Strategy} AI ({DifficultyName})" e.g. "Balanced AI (Adept)"
/// </summary>
public static string DisplayName(int difficulty, string strategy) =>
$"{strategy} AI ({DifficultyNames[difficulty]})";
public static async Task SeedAsync(
SorIdentityDbContext identityDb,
ILogger logger,
CancellationToken ct)
{
var expectedIds = new HashSet<Guid>();
var toUpsert = new List<Account>();
for (int d = 1; d <= 10; d++)
{
foreach (var strategy in Strategies)
{
var id = AccountId(d, strategy);
expectedIds.Add(id);
toUpsert.Add(new Account
{
Id = id,
UserName = $"ai-{DifficultyNames[d].ToLowerInvariant()}-{strategy.ToLowerInvariant()}",
NormalizedUserName = $"AI-{DifficultyNames[d].ToUpperInvariant()}-{strategy.ToUpperInvariant()}",
Email = $"ai-{d}-{strategy.ToLowerInvariant()}@internal.sor",
NormalizedEmail = $"AI-{d}-{strategy.ToUpperInvariant()}@INTERNAL.SOR",
EmailConfirmed = true,
PasswordHash = string.Empty,
SecurityStamp = Guid.NewGuid().ToString(),
DisplayName = DisplayName(d, strategy),
IsAi = true,
AiDifficulty = d,
AiStrategy = strategy,
IsHiddenFromLeaderboard = true,
RankScore = 0,
OriginPoints = 0,
CreatedAt = DateTimeOffset.UtcNow,
});
}
}
// Load existing AI accounts to detect what's missing.
var existingList = await identityDb.Users
.Where(u => expectedIds.Contains(u.Id))
.Select(u => u.Id)
.ToListAsync(ct);
var existing = existingList.ToHashSet();
int added = 0;
foreach (var account in toUpsert)
{
if (existing.Contains(account.Id))
continue;
identityDb.Users.Add(account);
added++;
}
if (added > 0)
{
await identityDb.SaveChangesAsync(ct);
logger.LogInformation("SOR.Ai: seeded {Count} AI accounts.", added);
}
else
{
logger.LogDebug("SOR.Ai: all {Total} AI accounts already exist.", expectedIds.Count);
}
}
// ── Helpers ───────────────────────────────────────────────────────────────
/// <summary>
/// Deterministic UUID v5 (SHA-1 namespace) from a string seed.
/// Produces the same 16-byte GUID every time for the same input.
/// </summary>
private static byte[] GuidV5(string seed)
{
// Use a fixed namespace so these GUIDs can never collide with random GUIDs.
var ns = new byte[] { 0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1,
0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8 };
var name = System.Text.Encoding.UTF8.GetBytes(seed);
var hash = System.Security.Cryptography.SHA1.HashData([..ns, ..name]);
// Force version 5 and variant bits per RFC 4122.
hash[6] = (byte)((hash[6] & 0x0F) | 0x50);
hash[8] = (byte)((hash[8] & 0x3F) | 0x80);
return hash[..16];
}
}
@@ -0,0 +1,70 @@
namespace SOR.Ai.Seeding;
/// <summary>
/// Describes one AI deck in terms of card names rather than IDs.
/// AiDeckSeeder resolves names to CardDefinitionIds at runtime.
/// One blueprint per strategy archetype. All AI accounts of a given strategy
/// share the same deck blueprint regardless of difficulty.
/// </summary>
internal sealed record AiDeckBlueprint(
string Strategy,
/// <summary>Display name of the ArchSpirit card in CardDefinitions.Name.</summary>
string ArchSpiritName,
/// <summary>Display name of the deck shown in the lobby.</summary>
string DeckName,
/// <summary>Card names with quantities. Keys = CardDefinition.Name, values = quantity.</summary>
IReadOnlyDictionary<string, int> Cards);
/// <summary>
/// Static table of deck blueprints — one per strategy archetype.
/// Card names must match CardDefinition.Name exactly (case-sensitive).
///
/// NOTE: If a card name does not exist in the catalog at seed time, AiDeckSeeder
/// will log a warning and skip that card rather than failing. This allows the server
/// to start even in environments where only a subset of cards are in the catalog.
/// </summary>
internal static class AiDeckDefinitions
{
/// <summary>
/// Returns all deck blueprints, one per strategy.
/// The consuming code matches strategies to AI accounts via AiAccountSeeder.Strategies.
/// </summary>
public static IReadOnlyList<AiDeckBlueprint> All { get; } =
[
// Balanced — generic mix of attack + defense.
// Replace card names with real catalog entries when available.
new AiDeckBlueprint(
Strategy : "Balanced",
ArchSpiritName: "Ignis Pup", // placeholder — update to real ArchSpirit name
DeckName : "Balanced Starter",
Cards : new Dictionary<string, int>()),
// Aggressive — rush strategy, cheap Spirits, prioritize ArchSpirit pressure.
new AiDeckBlueprint(
Strategy : "Aggressive",
ArchSpiritName: "Ignis Pup", // placeholder
DeckName : "Aggro Rush",
Cards : new Dictionary<string, int>()),
// Control — defensive, Terramorpha tile control, attrition.
new AiDeckBlueprint(
Strategy : "Control",
ArchSpiritName: "Ignis Pup", // placeholder
DeckName : "Control Fortress",
Cards : new Dictionary<string, int>()),
// Ramp — Sacrifice-heavy, builds ST then plays expensive threats.
new AiDeckBlueprint(
Strategy : "Ramp",
ArchSpiritName: "Ignis Pup", // placeholder
DeckName : "Sacrifice Engine",
Cards : new Dictionary<string, int>()),
// Swarm — flood the board with cheap low-cost Spirits.
new AiDeckBlueprint(
Strategy : "Swarm",
ArchSpiritName: "Ignis Pup", // placeholder
DeckName : "Spirit Horde",
Cards : new Dictionary<string, int>()),
];
}
+118
View File
@@ -0,0 +1,118 @@
namespace SOR.Ai.Seeding;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using SOR.Database.Contexts;
using SOR.Database.Entities.Collection;
/// <summary>
/// Seeds one Deck row per AI account based on the strategy-archetype blueprints
/// in AiDeckDefinitions. Called from AiSeedStartupService after AI accounts exist.
///
/// Graceful partial-seed: if a card name in the blueprint does not exist in the
/// catalog, it is skipped with a warning rather than throwing. The deck is still
/// created with IsValid=true so the AI can join games even with an incomplete deck.
/// Card definitions should be filled in once the full catalog is available.
/// </summary>
internal static class AiDeckSeeder
{
public static async Task SeedAsync(
SorIdentityDbContext identityDb,
CollectionDbContext collectionDb,
CatalogDbContext catalogDb,
ILogger logger,
CancellationToken ct)
{
// Build a lookup of blueprint by strategy.
var blueprints = AiDeckDefinitions.All.ToDictionary(b => b.Strategy);
// Load all card definitions by name for lookup.
var catalogCardNames = blueprints.Values
.SelectMany(b => b.Cards.Keys)
.Append(blueprints.Values.Select(b => b.ArchSpiritName).First())
.Concat(blueprints.Values.Select(b => b.ArchSpiritName))
.Distinct()
.ToList();
var catalogCards = catalogCardNames.Count > 0
? await catalogDb.Set<SOR.Database.Entities.Catalog.CardDefinition>()
.AsNoTracking()
.Where(c => catalogCardNames.Contains(c.Name))
.ToDictionaryAsync(c => c.Name, ct)
: new Dictionary<string, SOR.Database.Entities.Catalog.CardDefinition>();
int seeded = 0;
for (int difficulty = 1; difficulty <= 10; difficulty++)
{
foreach (var strategy in AiAccountSeeder.Strategies)
{
if (!blueprints.TryGetValue(strategy, out var blueprint))
continue;
var accountId = AiAccountSeeder.AccountId(difficulty, strategy);
// Skip if this AI account already has a deck.
var existingDeck = await collectionDb.Decks
.AsNoTracking()
.AnyAsync(d => d.AccountId == accountId, ct);
if (existingDeck)
continue;
// Resolve ArchSpirit definition ID.
if (!catalogCards.TryGetValue(blueprint.ArchSpiritName, out var archDef))
{
logger.LogWarning(
"SOR.Ai deck seed: ArchSpirit '{Name}' not found in catalog — " +
"skipping deck for {Strategy} difficulty {Diff}.",
blueprint.ArchSpiritName, strategy, difficulty);
continue;
}
var deck = new Deck
{
AccountId = accountId,
Name = blueprint.DeckName,
Description = $"Pre-built AI deck ({strategy} strategy)",
ArchSpiritCardDefinitionId = archDef.Id,
IsValid = true, // AI decks bypass normal validation
CreatedAt = DateTimeOffset.UtcNow,
UpdatedAt = DateTimeOffset.UtcNow,
};
// Add deck cards from the blueprint.
foreach (var (cardName, qty) in blueprint.Cards)
{
if (!catalogCards.TryGetValue(cardName, out var cardDef))
{
logger.LogWarning(
"SOR.Ai deck seed: card '{Name}' not found in catalog — " +
"skipping for {Strategy} deck.",
cardName, strategy);
continue;
}
deck.Cards.Add(new DeckCard
{
CardDefinitionId = cardDef.Id,
Quantity = qty,
});
}
collectionDb.Decks.Add(deck);
seeded++;
}
}
if (seeded > 0)
{
await collectionDb.SaveChangesAsync(ct);
logger.LogInformation("SOR.Ai: seeded {Count} AI decks.", seeded);
}
else
{
logger.LogDebug("SOR.Ai: all AI decks already exist or ArchSpirit not in catalog.");
}
}
}
@@ -0,0 +1,54 @@
namespace SOR.Ai.Seeding;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SOR.Ai.Core;
using SOR.Database.Contexts;
/// <summary>
/// One-shot IHostedService that runs at startup before the server accepts traffic.
/// Seeds AI accounts and decks, then loads the AiAccountRegistry so other services
/// can check IsAi without hitting the database on every turn.
/// </summary>
internal sealed class AiSeedStartupService : IHostedService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly AiAccountRegistry _registry;
private readonly ILogger<AiSeedStartupService> _logger;
public AiSeedStartupService(
IServiceScopeFactory scopeFactory,
AiAccountRegistry registry,
ILogger<AiSeedStartupService> logger)
{
_scopeFactory = scopeFactory;
_registry = registry;
_logger = logger;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
await using var scope = _scopeFactory.CreateAsyncScope();
var sp = scope.ServiceProvider;
var identityDb = sp.GetRequiredService<SorIdentityDbContext>();
var collectionDb = sp.GetRequiredService<CollectionDbContext>();
var catalogDb = sp.GetRequiredService<CatalogDbContext>();
// 1. Seed AI accounts (idempotent).
await AiAccountSeeder.SeedAsync(identityDb, _logger, cancellationToken);
// 2. Seed AI decks (idempotent; skips gracefully if catalog cards missing).
await AiDeckSeeder.SeedAsync(identityDb, collectionDb, catalogDb, _logger, cancellationToken);
// 3. Populate in-memory registry for O(1) IsAi checks.
_registry.Load(identityDb);
_logger.LogInformation(
"SOR.Ai: startup seed complete. {Count} AI accounts registered.",
_registry.Count);
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
+51
View File
@@ -0,0 +1,51 @@
namespace SOR.Ai;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SOR.Ai.Core;
using SOR.Ai.Handlers;
using SOR.Ai.Lobby;
using SOR.Ai.Seeding;
using SOR.Networking.Abstractions.Messaging;
using SOR.Shared;
/// <summary>
/// Registers all AI service components into the DI container.
/// Called from SOR.Host/Program.cs when ENABLED_SERVICES includes "game"
/// (AI is always co-located with the game service — it depends on game handlers directly).
/// </summary>
public static class ServiceRegistration
{
public static IServiceCollection AddAiService(
this IServiceCollection services,
IConfiguration configuration)
{
// ── Startup seed (one-shot IHostedService) ────────────────────────────
// Ensures AI accounts and decks exist in the DB before traffic is accepted.
services.AddHostedService<AiSeedStartupService>();
// ── Account registry (singleton, loaded at seed time) ─────────────────
// In-memory set of AI account IDs for O(1) "is this account an AI?" checks.
// Used by GameEndTurnHandler to decide whether to publish AiTurnStartedEvent.
// Registered as both the concrete type AND the shared interface so SOR.Game
// handlers can inject IAiAccountRegistry without referencing SOR.Ai directly.
services.AddSingleton<AiAccountRegistry>();
services.AddSingleton<IAiAccountRegistry>(sp => sp.GetRequiredService<AiAccountRegistry>());
// ── Session manager (singleton hosted service) ────────────────────────
// Listens for game-start events and orchestrates AI turns.
services.AddSingleton<AiPlayerSessionManager>();
services.AddHostedService(sp => sp.GetRequiredService<AiPlayerSessionManager>());
// ── Lobby scoped services ─────────────────────────────────────────────
services.AddScoped<AiSlotAssigner>();
services.AddScoped<AiLobbyService>();
// ── Lobby message handlers ────────────────────────────────────────────
services.AddTransient<IMessageHandler, GameAddAiHandler>();
services.AddTransient<IMessageHandler, GameRemoveAiHandler>();
services.AddTransient<IMessageHandler, GameConfigureAiHandler>();
return services;
}
}
@@ -0,0 +1,26 @@
namespace SOR.Ai.Transport;
using SOR.Networking.Abstractions.Messaging;
/// <summary>
/// An IClientMessage constructed by the AI layer to call game handlers directly,
/// bypassing the WebSocket transport entirely.
///
/// The payload must be pre-serialized as UTF-8 JSON using
/// JsonSerializer.SerializeToUtf8Bytes(request), which is exactly what the Gateway
/// WebSocket transport produces — so handlers see no difference.
/// </summary>
internal sealed class AiClientMessage : IClientMessage
{
public string Type { get; }
public int Seq { get; }
public ReadOnlyMemory<byte> Payload { get; }
public AiClientMessage(string type, ReadOnlyMemory<byte> payload, int seq = 0)
{
Type = type;
Seq = seq;
Payload = payload;
}
}
@@ -0,0 +1,40 @@
namespace SOR.Ai.Transport;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Transport;
/// <summary>
/// A no-op IClientConnection used when constructing an AuthenticatedConnection
/// for an AI player. The AI never receives WebSocket frames and never sends replies
/// over a socket — all communication goes through the game handler's push pipeline
/// (Redis → real players). Any attempt to actually send bytes through this connection
/// is silently discarded.
/// </summary>
internal sealed class AiNoOpClientConnection : IClientConnection
{
private readonly string _aiAccountId;
public AiNoOpClientConnection(string aiAccountId)
{
_aiAccountId = aiAccountId;
ConnectionId = $"ai-{aiAccountId}";
}
public string ConnectionId { get; }
public string RemoteAddress => "127.0.0.1:0";
public bool IsConnected => true;
// AI never receives messages via this connection; the session manager drives turns.
public Task<IClientMessage?> ReceiveAsync(CancellationToken cancellationToken) =>
Task.FromCanceled<IClientMessage?>(cancellationToken);
// AI replies are discarded — the handler already pushes state to real players
// via IClientPush (Redis). Nothing is lost by swallowing this.
public ValueTask SendBytesAsync(ReadOnlyMemory<byte> bytes, CancellationToken cancellationToken) =>
ValueTask.CompletedTask;
public Task CloseAsync(string reason, CancellationToken cancellationToken) =>
Task.CompletedTask;
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
@@ -131,6 +131,22 @@ public sealed class CustomLobby
/// </summary> /// </summary>
public string? TeamAssignmentsJson { get; set; } public string? TeamAssignmentsJson { get; set; }
// ── AI seats ─────────────────────────────────────────────────────────────
/// <summary>
/// JSON array of AI-controlled slots in this lobby, managed by the host via
/// game.ai.add / game.ai.remove / game.ai.configure messages.
///
/// Each element: { "accountId": "...", "seatIndex": N, "difficulty": N, "strategy": "..." }
///
/// These entries participate in the normal AdditionalPlayersJson / GuestAccountId
/// slot assignment — the AI accounts are real DB rows. This field is purely
/// for the SOR.Ai layer to know which seats it controls.
///
/// Null when no AI seats have been added.
/// </summary>
public string? AiSlotsJson { get; set; }
// ── Timestamps ─────────────────────────────────────────────────────────── // ── Timestamps ───────────────────────────────────────────────────────────
public DateTimeOffset CreatedAt { get; set; } public DateTimeOffset CreatedAt { get; set; }
@@ -50,4 +50,22 @@ public sealed class Account : IdentityUser<Guid>
/// Use for bots, dev accounts, and internal test accounts. /// Use for bots, dev accounts, and internal test accounts.
/// </summary> /// </summary>
public bool IsHiddenFromLeaderboard { get; set; } public bool IsHiddenFromLeaderboard { get; set; }
// ── AI account fields ─────────────────────────────────────────────────────
/// <summary>
/// True for AI-controlled virtual accounts (seeded by SOR.Ai at startup).
/// AI accounts are excluded from ranked matchmaking, leaderboards, and ELO updates.
/// They join custom lobbies as AI seats and submit game actions in-process.
/// </summary>
public bool IsAi { get; set; }
/// <summary>AI difficulty tier (1–10). Null for human accounts.</summary>
public int? AiDifficulty { get; set; }
/// <summary>
/// AI strategy archetype: "Aggressive" | "Control" | "Balanced" | "Ramp" | "Swarm".
/// Null for human accounts.
/// </summary>
public string? AiStrategy { get; set; }
} }
+31
View File
@@ -1,5 +1,36 @@
namespace SOR.Game; namespace SOR.Game;
// ── AI lobby requests / responses / pushes ────────────────────────────────────
/// <summary>Host adds an AI player to a custom lobby.</summary>
public sealed record GameAddAiRequest(Guid LobbyId, int Difficulty, string Strategy);
public sealed record GameAddAiResponse(Guid AiAccountId, string AiDisplayName, int SeatIndex);
/// <summary>Host removes an AI player from a custom lobby.</summary>
public sealed record GameRemoveAiRequest(Guid LobbyId, Guid AiAccountId);
public sealed record GameRemoveAiResponse(bool Success);
/// <summary>Host changes the difficulty or strategy of an existing AI slot.</summary>
public sealed record GameConfigureAiRequest(Guid LobbyId, Guid AiAccountId,
int? Difficulty, string? Strategy);
public sealed record GameConfigureAiResponse(bool Success);
/// <summary>
/// Pushed to all lobby members when the AI slot list changes
/// (AI added, removed, or configured).
/// </summary>
public sealed record CustomLobbyAiSlotsChangedPush(
Guid LobbyId,
IReadOnlyList<AiSlotInfo> CurrentAiSlots);
/// <summary>One AI seat in a custom lobby.</summary>
public sealed record AiSlotInfo(
Guid AccountId,
string DisplayName,
int Difficulty,
string Strategy,
int SeatIndex);
// ── Requests ───────────────────────────────────────────────────────────────── // ── Requests ─────────────────────────────────────────────────────────────────
/// <summary>Signal that the player has loaded the game screen and is ready to start.</summary> /// <summary>Signal that the player has loaded the game screen and is ready to start.</summary>
@@ -7,6 +7,8 @@ using SOR.Networking.Abstractions.EventBus;
using SOR.Networking.Abstractions.Messaging; using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Push; using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport; using SOR.Networking.Abstractions.Transport;
using SOR.Shared;
using SOR.Shared.Nats;
using SOR.Shared.Networking; using SOR.Shared.Networking;
/// <summary> /// <summary>
@@ -22,6 +24,8 @@ internal sealed class GameEndTurnHandler : GameHandlerBase, IMessageHandler
private readonly IClientPush _clientPush; private readonly IClientPush _clientPush;
private readonly IEventBus _eventBus; private readonly IEventBus _eventBus;
private readonly GameTurnTimerService _timerService; private readonly GameTurnTimerService _timerService;
// Optional: only present when SOR.Ai is loaded. Null when running without AI service.
private readonly IAiAccountRegistry? _aiRegistry;
public GameEndTurnHandler( public GameEndTurnHandler(
IMessageSerializer serializer, IMessageSerializer serializer,
@@ -29,7 +33,8 @@ internal sealed class GameEndTurnHandler : GameHandlerBase, IMessageHandler
SorIdentityDbContext identityDb, SorIdentityDbContext identityDb,
IClientPush clientPush, IClientPush clientPush,
IEventBus eventBus, IEventBus eventBus,
GameTurnTimerService timerService) GameTurnTimerService timerService,
IAiAccountRegistry? aiRegistry = null)
{ {
_serializer = serializer; _serializer = serializer;
_gameDb = gameDb; _gameDb = gameDb;
@@ -37,6 +42,7 @@ internal sealed class GameEndTurnHandler : GameHandlerBase, IMessageHandler
_clientPush = clientPush; _clientPush = clientPush;
_eventBus = eventBus; _eventBus = eventBus;
_timerService = timerService; _timerService = timerService;
_aiRegistry = aiRegistry;
} }
public string MessageType => "game.end_turn"; public string MessageType => "game.end_turn";
@@ -103,6 +109,17 @@ internal sealed class GameEndTurnHandler : GameHandlerBase, IMessageHandler
_timerService.ResetTimer(session.Id, newState.Rules.TurnTimerSeconds, _timerService.ResetTimer(session.Id, newState.Rules.TurnTimerSeconds,
newState.Rules.TimeLimitMinutes, session.CreatedAt); newState.Rules.TimeLimitMinutes, session.CreatedAt);
// If the newly active player is an AI seat, signal AiPlayerSessionManager to act.
if (_aiRegistry?.IsAi(newState.ActivePlayerAccountId) == true)
{
await _eventBus.PublishAsync(NatsSubjects.AiTurnStarted,
new AiTurnStartedEvent(
SessionId : session.Id,
AiAccountId : newState.ActivePlayerAccountId,
TurnNumber : newState.TurnNumber),
ct);
}
return ServerMessage.Reply("game.end_turn.ack", message.Seq, return ServerMessage.Reply("game.end_turn.ack", message.Seq,
new GameEndTurnResponse(stateDto)); new GameEndTurnResponse(stateDto));
} }
@@ -7,9 +7,12 @@ using SOR.Game.Grid;
using SOR.Database.Entities.Catalog; using SOR.Database.Entities.Catalog;
using SOR.Database.Entities.Collection; using SOR.Database.Entities.Collection;
using SOR.Database.Enums; using SOR.Database.Enums;
using SOR.Networking.Abstractions.EventBus;
using SOR.Networking.Abstractions.Messaging; using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Push; using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport; using SOR.Networking.Abstractions.Transport;
using SOR.Shared;
using SOR.Shared.Nats;
using SOR.Shared.Networking; using SOR.Shared.Networking;
/// <summary> /// <summary>
@@ -26,6 +29,9 @@ internal sealed class GameReadyHandler : GameHandlerBase, IMessageHandler
private readonly CollectionDbContext _collectionDb; private readonly CollectionDbContext _collectionDb;
private readonly CatalogDbContext _catalogDb; private readonly CatalogDbContext _catalogDb;
private readonly IClientPush _clientPush; private readonly IClientPush _clientPush;
private readonly IEventBus _eventBus;
// Optional: only present when SOR.Ai is loaded.
private readonly IAiAccountRegistry? _aiRegistry;
public GameReadyHandler( public GameReadyHandler(
IMessageSerializer serializer, IMessageSerializer serializer,
@@ -33,7 +39,9 @@ internal sealed class GameReadyHandler : GameHandlerBase, IMessageHandler
SorIdentityDbContext identityDb, SorIdentityDbContext identityDb,
CollectionDbContext collectionDb, CollectionDbContext collectionDb,
CatalogDbContext catalogDb, CatalogDbContext catalogDb,
IClientPush clientPush) IClientPush clientPush,
IEventBus eventBus,
IAiAccountRegistry? aiRegistry = null)
{ {
_serializer = serializer; _serializer = serializer;
_gameDb = gameDb; _gameDb = gameDb;
@@ -41,6 +49,8 @@ internal sealed class GameReadyHandler : GameHandlerBase, IMessageHandler
_collectionDb = collectionDb; _collectionDb = collectionDb;
_catalogDb = catalogDb; _catalogDb = catalogDb;
_clientPush = clientPush; _clientPush = clientPush;
_eventBus = eventBus;
_aiRegistry = aiRegistry;
} }
public string MessageType => "game.ready"; public string MessageType => "game.ready";
@@ -227,6 +237,17 @@ internal sealed class GameReadyHandler : GameHandlerBase, IMessageHandler
// Push initial state to both players. // Push initial state to both players.
await PushStateToPlayersAsync(_clientPush, session, state, ct); await PushStateToPlayersAsync(_clientPush, session, state, ct);
// If the first active player (Placement phase) is an AI seat, signal it to act.
if (_aiRegistry?.IsAi(state.ActivePlayerAccountId) == true)
{
await _eventBus.PublishAsync(NatsSubjects.AiTurnStarted,
new AiTurnStartedEvent(
SessionId : session.Id,
AiAccountId : state.ActivePlayerAccountId,
TurnNumber : state.TurnNumber),
ct);
}
return ServerMessage.Reply("game.ready.ack", message.Seq, return ServerMessage.Reply("game.ready.ack", message.Seq,
new GameReadyResponse(session.Id, "Started")); new GameReadyResponse(session.Id, "Started"));
} }
+3
View File
@@ -17,6 +17,7 @@ using SOR.Bazaar;
using SOR.Chat; using SOR.Chat;
using SOR.Collection; using SOR.Collection;
using SOR.Content; using SOR.Content;
using SOR.Ai;
using SOR.Game; using SOR.Game;
using SOR.Gateway; using SOR.Gateway;
using SOR.Matchmaking; using SOR.Matchmaking;
@@ -178,6 +179,8 @@ if (IsEnabled("content")) builder.Services.AddContentService(builder.Configur
if (IsEnabled("versioning")) builder.Services.AddVersioningService(builder.Configuration); if (IsEnabled("versioning")) builder.Services.AddVersioningService(builder.Configuration);
if (IsEnabled("matchmaking")) builder.Services.AddMatchmakingService(builder.Configuration); if (IsEnabled("matchmaking")) builder.Services.AddMatchmakingService(builder.Configuration);
if (IsEnabled("game")) builder.Services.AddGameService(builder.Configuration); if (IsEnabled("game")) builder.Services.AddGameService(builder.Configuration);
// AI is always co-located with game: it invokes game handlers in-process.
if (IsEnabled("game")) builder.Services.AddAiService(builder.Configuration);
if (IsEnabled("support")) builder.Services.AddSupportService(builder.Configuration); if (IsEnabled("support")) builder.Services.AddSupportService(builder.Configuration);
// ── BUILD ───────────────────────────────────────────────────────────────────── // ── BUILD ─────────────────────────────────────────────────────────────────────
+1
View File
@@ -42,6 +42,7 @@
<ProjectReference Include="..\SOR.Content\SOR.Content.csproj" /> <ProjectReference Include="..\SOR.Content\SOR.Content.csproj" />
<ProjectReference Include="..\SOR.Versioning\SOR.Versioning.csproj" /> <ProjectReference Include="..\SOR.Versioning\SOR.Versioning.csproj" />
<ProjectReference Include="..\SOR.Matchmaking\SOR.Matchmaking.csproj" /> <ProjectReference Include="..\SOR.Matchmaking\SOR.Matchmaking.csproj" />
<ProjectReference Include="..\SOR.Ai\SOR.Ai.csproj" />
<ProjectReference Include="..\SOR.Game\SOR.Game.csproj" /> <ProjectReference Include="..\SOR.Game\SOR.Game.csproj" />
<ProjectReference Include="..\SOR.Support\SOR.Support.csproj" /> <ProjectReference Include="..\SOR.Support\SOR.Support.csproj" />
</ItemGroup> </ItemGroup>
@@ -0,0 +1,20 @@
namespace SOR.Shared;
/// <summary>
/// Provides O(1) lookup for whether an account ID belongs to an AI-controlled virtual player.
///
/// Defined in SOR.Shared so that SOR.Game can depend on it without creating a circular
/// reference to SOR.Ai (which itself references SOR.Game).
///
/// Implemented by SOR.Ai.Core.AiAccountRegistry and registered as a singleton in
/// SOR.Host when the AI service is enabled. Injected as optional (nullable) in game
/// handlers so the game service works correctly even without SOR.Ai running.
/// </summary>
public interface IAiAccountRegistry
{
/// <summary>Returns true if the string account ID belongs to an AI account.</summary>
bool IsAi(string accountId);
/// <summary>Returns true if the Guid account ID belongs to an AI account.</summary>
bool IsAi(Guid accountId);
}
+9
View File
@@ -11,3 +11,12 @@ public sealed record GameEndedEvent(
Guid LoserId, Guid LoserId,
int DurationSeconds, int DurationSeconds,
DateTimeOffset EndedAt); DateTimeOffset EndedAt);
/// <summary>
/// Published by GameEndTurnHandler when the turn advances to an AI-controlled seat.
/// Consumed by AiPlayerSessionManager to kick off the AI's turn.
/// </summary>
public sealed record AiTurnStartedEvent(
Guid SessionId,
string AiAccountId,
int TurnNumber);
@@ -58,6 +58,16 @@ public static class NatsSubjects
/// </summary> /// </summary>
public const string LeaderboardMatchRated = "sor.leaderboard.match.rated"; public const string LeaderboardMatchRated = "sor.leaderboard.match.rated";
// ── AI ────────────────────────────────────────────────────────────────────
/// <summary>
/// Published by Game service (GameEndTurnHandler) when the turn advances to an
/// AI-controlled seat. Consumed by SOR.Ai (AiPlayerSessionManager) to trigger
/// the AI's turn execution.
/// Payload: AiTurnStartedEvent { SessionId, AiAccountId, TurnNumber }
/// </summary>
public const string AiTurnStarted = "sor.ai.turn_started";
// ── Admin ───────────────────────────────────────────────────────────────── // ── Admin ─────────────────────────────────────────────────────────────────
/// <summary> /// <summary>