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>
This commit is contained in:
dingo
2026-04-12 18:35:23 -04:00
co-authored by Claude Happy
parent 57915ae6da
commit 27e1b7c8a3
27 changed files with 2242 additions and 19 deletions
@@ -163,6 +163,23 @@
</li>
</ul>
</li>
<li class="nav-item">
<NavLink class="nav-link text-white" href="/ai/elo" Match="NavLinkMatch.All">
<i class="bi bi-robot me-2"></i>AI
</NavLink>
<ul class="nav nav-pills flex-column gap-1 ps-3 mt-1">
<li class="nav-item">
<NavLink class="nav-link text-white-50 py-1" href="/ai/elo">
<i class="bi bi-trophy me-2"></i>ELO Leaderboard
</NavLink>
</li>
<li class="nav-item">
<NavLink class="nav-link text-white-50 py-1" href="/ai/calibration">
<i class="bi bi-sliders me-2"></i>Calibration
</NavLink>
</li>
</ul>
</li>
<li class="nav-item">
<NavLink class="nav-link text-white" href="/feature-flags">
<i class="bi bi-toggles me-2"></i>Feature Flags
@@ -0,0 +1,202 @@
@page "/ai/calibration"
@using Microsoft.EntityFrameworkCore
@using SOR.Ai.Calibration
@using SOR.Ai.Training
@using SOR.Database.Contexts
@inject AiCalibrationJob CalibrationJob
@inject GameDbContext Db
@inject ILogger<AiCalibrationPage> Logger
<PageTitle>AI Calibration – SOR Admin</PageTitle>
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="mb-0">AI Calibration</h1>
<div class="d-flex gap-2">
<button class="btn btn-outline-secondary btn-sm" @onclick="LoadAsync">
<i class="bi bi-arrow-clockwise me-1"></i>Refresh
</button>
</div>
</div>
@if (_error is not null)
{
<div class="alert alert-danger">@_error</div>
}
@if (_success is not null)
{
<div class="alert alert-success">@_success</div>
}
<!-- Run calibration -->
<div class="card mb-4">
<div class="card-header">Run Self-Play Calibration</div>
<div class="card-body">
<div class="row g-3 align-items-end">
<div class="col-md-3">
<label class="form-label">Difficulty A</label>
<input class="form-control" type="number" min="1" max="10" @bind="_diffA" />
</div>
<div class="col-md-3">
<label class="form-label">Difficulty B</label>
<input class="form-control" type="number" min="1" max="10" @bind="_diffB" />
</div>
<div class="col-md-2">
<label class="form-label">Games</label>
<input class="form-control" type="number" min="2" max="200" @bind="_games" />
</div>
<div class="col-md-2">
<label class="form-label">Notes</label>
<input class="form-control" type="text" @bind="_notes" placeholder="optional" />
</div>
<div class="col-md-2">
<button class="btn btn-primary w-100" @onclick="RunPairAsync" disabled="@_running">
@if (_running) { <span class="spinner-border spinner-border-sm me-1"></span> }
Run Pair
</button>
</div>
</div>
<div class="mt-2">
<button class="btn btn-warning btn-sm" @onclick="RunAllPairsAsync" disabled="@_running">
@if (_running) { <span class="spinner-border spinner-border-sm me-1"></span> }
Run All Adjacent Pairs (1v2 … 9v10)
</button>
</div>
</div>
</div>
<!-- Run training data export -->
<div class="card mb-4">
<div class="card-header">Export Training Data</div>
<div class="card-body">
<div class="row g-3 align-items-end">
<div class="col-md-4">
<label class="form-label">Output Path</label>
<input class="form-control" type="text" @bind="_exportPath" placeholder="/data/training.jsonl" />
</div>
<div class="col-md-2">
<label class="form-label">Max Sessions</label>
<input class="form-control" type="number" min="1" max="5000" @bind="_exportMax" />
</div>
<div class="col-md-2">
<button class="btn btn-secondary w-100" @onclick="RunExportAsync" disabled="@_running">
@if (_running) { <span class="spinner-border spinner-border-sm me-1"></span> }
Export
</button>
</div>
</div>
</div>
</div>
<!-- Calibration history -->
<div class="card">
<div class="card-header">Calibration History</div>
@if (_runs is null)
{
<div class="card-body"><span class="spinner-border spinner-border-sm"></span> Loading…</div>
}
else if (_runs.Count == 0)
{
<div class="card-body text-muted">No calibration runs yet.</div>
}
else
{
<div class="table-responsive">
<table class="table table-sm table-hover mb-0">
<thead>
<tr>
<th>Date</th>
<th>Difficulty A</th>
<th>Difficulty B</th>
<th>Win Rate A</th>
<th>Games</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
@foreach (var run in _runs)
{
<tr>
<td>@run.RunAt.ToString("yyyy-MM-dd HH:mm")</td>
<td>D@(run.DifficultyA)</td>
<td>D@(run.DifficultyB)</td>
<td>
<span class="@(run.WinRateA < 0.45f ? "text-success" : run.WinRateA > 0.55f ? "text-danger" : "text-warning")">
@(run.WinRateA.ToString("P1"))
</span>
</td>
<td>@run.GameCount</td>
<td class="text-muted small">@run.Notes</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
@code {
private List<SOR.Database.Entities.Game.AiCalibrationRun>? _runs;
private bool _running;
private string? _error;
private string? _success;
private int _diffA = 1;
private int _diffB = 2;
private int _games = 20;
private string? _notes;
private string _exportPath = "/data/training.jsonl";
private int _exportMax = 500;
[Inject] private SelfPlayOrchestrator Orchestrator { get; set; } = default!;
[Inject] private GameReplayExporter Exporter { get; set; } = default!;
protected override async Task OnInitializedAsync() => await LoadAsync();
private async Task LoadAsync()
{
_runs = await Db.AiCalibrationRuns
.OrderByDescending(r => r.RunAt)
.Take(100)
.ToListAsync();
StateHasChanged();
}
private async Task RunPairAsync()
{
_running = true; _error = null; _success = null; StateHasChanged();
try
{
int created = await CalibrationJob.RunPairAsync(_diffA, _diffB, "Balanced", _games, _notes);
_success = $"Calibration run saved ({created} record(s)).";
await LoadAsync();
}
catch (Exception ex) { _error = ex.Message; }
finally { _running = false; StateHasChanged(); }
}
private async Task RunAllPairsAsync()
{
_running = true; _error = null; _success = null; StateHasChanged();
try
{
int created = await CalibrationJob.RunAllPairsAsync("Balanced", _games, _notes);
_success = $"All pairs calibrated — {created} record(s) saved.";
await LoadAsync();
}
catch (Exception ex) { _error = ex.Message; }
finally { _running = false; StateHasChanged(); }
}
private async Task RunExportAsync()
{
_running = true; _error = null; _success = null; StateHasChanged();
try
{
int written = await Exporter.ExportAsync(_exportPath, _exportMax);
_success = $"Exported {written} training records to {_exportPath}.";
}
catch (Exception ex) { _error = ex.Message; }
finally { _running = false; StateHasChanged(); }
}
}
@@ -0,0 +1,86 @@
@page "/ai/elo"
@using Microsoft.EntityFrameworkCore
@using SOR.Database.Contexts
@inject GameDbContext Db
@inject SorIdentityDbContext IdentityDb
<PageTitle>AI ELO Leaderboard – SOR Admin</PageTitle>
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="mb-0">AI ELO Leaderboard</h1>
<button class="btn btn-outline-secondary btn-sm" @onclick="LoadAsync">
<i class="bi bi-arrow-clockwise me-1"></i>Refresh
</button>
</div>
@if (_rows is null)
{
<p><span class="spinner-border spinner-border-sm"></span> Loading…</p>
}
else if (_rows.Count == 0)
{
<p class="text-muted">No AI ELO records found. Run calibration games to populate.</p>
}
else
{
<div class="table-responsive">
<table class="table table-sm table-hover">
<thead>
<tr>
<th>#</th>
<th>Username</th>
<th>ELO</th>
<th>Wins</th>
<th>Losses</th>
<th>W/L</th>
<th>Updated</th>
</tr>
</thead>
<tbody>
@{ int rank = 1; }
@foreach (var row in _rows)
{
<tr>
<td>@(rank++)</td>
<td><code>@row.Username</code></td>
<td><strong>@row.Elo</strong></td>
<td class="text-success">@row.Wins</td>
<td class="text-danger">@row.Losses</td>
<td>@(row.Total == 0 ? "—" : $"{(float)row.Wins / row.Total:P0}")</td>
<td class="text-muted small">@row.UpdatedAt.ToString("yyyy-MM-dd HH:mm")</td>
</tr>
}
</tbody>
</table>
</div>
}
@code {
private record EloRow(string Username, int Elo, int Wins, int Losses, int Total, DateTimeOffset UpdatedAt);
private List<EloRow>? _rows;
protected override async Task OnInitializedAsync() => await LoadAsync();
private async Task LoadAsync()
{
var records = await Db.AiEloRecords
.OrderByDescending(r => r.EloScore)
.ToListAsync();
var accountIds = records.Select(r => r.AiAccountId).ToList();
var accounts = await IdentityDb.Users
.Where(a => accountIds.Contains(a.Id))
.ToDictionaryAsync(a => a.Id, a => a.UserName ?? a.Id.ToString());
_rows = records.Select(r => new EloRow(
Username : accounts.GetValueOrDefault(r.AiAccountId, r.AiAccountId.ToString()),
Elo : r.EloScore,
Wins : r.Wins,
Losses : r.Losses,
Total : r.Wins + r.Losses,
UpdatedAt : r.UpdatedAt)).ToList();
StateHasChanged();
}
}