Initial commit

This commit is contained in:
KoalaTrapLord committed 2026-03-10 12:13:56 -04:00
commit e6b5e0cedb
402 files changed
+64931

No files matched your search

@@ -0,0 +1,122 @@
package commanderailab.schema;
import java.util.List;
/**
* Complete data model for batch simulation results.
* Serialized to JSON conforming to batch-result-schema.json.
*/
public class BatchResult {
public Metadata metadata;
public List<DeckInfo> decks;
public List<GameResult> games;
public Summary summary;
// ── Metadata ───────────────────────────────────────────────
public static class Metadata {
public String schemaVersion = "1.0.0";
public String batchId;
public String timestamp; // ISO 8601
public int totalGames;
public int completedGames;
public String format = "commander";
public int podSize = 3;
public String engineVersion;
public Long masterSeed; // null if random
public int threads = 1;
public long elapsedMs;
}
// ── Deck Info ──────────────────────────────────────────────
public static class DeckInfo {
public int seatIndex;
public String deckName;
public String commanderName;
public String deckFile;
public List<String> colorIdentity;
public int cardCount;
// v3: Source/import metadata
public String source; // e.g., "edhrec", "archidekt", "local", "text"
public String sourceUrl; // URL to original deck (if imported)
public String archetype; // e.g., "aggro", "control", "combo"
public Integer sampleSize; // EDHREC: number of decks sampled
public String importedAt; // ISO 8601 timestamp of import
}
// ── Per-Game Result ────────────────────────────────────────
public static class GameResult {
public int gameIndex;
public Integer winningSeat; // null if draw/timeout
public int totalTurns;
public String winCondition; // enum from schema
public long gameSeed;
public long elapsedMs;
public List<PlayerResult> playerResults;
}
public static class PlayerResult {
public int seatIndex;
public int finalLife;
public int mulligans;
public boolean isWinner;
public int commanderDamageDealt;
public int commanderCasts;
public int landsPlayed;
public int spellsCast;
public int creaturesDestroyed;
// v4: Per-card detailed stats for coach analytics
public List<PerCardGameStats> cardStats;
}
// ── Summary ────────────────────────────────────────────────
public static class Summary {
public List<DeckSummary> perDeck;
public double avgGameTurns;
public double avgGameTimeMs;
public double simsPerSecond;
}
public static class DeckSummary {
public int seatIndex;
public String deckName;
public int wins;
public int losses;
public int draws;
public double winRate;
public Double avgTurnsToWin; // null if zero wins
public double avgMulligans;
public double avgFinalLife;
public WinConditionBreakdown winConditionBreakdown;
}
public static class WinConditionBreakdown {
public int combat_damage;
public int commander_damage;
public int combo_alt_win;
public int life_drain;
public int mill;
public int concession;
public int timeout;
public int unknown;
public void increment(String condition) {
switch (condition) {
case "combat_damage" -> combat_damage++;
case "commander_damage" -> commander_damage++;
case "combo_alt_win" -> combo_alt_win++;
case "life_drain" -> life_drain++;
case "mill" -> mill++;
case "concession" -> concession++;
case "timeout" -> timeout++;
default -> unknown++;
}
}
}
}
@@ -0,0 +1,74 @@
package commanderailab.schema;
import java.util.List;
/**
* DecisionSnapshot — State + action at a single decision point.
*
* Captures the full game state observable to the active player,
* plus the action taken. Used for supervised learning of a policy network.
*
* Serialized as JSON, one per decision point per game.
* Format: {"RL_DECISION": <json>} on a single log line so it can be
* parsed reliably from Forge subprocess output.
*
* State encoding (consumed by Python ml/encoder/):
* - Global: turn, phase, active_seat
* - Per-player: life, cmdr_damage, mana, cards_in_hand, etc.
* - Per-zone per-player: list of card names (IDs resolved Python-side)
*
* Action: the raw Forge action string, later labeled into a macro-action
* by ml/actions/labeler.py
*/
public class DecisionSnapshot {
// ── Game context ──────────────────────────────────────────
public String gameId;
public int turnNumber;
public String phase; // "main_1", "combat", "main_2", "end"
public int activeSeat; // 0-based seat index of acting player
// ── Per-player state (index = seat) ──────────────────────
public List<PlayerSnapshot> players;
// ── Action taken ─────────────────────────────────────────
public ActionRecord action;
// ══════════════════════════════════════════════════════════
// Player state at this decision point
// ══════════════════════════════════════════════════════════
public static class PlayerSnapshot {
public int seatIndex;
public int lifeTotal;
public int commanderDamageTaken; // from opponent's commander
public int manaAvailable; // untapped mana sources
public int commanderTax; // times commander has been cast × 2
public int commanderCasts;
// Zone contents — card names for embedding lookup
public List<String> hand;
public List<String> battlefield; // permanents controlled
public List<String> graveyard;
public List<String> commandZone; // commander if not on field
// Board summary stats (pre-computed for faster encoding)
public int creaturesOnField;
public int totalPowerOnBoard;
public int totalToughnessOnBoard;
public int artifactsOnField;
public int enchantmentsOnField;
public int landCount; // lands on battlefield
}
// ══════════════════════════════════════════════════════════
// Action record — what the AI chose to do
// ══════════════════════════════════════════════════════════
public static class ActionRecord {
public String type; // "cast", "attack", "activate", "pass", "land"
public String cardName; // card involved (null for pass/attack)
public String targetDescription; // human-readable target ("Ai(2)-Name", etc.)
public String rawLogLine; // original Forge log line for this action
}
}
@@ -0,0 +1,91 @@
package commanderailab.schema;
import java.util.*;
/**
* DeckReport — Complete deck performance profile.
*
* Aggregates simulation results into a comprehensive report that
* the Python coach service consumes to generate improvement suggestions.
*
* Serialized to JSON and written to deck-reports/{deckId}.json.
*/
public class DeckReport {
public String deckId;
public String commander;
public List<String> colorIdentity = new ArrayList<>();
public DeckMeta meta = new DeckMeta();
public List<MatchupRecord> matchups = new ArrayList<>();
public DeckStructure structure = new DeckStructure();
public List<CardPerformance> cards = new ArrayList<>();
public List<String> underperformers = new ArrayList<>();
public List<String> overperformers = new ArrayList<>();
public List<ComboRecord> knownCombos = new ArrayList<>();
public String lastUpdated; // ISO 8601
// ── Deck-Level Meta Stats ─────────────────────────────────
public static class DeckMeta {
public int gamesSimulated;
public double overallWinRate;
public double avgGameLength;
public Map<String, Double> perArchetypeWinRates = new LinkedHashMap<>();
}
// ── Matchup Record ────────────────────────────────────────
public static class MatchupRecord {
public String opponentDeck;
public String opponentCommander = "";
public int gamesPlayed;
public double winRate;
}
// ── Deck Structure ────────────────────────────────────────
public static class DeckStructure {
public int landCount;
public int[] curveBuckets = new int[8]; // CMC 0-7+
public Map<String, Integer> cardTypeCounts = new LinkedHashMap<>();
public Map<String, Integer> functionalCounts = new LinkedHashMap<>();
}
// ── Per-Card Performance ──────────────────────────────────
public static class CardPerformance {
public String name;
public double drawnRate;
public double castRate;
public double keptInOpeningHandRate;
public double deadCardRate;
public double impactScore; // (winRateWhenCast - overallWinRate) * castRate
public double synergyScore;
public double clunkinessScore; // deadCardRate * (1 - castRate)
public Double avgTurnCast; // null if never cast
public double avgDamageDealt;
public List<String> tags = new ArrayList<>();
// ── Intermediate accumulators (not serialized) ────────
// Used during aggregation, then converted to rates
public transient int gamesDrawn;
public transient int gamesCast;
public transient int gamesKeptInOpening;
public transient int gamesDeadCard;
public transient int gamesWhenCast;
public transient int winsWhenCast;
public transient double totalTurnCast;
public transient double totalDamage;
public transient int gamesSeen;
}
// ── Combo Record ──────────────────────────────────────────
public static class ComboRecord {
public List<String> cardNames = new ArrayList<>();
public double winRateWhenAssembled;
public double assemblyRate;
}
}
@@ -0,0 +1,74 @@
package commanderailab.schema;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
/**
* JsonExporter — Serializes BatchResult to JSON files.
*
* Output conforms to batch-result-schema.json.
*/
public class JsonExporter {
private static final Gson GSON = new GsonBuilder()
.setPrettyPrinting()
.serializeNulls()
.disableHtmlEscaping()
.create();
/**
* Serialize a BatchResult to a JSON string.
*/
public static String toJson(BatchResult result) {
return GSON.toJson(result);
}
/**
* Write a BatchResult to a JSON file.
*
* @param result The batch result to export
* @param filePath Output file path (e.g., "results/batch-20260306-001.json")
* @throws IOException if file cannot be written
*/
public static void writeToFile(BatchResult result, String filePath) throws IOException {
Path path = Paths.get(filePath);
// Ensure parent directories exist
if (path.getParent() != null) {
Files.createDirectories(path.getParent());
}
String json = toJson(result);
Files.writeString(path, json, StandardCharsets.UTF_8);
}
/**
* Read a BatchResult from a JSON file.
*/
public static BatchResult readFromFile(String filePath) throws IOException {
String json = Files.readString(Paths.get(filePath), StandardCharsets.UTF_8);
return GSON.fromJson(json, BatchResult.class);
}
/**
* Validate that a JSON string contains all required top-level keys.
* (Lightweight validation — full JSON Schema validation would need a library.)
*/
public static boolean validateBasicStructure(String json) {
try {
BatchResult result = GSON.fromJson(json, BatchResult.class);
return result.metadata != null
&& result.decks != null && result.decks.size() == 3
&& result.games != null
&& result.summary != null
&& result.metadata.schemaVersion.equals("1.0.0")
&& result.metadata.podSize == 3;
} catch (Exception e) {
return false;
}
}
}
@@ -0,0 +1,51 @@
package commanderailab.schema;
/**
* Per-card statistics for a single game.
* Tracks what happened to each card during one simulation game.
* Attached to PlayerResult as a list.
*/
public class PerCardGameStats {
public String cardName;
// ── Draw/Cast tracking ────────────────────────────────────
public boolean drawn;
public int turnDrawn = -1; // -1 if not drawn
public boolean inOpeningHand;
public boolean keptInOpeningHand; // false if mulliganed away
public boolean cast;
public int turnCast = -1; // -1 if not cast
// ── Board/hand state ──────────────────────────────────────
public boolean stuckInHand; // drawn but never cast/used
public boolean onBattlefieldAtEnd; // was on battlefield when game ended
// ── Combat/value tracking ─────────────────────────────────
public int damageDealt;
public int manaProduced;
public int tokensCreated;
// ── Constructors ──────────────────────────────────────────
public PerCardGameStats() {}
public PerCardGameStats(String cardName) {
this.cardName = cardName;
}
/**
* Mark card as a "dead card" — drawn but never cast and still in hand
* at end of game.
*/
public void computeStuckInHand() {
this.stuckInHand = drawn && !cast;
}
@Override
public String toString() {
return String.format("PerCardGameStats{%s drawn=%b cast=%b stuck=%b dmg=%d}",
cardName, drawn, cast, stuckInHand, damageDealt);
}
}