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,48 @@
package commanderailab.ai;
/**
* AiPolicy — Abstraction for AI decision-making in Commander.
*
* v1 uses Forge's built-in AI, but this interface allows swapping in
* custom heuristic or learned policies in v2+.
*
* The policy scores actions based on weighted features:
* - Card advantage
* - Tempo / mana efficiency
* - Threat scoring per opponent
* - Basic combat logic
*/
public interface AiPolicy {
/**
* Unique name of this policy (e.g., "forge-builtin", "utility-v1").
*/
String getName();
/**
* Weight for card-advantage heuristic (0.0–1.0).
*/
double getCardAdvantageWeight();
/**
* Weight for tempo/mana-efficiency heuristic (0.0–1.0).
*/
double getTempoWeight();
/**
* Weight for threat scoring per opponent (0.0–1.0).
*/
double getThreatScoringWeight();
/**
* Weight for combat-outcome evaluation (0.0–1.0).
*/
double getCombatWeight();
/**
* Whether this policy delegates to Forge's built-in AI.
* When true, the batch runner uses Forge's sim mode directly.
* When false, decisions are intercepted by BridgePlayerController.
*/
boolean usesForgeBuiltinAi();
}
@@ -0,0 +1,275 @@
package commanderailab.ai;
import java.util.*;
/**
* AiProfile — Configurable AI behavior profile for Commander simulations.
*
* Each profile defines a set of heuristic weights that influence how the
* Forge AI evaluates decisions. These map to Forge's internal AI tuning
* parameters where available, and to our own post-processing heuristics.
*
* v2 Design:
* - Profiles are serializable to/from JSON for storage and UI selection
* - Built-in presets: DEFAULT, AGGRO, CONTROL, COMBO, MIDRANGE
* - Custom profiles can override any weight
* - Weights are normalized 0.0 – 1.0 (0 = ignore, 1 = maximum priority)
*/
public class AiProfile {
// ── Identity ───────────────────────────────────────────
private String name;
private String description;
// ── Combat Weights ─────────────────────────────────────
/** How eagerly the AI attacks (0 = conservative, 1 = all-out aggro) */
private double aggression = 0.5;
/** How much the AI values trading creatures in combat */
private double combatWillingness = 0.5;
/** Priority on dealing commander damage vs regular damage */
private double commanderDamagePriority = 0.3;
// ── Resource Weights ───────────────────────────────────
/** How much the AI values mana efficiency (curving out, using all mana) */
private double manaEfficiency = 0.5;
/** How much the AI values card advantage (drawing, cantrips) */
private double cardAdvantage = 0.5;
/** How much the AI prioritizes ramping / mana acceleration */
private double rampPriority = 0.4;
// ── Threat Assessment ──────────────────────────────────
/** How much the AI focuses on the leading player */
private double threatFocus = 0.5;
/** How much the AI values removal / interaction spells */
private double removalPriority = 0.5;
/** How likely the AI is to use removal on the biggest threat vs spreading */
private double targetConcentration = 0.5;
// ── Strategic Weights ──────────────────────────────────
/** How much the AI values board presence (creatures on battlefield) */
private double boardPresence = 0.5;
/** How much the AI holds back resources for future turns */
private double patience = 0.5;
/** How much the AI values combo pieces and assembling combos */
private double comboPriority = 0.3;
/** Mulligan aggressiveness (higher = more willing to mulligan weak hands) */
private double mulliganStrictness = 0.5;
// ── Forge Sim Flags ────────────────────────────────────
/** Clock override in seconds (0 = use default) */
private int clockOverride = 0;
// ══════════════════════════════════════════════════════════
// Constructors
// ══════════════════════════════════════════════════════════
public AiProfile() {
this.name = "custom";
this.description = "Custom AI profile";
}
public AiProfile(String name, String description) {
this.name = name;
this.description = description;
}
// ══════════════════════════════════════════════════════════
// Built-in Presets
// ══════════════════════════════════════════════════════════
/** Default balanced profile — Forge's built-in AI behavior. */
public static AiProfile defaultProfile() {
AiProfile p = new AiProfile("default", "Balanced — Forge's default AI behavior");
// All weights at 0.5 (balanced)
return p;
}
/** Aggro profile — attacks early and often, prioritizes damage output. */
public static AiProfile aggro() {
AiProfile p = new AiProfile("aggro", "Aggressive — attacks early, prioritizes damage");
p.aggression = 0.9;
p.combatWillingness = 0.8;
p.commanderDamagePriority = 0.6;
p.manaEfficiency = 0.7;
p.cardAdvantage = 0.3;
p.rampPriority = 0.2;
p.threatFocus = 0.3;
p.removalPriority = 0.3;
p.targetConcentration = 0.7;
p.boardPresence = 0.8;
p.patience = 0.1;
p.comboPriority = 0.1;
p.mulliganStrictness = 0.6;
return p;
}
/** Control profile — plays defensively, prioritizes removal and card draw. */
public static AiProfile control() {
AiProfile p = new AiProfile("control", "Control — defensive, removal-heavy, card advantage");
p.aggression = 0.2;
p.combatWillingness = 0.3;
p.commanderDamagePriority = 0.2;
p.manaEfficiency = 0.6;
p.cardAdvantage = 0.9;
p.rampPriority = 0.6;
p.threatFocus = 0.8;
p.removalPriority = 0.9;
p.targetConcentration = 0.8;
p.boardPresence = 0.3;
p.patience = 0.9;
p.comboPriority = 0.4;
p.mulliganStrictness = 0.7;
return p;
}
/** Combo profile — assembles win conditions, protects key pieces. */
public static AiProfile combo() {
AiProfile p = new AiProfile("combo", "Combo — ramps, digs for pieces, assembles combos");
p.aggression = 0.2;
p.combatWillingness = 0.2;
p.commanderDamagePriority = 0.1;
p.manaEfficiency = 0.8;
p.cardAdvantage = 0.8;
p.rampPriority = 0.9;
p.threatFocus = 0.4;
p.removalPriority = 0.4;
p.targetConcentration = 0.5;
p.boardPresence = 0.3;
p.patience = 0.7;
p.comboPriority = 0.95;
p.mulliganStrictness = 0.8;
return p;
}
/** Midrange profile — flexible, adapts between aggro and control. */
public static AiProfile midrange() {
AiProfile p = new AiProfile("midrange", "Midrange — flexible, strong board presence, value-oriented");
p.aggression = 0.5;
p.combatWillingness = 0.6;
p.commanderDamagePriority = 0.4;
p.manaEfficiency = 0.6;
p.cardAdvantage = 0.6;
p.rampPriority = 0.5;
p.threatFocus = 0.6;
p.removalPriority = 0.6;
p.targetConcentration = 0.5;
p.boardPresence = 0.7;
p.patience = 0.5;
p.comboPriority = 0.3;
p.mulliganStrictness = 0.5;
return p;
}
/** Get a preset by name. */
public static AiProfile byName(String name) {
return switch (name.toLowerCase()) {
case "aggro" -> aggro();
case "control" -> control();
case "combo" -> combo();
case "midrange" -> midrange();
default -> defaultProfile();
};
}
/** List all preset names. */
public static List<String> presetNames() {
return List.of("default", "aggro", "control", "combo", "midrange");
}
/** Get all presets as a map. */
public static Map<String, AiProfile> allPresets() {
Map<String, AiProfile> presets = new LinkedHashMap<>();
presets.put("default", defaultProfile());
presets.put("aggro", aggro());
presets.put("control", control());
presets.put("combo", combo());
presets.put("midrange", midrange());
return presets;
}
// ══════════════════════════════════════════════════════════
// Utility Methods
// ══════════════════════════════════════════════════════════
/**
* Compute an overall "style score" for display purposes.
* Returns a map of style dimensions to 0-100 integer scores.
*/
public Map<String, Integer> getStyleRadar() {
Map<String, Integer> radar = new LinkedHashMap<>();
radar.put("Aggression", toPercent(aggression));
radar.put("Card Advantage", toPercent(cardAdvantage));
radar.put("Removal", toPercent(removalPriority));
radar.put("Board Presence", toPercent(boardPresence));
radar.put("Combo", toPercent(comboPriority));
radar.put("Patience", toPercent(patience));
return radar;
}
private int toPercent(double val) {
return (int) Math.round(val * 100);
}
/**
* Create a summary string for CLI / log output.
*/
public String toSummaryString() {
return String.format(
"AiProfile[%s] — aggro=%.1f card=%.1f removal=%.1f board=%.1f combo=%.1f patience=%.1f",
name, aggression, cardAdvantage, removalPriority, boardPresence, comboPriority, patience
);
}
// ══════════════════════════════════════════════════════════
// Getters / Setters
// ══════════════════════════════════════════════════════════
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String desc) { this.description = desc; }
public double getAggression() { return aggression; }
public void setAggression(double v) { this.aggression = clamp(v); }
public double getCombatWillingness() { return combatWillingness; }
public void setCombatWillingness(double v) { this.combatWillingness = clamp(v); }
public double getCommanderDamagePriority() { return commanderDamagePriority; }
public void setCommanderDamagePriority(double v) { this.commanderDamagePriority = clamp(v); }
public double getManaEfficiency() { return manaEfficiency; }
public void setManaEfficiency(double v) { this.manaEfficiency = clamp(v); }
public double getCardAdvantage() { return cardAdvantage; }
public void setCardAdvantage(double v) { this.cardAdvantage = clamp(v); }
public double getRampPriority() { return rampPriority; }
public void setRampPriority(double v) { this.rampPriority = clamp(v); }
public double getThreatFocus() { return threatFocus; }
public void setThreatFocus(double v) { this.threatFocus = clamp(v); }
public double getRemovalPriority() { return removalPriority; }
public void setRemovalPriority(double v) { this.removalPriority = clamp(v); }
public double getTargetConcentration() { return targetConcentration; }
public void setTargetConcentration(double v) { this.targetConcentration = clamp(v); }
public double getBoardPresence() { return boardPresence; }
public void setBoardPresence(double v) { this.boardPresence = clamp(v); }
public double getPatience() { return patience; }
public void setPatience(double v) { this.patience = clamp(v); }
public double getComboPriority() { return comboPriority; }
public void setComboPriority(double v) { this.comboPriority = clamp(v); }
public double getMulliganStrictness() { return mulliganStrictness; }
public void setMulliganStrictness(double v) { this.mulliganStrictness = clamp(v); }
public int getClockOverride() { return clockOverride; }
public void setClockOverride(int v) { this.clockOverride = v; }
private double clamp(double v) { return Math.max(0.0, Math.min(1.0, v)); }
}
@@ -0,0 +1,71 @@
package commanderailab.ai;
/**
* ForgeBuiltinPolicy — v1 default policy that delegates all decisions
* to Forge's built-in utility-based AI.
*
* This is the simplest and most correct starting point because Forge's AI
* already handles:
* - Mana payment and land sequencing
* - Spell casting priority
* - Attacker/blocker declaration
* - Target selection
* - Mulligan decisions
*
* The weight fields here are placeholders for future custom policies.
*/
public class ForgeBuiltinPolicy implements AiPolicy {
private final double cardAdvantageWeight;
private final double tempoWeight;
private final double threatScoringWeight;
private final double combatWeight;
public ForgeBuiltinPolicy() {
// Default balanced weights (used as metadata; Forge AI makes actual decisions)
this(0.25, 0.30, 0.25, 0.20);
}
public ForgeBuiltinPolicy(double cardAdv, double tempo, double threat, double combat) {
this.cardAdvantageWeight = cardAdv;
this.tempoWeight = tempo;
this.threatScoringWeight = threat;
this.combatWeight = combat;
}
@Override
public String getName() {
return "forge-builtin";
}
@Override
public double getCardAdvantageWeight() {
return cardAdvantageWeight;
}
@Override
public double getTempoWeight() {
return tempoWeight;
}
@Override
public double getThreatScoringWeight() {
return threatScoringWeight;
}
@Override
public double getCombatWeight() {
return combatWeight;
}
@Override
public boolean usesForgeBuiltinAi() {
return true;
}
@Override
public String toString() {
return String.format("ForgeBuiltinPolicy[cardAdv=%.2f, tempo=%.2f, threat=%.2f, combat=%.2f]",
cardAdvantageWeight, tempoWeight, threatScoringWeight, combatWeight);
}
}
@@ -0,0 +1,518 @@
package commanderailab.analytics;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.regex.*;
import java.util.stream.*;
/**
* DeckAnalyzer — Static analysis of Commander .dck files.
*
* Parses Forge deck files and computes:
* - Mana curve (CMC distribution)
* - Color identity breakdown
* - Card category counts (lands, creatures, instants, sorceries, etc.)
* - Functional role tagging (ramp, removal, draw, board wipes, tutors)
* - Deck health checklist (recommended counts vs actual)
*
* Works with Forge .dck format:
* [metadata]
* Name=Deck Name
* [Commander]
* 1 Card Name|SET
* [Main]
* 1 Card Name|SET
* ...
*
* Note: Without Scryfall API calls, category tagging uses heuristic
* keyword matching on card names. A future version can enrich with
* Scryfall data for accurate type/oracle text analysis.
*/
public class DeckAnalyzer {
// ── Analysis Result ────────────────────────────────────
public static class DeckAnalysis {
public String deckName;
public String deckFile;
public String commanderName;
public int totalCards;
// Category counts
public int lands;
public int creatures;
public int instants;
public int sorceries;
public int artifacts;
public int enchantments;
public int planeswalkers;
public int other;
// Functional roles (heuristic)
public int rampCards;
public int removalCards;
public int drawCards;
public int boardWipes;
public int tutors;
public int counterSpells;
public int protectionCards;
public int recursionCards;
// Mana curve (index = CMC, value = count; index 7+ = "7+")
public int[] manaCurve = new int[8]; // 0,1,2,3,4,5,6,7+
// Color breakdown (count of cards with each color in cost)
public Map<String, Integer> colorBreakdown = new LinkedHashMap<>();
// Raw card list
public List<CardEntry> cards = new ArrayList<>();
// Health checklist
public Map<String, HealthCheck> healthChecks = new LinkedHashMap<>();
public static class HealthCheck {
public String category;
public int actual;
public int recommendedMin;
public int recommendedMax;
public String status; // "good", "low", "high"
public HealthCheck(String cat, int actual, int min, int max) {
this.category = cat;
this.actual = actual;
this.recommendedMin = min;
this.recommendedMax = max;
if (actual < min) this.status = "low";
else if (actual > max) this.status = "high";
else this.status = "good";
}
}
}
public static class CardEntry {
public int quantity;
public String name;
public String set;
public String section; // "Commander", "Main", "Sideboard"
public List<String> tags = new ArrayList<>(); // heuristic role tags
public CardEntry(int qty, String name, String set, String section) {
this.quantity = qty;
this.name = name;
this.set = set;
this.section = section;
}
}
// ── Parsing ────────────────────────────────────────────
/**
* Analyze a .dck file from disk.
*/
public static DeckAnalysis analyze(String deckFilePath) throws IOException {
List<String> lines = Files.readAllLines(Path.of(deckFilePath));
String fileName = Path.of(deckFilePath).getFileName().toString();
return analyze(lines, fileName);
}
/**
* Analyze a deck from its lines and filename.
*/
public static DeckAnalysis analyze(List<String> lines, String fileName) {
DeckAnalysis a = new DeckAnalysis();
a.deckFile = fileName;
a.deckName = fileName.replace(".dck", "");
a.colorBreakdown.put("W", 0);
a.colorBreakdown.put("U", 0);
a.colorBreakdown.put("B", 0);
a.colorBreakdown.put("R", 0);
a.colorBreakdown.put("G", 0);
a.colorBreakdown.put("C", 0); // Colorless
String currentSection = "Main";
Pattern cardPattern = Pattern.compile("^(\\d+)\\s+(.+?)(?:\\|(.+))?$");
for (String line : lines) {
line = line.trim();
if (line.isEmpty() || line.startsWith("//")) continue;
// Section headers
if (line.startsWith("[") && line.endsWith("]")) {
String section = line.substring(1, line.length() - 1);
if (section.equalsIgnoreCase("Commander")) {
currentSection = "Commander";
} else if (section.equalsIgnoreCase("Main")) {
currentSection = "Main";
} else if (section.equalsIgnoreCase("Sideboard")) {
currentSection = "Sideboard";
}
continue;
}
// Metadata: Name=...
if (line.startsWith("Name=")) {
a.deckName = line.substring(5).trim();
continue;
}
// Card entry: "1 Card Name|SET" or "1 Card Name"
Matcher m = cardPattern.matcher(line);
if (m.matches()) {
int qty = Integer.parseInt(m.group(1));
String cardName = m.group(2).trim();
String setCode = m.group(3) != null ? m.group(3).trim() : "";
CardEntry card = new CardEntry(qty, cardName, setCode, currentSection);
a.cards.add(card);
a.totalCards += qty;
if (currentSection.equals("Commander")) {
a.commanderName = cardName;
}
// Tag and classify
tagCard(card);
classifyCard(a, card);
}
}
// Compute health checklist
computeHealthChecks(a);
return a;
}
// ── Card Tagging (Heuristic) ───────────────────────────
/**
* Tag a card with functional roles based on name heuristics.
* This is best-effort without Scryfall data.
*/
private static void tagCard(CardEntry card) {
String lower = card.name.toLowerCase();
// Land detection
if (isLikelyLand(lower)) {
card.tags.add("land");
}
// Ramp
if (isLikelyRamp(lower)) {
card.tags.add("ramp");
}
// Removal
if (isLikelyRemoval(lower)) {
card.tags.add("removal");
}
// Card draw
if (isLikelyDraw(lower)) {
card.tags.add("draw");
}
// Board wipes
if (isLikelyBoardWipe(lower)) {
card.tags.add("wipe");
}
// Tutors
if (isLikelyTutor(lower)) {
card.tags.add("tutor");
}
// Counter spells
if (isLikelyCounter(lower)) {
card.tags.add("counter");
}
// Protection
if (isLikelyProtection(lower)) {
card.tags.add("protection");
}
// Recursion
if (isLikelyRecursion(lower)) {
card.tags.add("recursion");
}
// Creature detection
if (isLikelyCreature(lower)) {
card.tags.add("creature");
}
}
// ── Heuristic Keyword Matchers ─────────────────────────
private static boolean isLikelyLand(String name) {
String[] landKeywords = {
"forest", "island", "mountain", "plains", "swamp",
"land", "grove", "falls", "gardens", "temple",
"shrine", "citadel", "tower", "gate", "passage",
"foundry", "forge", "cave", "marsh", "bog",
"field", "meadow", "terrace", "basin", "pool",
"command tower", "exotic orchard", "mana confluence",
"city of brass", "reflecting pool", "sol ring"
};
// Sol Ring is NOT a land but commonly in land-adjacent lists — remove it
if (name.equals("sol ring")) return false;
for (String kw : landKeywords) {
if (name.contains(kw)) return true;
}
return false;
}
private static boolean isLikelyRamp(String name) {
String[] rampKeywords = {
"sol ring", "mana crypt", "arcane signet", "signet",
"talisman", "cultivate", "kodama's reach", "rampant growth",
"farseek", "nature's lore", "three visits", "sakura-tribe elder",
"solemn simulacrum", "birds of paradise", "llanowar elves",
"elvish mystic", "dryad of the ilysian grove", "exploration",
"mana vault", "mana rock", "fellwar stone", "mind stone",
"thought vessel", "commander's sphere", "gilded lotus",
"thran dynamo", "worn powerstone", "dark ritual",
"cabal ritual", "jeweled lotus", "lotus petal",
"chrome mox", "mox diamond", "growth spiral",
};
for (String kw : rampKeywords) {
if (name.contains(kw)) return true;
}
return false;
}
private static boolean isLikelyRemoval(String name) {
String[] removalKeywords = {
"swords to plowshares", "path to exile", "terminate",
"murder", "doom blade", "go for the throat", "beast within",
"chaos warp", "anguished unmaking", "vindicate",
"assassin's trophy", "generous gift", "rapid hybridization",
"pongify", "reality shift", "cyclonic rift",
"abrupt decay", "mortify", "putrefy", "despark",
"vanishing verse", "fateful absence", "infernal grasp",
"deadly rollick", "force of despair", "dismember",
"ravenous chupacabra", "shriekmaw", "nekrataal",
};
for (String kw : removalKeywords) {
if (name.contains(kw)) return true;
}
return false;
}
private static boolean isLikelyDraw(String name) {
String[] drawKeywords = {
"rhystic study", "mystic remora", "sylvan library",
"phyrexian arena", "necropotence", "harmonize",
"blue sun's zenith", "brainstorm", "ponder", "preordain",
"sign in blood", "read the bones", "night's whisper",
"skullclamp", "beast whisperer", "guardian project",
"the great henge", "esper sentinel", "dark confidant",
"consecrated sphinx", "windfall", "wheel of fortune",
"wheel of misfortune", "faithless looting",
"treasure cruise", "dig through time",
};
for (String kw : drawKeywords) {
if (name.contains(kw)) return true;
}
return false;
}
private static boolean isLikelyBoardWipe(String name) {
String[] wipeKeywords = {
"wrath of god", "damnation", "blasphemous act",
"cyclonic rift", "toxic deluge", "farewell",
"supreme verdict", "merciless eviction", "austere command",
"vanquish the horde", "hour of devastation",
"massacre wurm", "living death", "all is dust",
"decree of pain", "kindred dominance", "in garruk's wake",
"storm's wrath", "chain reaction",
};
for (String kw : wipeKeywords) {
if (name.contains(kw)) return true;
}
return false;
}
private static boolean isLikelyTutor(String name) {
String[] tutorKeywords = {
"demonic tutor", "vampiric tutor", "enlightened tutor",
"mystical tutor", "worldly tutor", "imperial seal",
"gamble", "fabricate", "diabolic tutor", "diabolic intent",
"idyllic tutor", "eladamri's call", "green sun's zenith",
"finale of devastation", "chord of calling",
"natural order", "eldritch evolution",
};
for (String kw : tutorKeywords) {
if (name.contains(kw)) return true;
}
return false;
}
private static boolean isLikelyCounter(String name) {
String[] counterKeywords = {
"counterspell", "swan song", "negate", "arcane denial",
"mana drain", "force of will", "force of negation",
"fierce guardianship", "pact of negation", "dovin's veto",
"delay", "tale's end", "an offer you can't refuse",
"flusterstorm", "mental misstep", "spell pierce",
};
for (String kw : counterKeywords) {
if (name.contains(kw)) return true;
}
return false;
}
private static boolean isLikelyProtection(String name) {
String[] protectionKeywords = {
"lightning greaves", "swiftfoot boots", "heroic intervention",
"teferi's protection", "boros charm", "flawless maneuver",
"deflecting swat", "grand abolisher", "veil of summer",
"mother of runes", "giver of runes", "selfless spirit",
"avacyn, angel of hope", "dauntless bodyguard",
};
for (String kw : protectionKeywords) {
if (name.contains(kw)) return true;
}
return false;
}
private static boolean isLikelyRecursion(String name) {
String[] recursionKeywords = {
"eternal witness", "regrowth", "noxious revival",
"reanimate", "animate dead", "dance of the dead",
"necromancy", "living death", "sun titan",
"muldrotha", "lurrus", "sevinne's reclamation",
"archaeomancer", "snapcaster mage", "mission briefing",
};
for (String kw : recursionKeywords) {
if (name.contains(kw)) return true;
}
return false;
}
private static boolean isLikelyCreature(String name) {
// Very rough heuristic — many Commander creatures have distinctive names
// This catches some but is not exhaustive
String[] creatureKeywords = {
"elder", "dragon", "angel", "demon", "vampire",
"zombie", "goblin", "elf", "knight", "wizard",
"shaman", "cleric", "warrior", "beast", "elemental",
"sphinx", "titan", "wurm", "drake", "spirit",
};
for (String kw : creatureKeywords) {
if (name.contains(kw)) return true;
}
return false;
}
// ── Classification ─────────────────────────────────────
private static void classifyCard(DeckAnalysis a, CardEntry card) {
int qty = card.quantity;
// Count by tag
if (card.tags.contains("land")) a.lands += qty;
if (card.tags.contains("creature")) a.creatures += qty;
if (card.tags.contains("ramp")) a.rampCards += qty;
if (card.tags.contains("removal")) a.removalCards += qty;
if (card.tags.contains("draw")) a.drawCards += qty;
if (card.tags.contains("wipe")) a.boardWipes += qty;
if (card.tags.contains("tutor")) a.tutors += qty;
if (card.tags.contains("counter")) a.counterSpells += qty;
if (card.tags.contains("protection")) a.protectionCards += qty;
if (card.tags.contains("recursion")) a.recursionCards += qty;
}
// ── Health Checks ──────────────────────────────────────
/**
* Commander deck health checklist with recommended ranges.
* Based on common Commander deckbuilding guidelines.
*/
private static void computeHealthChecks(DeckAnalysis a) {
a.healthChecks.put("Lands",
new DeckAnalysis.HealthCheck("Lands", a.lands, 35, 40));
a.healthChecks.put("Ramp",
new DeckAnalysis.HealthCheck("Ramp", a.rampCards, 8, 15));
a.healthChecks.put("Card Draw",
new DeckAnalysis.HealthCheck("Card Draw", a.drawCards, 8, 15));
a.healthChecks.put("Removal",
new DeckAnalysis.HealthCheck("Removal", a.removalCards, 8, 12));
a.healthChecks.put("Board Wipes",
new DeckAnalysis.HealthCheck("Board Wipes", a.boardWipes, 2, 5));
a.healthChecks.put("Total Cards",
new DeckAnalysis.HealthCheck("Total Cards", a.totalCards, 99, 100));
}
// ══════════════════════════════════════════════════════════
// Summary Output
// ══════════════════════════════════════════════════════════
/**
* Print a human-readable analysis summary to stdout.
*/
public static void printSummary(DeckAnalysis a) {
System.out.println("╔══════════════════════════════════════════════════════════╗");
System.out.printf( "║ Deck Analysis: %-40s ║%n", a.deckName);
if (a.commanderName != null) {
System.out.printf("║ Commander: %-44s ║%n", a.commanderName);
}
System.out.printf( "║ Total Cards: %-42d ║%n", a.totalCards);
System.out.println("╠══════════════════════════════════════════════════════════╣");
System.out.println("║ CARD TYPES ");
System.out.printf( "║ Lands: %3d Creatures: %3d%n", a.lands, a.creatures);
System.out.printf( "║ Instants: %3d Sorceries: %3d%n", a.instants, a.sorceries);
System.out.printf( "║ Artifacts: %3d Enchantments: %3d%n", a.artifacts, a.enchantments);
System.out.printf( "║ Planeswalkers: %3d%n", a.planeswalkers);
System.out.println("║");
System.out.println("║ FUNCTIONAL ROLES");
System.out.printf( "║ Ramp: %3d Card Draw: %3d Removal: %3d%n",
a.rampCards, a.drawCards, a.removalCards);
System.out.printf( "║ Wipes: %3d Tutors: %3d Counters: %3d%n",
a.boardWipes, a.tutors, a.counterSpells);
System.out.printf( "║ Protection: %3d Recursion: %3d%n",
a.protectionCards, a.recursionCards);
System.out.println("║");
System.out.println("║ HEALTH CHECKLIST");
for (var check : a.healthChecks.values()) {
String icon = switch (check.status) {
case "good" -> "[OK]";
case "low" -> "[LOW]";
case "high" -> "[HIGH]";
default -> "[??]";
};
System.out.printf("║ %-14s %3d (recommended: %d-%d) %s%n",
check.category, check.actual, check.recommendedMin, check.recommendedMax, icon);
}
System.out.println("╚══════════════════════════════════════════════════════════╝");
}
/**
* Analyze a deck from a Forge decks directory by name.
*/
public static DeckAnalysis analyzeFromForge(String decksDir, String deckName) throws IOException {
// Try exact match first
Path deckPath = Path.of(decksDir, deckName + ".dck");
if (!Files.exists(deckPath)) {
// Try case-insensitive search
try (var stream = Files.list(Path.of(decksDir))) {
deckPath = stream
.filter(p -> p.getFileName().toString().toLowerCase()
.equals(deckName.toLowerCase() + ".dck"))
.findFirst()
.orElse(null);
}
}
if (deckPath == null || !Files.exists(deckPath)) {
throw new FileNotFoundException("Deck not found: " + deckName + " in " + decksDir);
}
return analyze(deckPath.toString());
}
}
@@ -0,0 +1,312 @@
package commanderailab.analytics;
import commanderailab.schema.BatchResult;
import commanderailab.schema.BatchResult.*;
import commanderailab.schema.DeckReport;
import commanderailab.schema.DeckReport.*;
import commanderailab.schema.PerCardGameStats;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.*;
import java.nio.file.*;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
/**
* ReportAggregator — Transforms raw BatchResult data into DeckReport objects.
*
* Reads batch result JSON files and computes:
* - Deck-level stats: win rate, avg game length, matchup records
* - Per-card stats: drawn/cast rates, impact scores, synergy scores
* - Underperformer/overperformer identification
* - Deck structure analysis
*
* Output: writes deck-reports/{deckId}.json to disk.
*/
public class ReportAggregator {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
// Threshold for identifying underperformers (impactScore below this)
private static final double UNDERPERFORMER_THRESHOLD = -0.05;
private static final int MAX_UNDERPERFORMERS = 8;
private static final int MAX_OVERPERFORMERS = 8;
/**
* Generate a DeckReport for a specific deck from multiple batch results.
*
* @param deckId Unique deck identifier (typically deck name)
* @param deckSeat The seat index this deck occupied
* @param batchResults List of batch results to aggregate
* @return Complete DeckReport
*/
public DeckReport generateDeckReport(String deckId, int deckSeat,
List<BatchResult> batchResults) {
DeckReport report = new DeckReport();
report.deckId = deckId;
report.lastUpdated = Instant.now().toString();
// Collect all games where this deck participated
int totalGames = 0;
int totalWins = 0;
long totalTurns = 0;
long totalTurnsOnWin = 0;
// Per-card accumulators
Map<String, CardPerformance> cardMap = new LinkedHashMap<>();
// Matchup tracking: opponent deck name -> [games, wins]
Map<String, int[]> matchupMap = new LinkedHashMap<>();
// Win condition tracking
Map<String, Integer> winConditions = new LinkedHashMap<>();
for (BatchResult batch : batchResults) {
// Find this deck's info
DeckInfo deckInfo = null;
for (DeckInfo di : batch.decks) {
if (di.seatIndex == deckSeat) {
deckInfo = di;
break;
}
}
if (deckInfo == null) continue;
// Set commander/color from first batch
if (report.commander == null || report.commander.isEmpty()) {
report.commander = deckInfo.commanderName != null
? deckInfo.commanderName : deckId;
if (deckInfo.colorIdentity != null) {
report.colorIdentity = new ArrayList<>(deckInfo.colorIdentity);
}
}
// Track opponents for matchups
List<String> opponents = new ArrayList<>();
for (DeckInfo di : batch.decks) {
if (di.seatIndex != deckSeat) {
opponents.add(di.deckName);
}
}
// Process each game
for (GameResult game : batch.games) {
totalGames++;
totalTurns += game.totalTurns;
PlayerResult myResult = null;
for (PlayerResult pr : game.playerResults) {
if (pr.seatIndex == deckSeat) {
myResult = pr;
break;
}
}
if (myResult == null) continue;
boolean won = myResult.isWinner;
if (won) {
totalWins++;
totalTurnsOnWin += game.totalTurns;
if (game.winCondition != null) {
winConditions.merge(game.winCondition, 1, Integer::sum);
}
}
// Track matchups
for (String opp : opponents) {
int[] stats = matchupMap.computeIfAbsent(opp, k -> new int[2]);
stats[0]++; // games
if (won) stats[1]++; // wins
}
// Aggregate per-card stats if available
if (myResult.cardStats != null) {
for (PerCardGameStats pcs : myResult.cardStats) {
CardPerformance cp = cardMap.computeIfAbsent(
pcs.cardName, name -> {
CardPerformance c = new CardPerformance();
c.name = name;
return c;
});
cp.gamesSeen++;
if (pcs.drawn) {
cp.gamesDrawn++;
if (pcs.cast) {
cp.gamesCast++;
cp.gamesWhenCast++;
if (won) cp.winsWhenCast++;
if (pcs.turnCast >= 0) {
cp.totalTurnCast += pcs.turnCast;
}
}
if (pcs.stuckInHand) {
cp.gamesDeadCard++;
}
}
if (pcs.inOpeningHand && pcs.keptInOpeningHand) {
cp.gamesKeptInOpening++;
}
cp.totalDamage += pcs.damageDealt;
}
}
}
}
// ── Compute deck-level stats ──────────────────────────────
report.meta.gamesSimulated = totalGames;
report.meta.overallWinRate = totalGames > 0
? (double) totalWins / totalGames : 0.0;
report.meta.avgGameLength = totalGames > 0
? (double) totalTurns / totalGames : 0.0;
// ── Compute matchups ──────────────────────────────────────
for (Map.Entry<String, int[]> entry : matchupMap.entrySet()) {
MatchupRecord mr = new MatchupRecord();
mr.opponentDeck = entry.getKey();
mr.gamesPlayed = entry.getValue()[0];
mr.winRate = mr.gamesPlayed > 0
? (double) entry.getValue()[1] / mr.gamesPlayed : 0.0;
report.matchups.add(mr);
}
// ── Compute per-card performance ──────────────────────────
double overallWinRate = report.meta.overallWinRate;
for (CardPerformance cp : cardMap.values()) {
int gs = cp.gamesSeen;
if (gs == 0) continue;
cp.drawnRate = (double) cp.gamesDrawn / gs;
cp.castRate = cp.gamesDrawn > 0
? (double) cp.gamesCast / cp.gamesDrawn : 0.0;
cp.deadCardRate = cp.gamesDrawn > 0
? (double) cp.gamesDeadCard / cp.gamesDrawn : 0.0;
cp.keptInOpeningHandRate = gs > 0
? (double) cp.gamesKeptInOpening / gs : 0.0;
// Impact score: how much does casting this card correlate with winning?
double winRateWhenCast = cp.gamesWhenCast > 0
? (double) cp.winsWhenCast / cp.gamesWhenCast : 0.0;
cp.impactScore = (winRateWhenCast - overallWinRate) * cp.castRate;
// Clunkiness: high dead card rate + low cast rate = clunky
cp.clunkinessScore = cp.deadCardRate * (1.0 - cp.castRate);
// Average turn cast
cp.avgTurnCast = cp.gamesCast > 0
? cp.totalTurnCast / cp.gamesCast : null;
cp.avgDamageDealt = gs > 0 ? cp.totalDamage / gs : 0.0;
report.cards.add(cp);
}
// ── Identify under/over performers ────────────────────────
List<CardPerformance> sorted = report.cards.stream()
.sorted(Comparator.comparingDouble(c -> c.impactScore))
.collect(Collectors.toList());
for (int i = 0; i < Math.min(MAX_UNDERPERFORMERS, sorted.size()); i++) {
CardPerformance cp = sorted.get(i);
if (cp.impactScore < UNDERPERFORMER_THRESHOLD) {
report.underperformers.add(cp.name);
}
}
for (int i = sorted.size() - 1;
i >= Math.max(0, sorted.size() - MAX_OVERPERFORMERS); i--) {
CardPerformance cp = sorted.get(i);
if (cp.impactScore > 0) {
report.overperformers.add(cp.name);
}
}
return report;
}
/**
* Save a DeckReport as JSON to the specified directory.
*/
public void saveDeckReport(DeckReport report, Path outputDir) throws IOException {
Files.createDirectories(outputDir);
Path outFile = outputDir.resolve(report.deckId + ".json");
try (Writer writer = new FileWriter(outFile.toFile())) {
GSON.toJson(report, writer);
}
}
/**
* Load a DeckReport from JSON file.
*/
public DeckReport loadDeckReport(Path reportFile) throws IOException {
try (Reader reader = new FileReader(reportFile.toFile())) {
return GSON.fromJson(reader, DeckReport.class);
}
}
/**
* Load a BatchResult from JSON file.
*/
public BatchResult loadBatchResult(Path resultFile) throws IOException {
try (Reader reader = new FileReader(resultFile.toFile())) {
return GSON.fromJson(reader, BatchResult.class);
}
}
/**
* Rebuild all deck reports from a directory of batch result JSONs.
*/
public List<DeckReport> rebuildAllReports(Path inputLogsDir, Path outputDir)
throws IOException {
List<BatchResult> allResults = new ArrayList<>();
// Load all batch result files
try (var stream = Files.list(inputLogsDir)) {
stream.filter(p -> p.toString().endsWith(".json"))
.forEach(p -> {
try {
allResults.add(loadBatchResult(p));
} catch (IOException e) {
System.err.println("Failed to load: " + p + " - " + e.getMessage());
}
});
}
if (allResults.isEmpty()) {
System.out.println("No batch result files found in " + inputLogsDir);
return Collections.emptyList();
}
// Find all unique decks across batches
Map<String, Integer> deckSeats = new LinkedHashMap<>();
for (BatchResult br : allResults) {
for (DeckInfo di : br.decks) {
deckSeats.putIfAbsent(di.deckName, di.seatIndex);
}
}
// Generate report for each deck
List<DeckReport> reports = new ArrayList<>();
for (Map.Entry<String, Integer> entry : deckSeats.entrySet()) {
DeckReport report = generateDeckReport(
entry.getKey(), entry.getValue(), allResults);
saveDeckReport(report, outputDir);
reports.add(report);
System.out.printf("Generated report for %s: %d games, %.1f%% win rate%n",
report.deckId, report.meta.gamesSimulated,
report.meta.overallWinRate * 100);
}
return reports;
}
}
@@ -0,0 +1,949 @@
package commanderailab.batch;
import commanderailab.ai.AiPolicy;
import commanderailab.ml.DecisionExtractor;
import commanderailab.ml.DecisionLogger;
import commanderailab.schema.BatchResult;
import commanderailab.schema.BatchResult.*;
import commanderailab.schema.DecisionSnapshot;
import commanderailab.schema.PerCardGameStats;
import commanderailab.stats.StatsAggregator;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.*;
/**
* BatchRunner — Single-threaded batch simulation runner.
*
* Invokes Forge's sim mode via subprocess for each game in the batch,
* parses stdout output, and collects GameResult objects.
*
* Forge output format (with -q flag):
* Game Outcome: Turn 11
* Game Outcome: Ai(1)-Edgar Markov has won because all opponents have lost
* Game Outcome: Ai(2)-Grimgrin has lost because life total reached 0
* Game Outcome: Ai(3)-Xyris has lost because life total reached 0
* Match Result: Ai(1)-Edgar Markov: 1 Ai(2)-Grimgrin: 0 Ai(3)-Xyris: 0
* Game Result: Game 1 ended in 9201 ms. Ai(1)-Edgar Markov has won!
*/
public class BatchRunner {
private final String forgeJarPath; // Path to forge-gui-desktop JAR (jar-with-dependencies)
private final String forgeWorkDir; // Working directory for Forge (where res/ folder is)
private final List<DeckInfo> decks; // Exactly 3 decks
private final AiPolicy policy;
private final boolean quiet;
private final int clockSeconds; // Max seconds per game before draw (default 120)
private String javaPath = "java"; // Path to Java 17 executable (Forge requires Java 17)
// ── ML Decision Logging ───────────────────────────────────
private boolean mlLoggingEnabled = false;
private DecisionLogger mlDecisionLogger;
private String mlResultsDir = "results";
// ── Regex patterns for parsing Forge sim output ────────────────────
// "Game Outcome: Turn 11"
private static final Pattern TURN_PATTERN =
Pattern.compile("Game Outcome:\\s*Turn\\s+(\\d+)");
// "Game Outcome: Ai(1)-Edgar Markov has won because all opponents have lost"
private static final Pattern WINNER_PATTERN =
Pattern.compile("Game Outcome:\\s*Ai\\((\\d+)\\)-(.+?)\\s+has won because (.+)");
// "Game Outcome: Ai(2)-Grimgrin has lost because life total reached 0"
private static final Pattern LOSER_PATTERN =
Pattern.compile("Game Outcome:\\s*Ai\\((\\d+)\\)-(.+?)\\s+has lost because (.+)");
// "Game Result: Game 1 ended in 9201 ms. Ai(1)-Edgar Markov has won!"
private static final Pattern GAME_RESULT_PATTERN =
Pattern.compile("Game Result:\\s*Game\\s+(\\d+)\\s+ended in\\s+(\\d+)\\s*ms\\.\\s*(.+?)\\s+has won!");
// "Game Result: Game 1 ended in 9201 ms. It's a draw!" (timeout/draw case)
private static final Pattern GAME_DRAW_PATTERN =
Pattern.compile("Game Result:\\s*Game\\s+(\\d+)\\s+ended in\\s+(\\d+)\\s*ms\\..+draw", Pattern.CASE_INSENSITIVE);
// "Match Result: Ai(1)-Edgar Markov: 1 Ai(2)-Grimgrin: 0 Ai(3)-Xyris: 0"
private static final Pattern MATCH_RESULT_PATTERN =
Pattern.compile("Match Result:");
// ── Verbose game-log patterns for extracting combat stats ────────────
// "Ai(1)-Name casts CardName" — any spell cast
private static final Pattern CAST_PATTERN =
Pattern.compile("Ai\\((\\d+)\\)-[^\\s].*?\\s+casts\\s+(.+?)\\.", Pattern.CASE_INSENSITIVE);
// "Ai(1)-Name plays Land" — land drop
private static final Pattern LAND_PLAY_PATTERN =
Pattern.compile("Ai\\((\\d+)\\)-[^\\s].*?\\s+plays\\s+(.+?)\\.", Pattern.CASE_INSENSITIVE);
// "...is destroyed" or "...is put into graveyard from the battlefield"
private static final Pattern CREATURE_DESTROYED_PATTERN =
Pattern.compile("(is destroyed|dies|is put into .* graveyard from the battlefield)", Pattern.CASE_INSENSITIVE);
// "deals N combat damage" or "deals N damage to Ai(X)"
private static final Pattern DAMAGE_PATTERN =
Pattern.compile("deals\\s+(\\d+)\\s+(?:combat\\s+)?damage\\s+to\\s+Ai\\((\\d+)\\)", Pattern.CASE_INSENSITIVE);
// "commander damage" — specifically commander damage dealt
private static final Pattern CMDR_DAMAGE_PATTERN =
Pattern.compile("Ai\\((\\d+)\\).*?commander.*?damage.*?(\\d+)", Pattern.CASE_INSENSITIVE);
// ── Per-card tracking patterns (verbose log) ─────────────────────────
// "Ai(1)-Name draws CardName." — card drawn
private static final Pattern DRAW_PATTERN =
Pattern.compile("Ai\\((\\d+)\\)-[^\\s].*?\\s+draws\\s+(.+?)\\.", Pattern.CASE_INSENSITIVE);
// Turn boundary: "Turn 5 (Ai(1)-Name)" or "Turn 5 (Ai(2)-Name)"
// Some Forge versions use: "== Turn X (Ai(N)-Name) =="
private static final Pattern VERBOSE_TURN_PATTERN =
Pattern.compile("Turn\\s+(\\d+)\\s+\\(Ai\\((\\d+)\\)", Pattern.CASE_INSENSITIVE);
// "CardName deals N damage" — damage by a specific card
private static final Pattern CARD_DAMAGE_PATTERN =
Pattern.compile("(.+?)\\s+deals\\s+(\\d+)\\s+(?:combat\\s+)?damage", Pattern.CASE_INSENSITIVE);
public BatchRunner(String forgeJarPath, String forgeWorkDir, List<DeckInfo> decks, AiPolicy policy) {
this(forgeJarPath, forgeWorkDir, decks, policy, false, 120); // verbose by default for combat stats
}
public BatchRunner(String forgeJarPath, String forgeWorkDir, List<DeckInfo> decks,
AiPolicy policy, boolean quiet, int clockSeconds) {
this(forgeJarPath, forgeWorkDir, decks, policy, quiet, clockSeconds, "java");
}
public BatchRunner(String forgeJarPath, String forgeWorkDir, List<DeckInfo> decks,
AiPolicy policy, boolean quiet, int clockSeconds, String javaPath) {
if (decks.size() != 3) {
throw new IllegalArgumentException("v1 requires exactly 3 decks, got " + decks.size());
}
this.forgeJarPath = forgeJarPath;
this.forgeWorkDir = forgeWorkDir;
this.decks = decks;
this.policy = policy;
this.quiet = quiet;
this.clockSeconds = clockSeconds;
this.javaPath = (javaPath != null && !javaPath.isEmpty()) ? javaPath : "java";
}
/**
* Enable ML decision logging for this batch.
* When enabled, each game's decision points are extracted and written
* to a JSONL file for supervised learning.
*
* @param resultsDir Directory for ML output files
* @param batchId Batch identifier for file naming
*/
public void enableMlLogging(String resultsDir, String batchId) {
this.mlLoggingEnabled = true;
this.mlResultsDir = resultsDir;
try {
this.mlDecisionLogger = new DecisionLogger(resultsDir, batchId);
System.out.println("[ML] Decision logging enabled for batch: " + batchId);
} catch (IOException e) {
System.err.println("[ML] Failed to initialize decision logger: " + e.getMessage());
this.mlLoggingEnabled = false;
}
}
/**
* Close ML logger after batch completes. Call from the API layer.
*/
public void closeMlLogger() {
if (mlDecisionLogger != null) {
mlDecisionLogger.close();
}
}
public boolean isMlLoggingEnabled() {
return mlLoggingEnabled;
}
public DecisionLogger getMlDecisionLogger() {
return mlDecisionLogger;
}
/**
* Run N games sequentially on the current thread.
* Each invocation of Forge sim runs 1 game (-n 1) to get individual results.
*
* @param numGames Number of games to simulate
* @param masterSeed Base seed (null for random); each game uses masterSeed + gameIndex
* @return List of GameResult objects
*/
public List<GameResult> runBatchSingleThread(int numGames, Long masterSeed) {
List<GameResult> results = new ArrayList<>();
for (int i = 0; i < numGames; i++) {
long gameSeed = (masterSeed != null) ? masterSeed + i : System.nanoTime();
long startMs = System.currentTimeMillis();
try {
GameResult result = runSingleGame(i, gameSeed);
// Use Forge-reported time if available, otherwise wall clock
if (result.elapsedMs == 0) {
result.elapsedMs = System.currentTimeMillis() - startMs;
}
results.add(result);
System.out.printf("[Game %d/%d] Winner: %s | Turns: %d | Time: %dms%n",
i + 1, numGames,
result.winningSeat != null
? decks.get(result.winningSeat).deckName
: "DRAW",
result.totalTurns, result.elapsedMs);
} catch (Exception e) {
System.err.printf("[Game %d/%d] ERROR: %s%n", i + 1, numGames, e.getMessage());
GameResult failed = createFailedGame(i, gameSeed, System.currentTimeMillis() - startMs);
results.add(failed);
}
}
return results;
}
/**
* Run a single game via Forge subprocess.
*/
private GameResult runSingleGame(int gameIndex, long gameSeed) throws IOException, InterruptedException {
List<String> cmd = buildForgeCommand();
// Log the full command for debugging
String cmdStr = String.join(" ", cmd);
System.out.println("[DEBUG] Forge command: " + cmdStr);
System.out.println("[DEBUG] Working dir: " + forgeWorkDir);
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.directory(new File(forgeWorkDir));
pb.redirectErrorStream(true);
// Remove JAVA_TOOL_OPTIONS if inherited — it interferes with Forge startup
pb.environment().remove("JAVA_TOOL_OPTIONS");
// Timeout: clock seconds + 120s buffer for initialization
long timeoutSeconds = clockSeconds + 120;
Process process = pb.start();
// Read stdout with a watchdog thread for timeout
StringBuilder output = new StringBuilder();
Thread watchdog = new Thread(() -> {
try {
Thread.sleep(timeoutSeconds * 1000);
if (process.isAlive()) {
System.err.println("[WATCHDOG] Forge process exceeded timeout (" + timeoutSeconds + "s). Killing.");
process.destroyForcibly();
}
} catch (InterruptedException ignored) {
// Normal: watchdog cancelled because process finished in time
}
}, "ForgeWatchdog-" + gameIndex);
watchdog.setDaemon(true);
watchdog.start();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
}
int exitCode = process.waitFor();
watchdog.interrupt(); // Cancel watchdog if process finished naturally
// Diagnostic: show Forge output summary
String rawOutput = output.toString();
String[] outLines = rawOutput.split("\n");
System.out.printf("[DEBUG] Forge exit=%d, output=%d lines, length=%d chars%n",
exitCode, outLines.length, rawOutput.length());
if (rawOutput.isBlank()) {
System.out.println("[DEBUG] Forge produced NO output — deck may not be found or Forge failed silently");
} else {
// Print first 5 and last 5 lines for quick diagnosis
int show = Math.min(5, outLines.length);
for (int li = 0; li < show; li++) {
System.out.println("[DEBUG] OUT> " + outLines[li]);
}
if (outLines.length > 10) {
System.out.println("[DEBUG] ... (" + (outLines.length - 10) + " lines omitted) ...");
for (int li = outLines.length - 5; li < outLines.length; li++) {
if (li >= 0) System.out.println("[DEBUG] OUT> " + outLines[li]);
}
}
}
// Write debug log for every game
writeDebugLog(gameIndex, cmdStr, rawOutput, exitCode);
return parseForgeOutput(gameIndex, gameSeed, rawOutput, exitCode);
}
/**
* Write raw Forge subprocess output to a debug log file.
* This helps diagnose issues where Forge produces unexpected output.
*/
private void writeDebugLog(int gameIndex, String command, String output, int exitCode) {
try {
Path logDir = Path.of(forgeWorkDir).getParent();
if (logDir == null) logDir = Path.of(".");
Path logFile = logDir.resolve("forge-sim-debug.log");
StringBuilder log = new StringBuilder();
log.append("\n════════════════════════════════════════════════════════════\n");
log.append("Game ").append(gameIndex).append(" @ ");
log.append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
log.append("\nCommand: ").append(command);
log.append("\nWorking Dir: ").append(forgeWorkDir);
log.append("\nExit Code: ").append(exitCode);
log.append("\n── RAW OUTPUT ──────────────────────────────────────────────\n");
if (output.isBlank()) {
log.append("<< NO OUTPUT >>\n");
} else {
log.append(output);
}
log.append("── END OUTPUT ──────────────────────────────────────────────\n");
Files.writeString(logFile, log.toString(), StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
System.out.println("[DEBUG] Log written to: " + logFile.toAbsolutePath());
} catch (Exception e) {
System.err.println("[DEBUG] Failed to write debug log: " + e.getMessage());
}
}
/**
* Build the Forge sim command.
* Invokes: java -jar forge-gui-desktop-XXX-jar-with-dependencies.jar sim -d "deck1" "deck2" "deck3" -f commander -n 1 -q
*/
private List<String> buildForgeCommand() {
List<String> cmd = new ArrayList<>();
cmd.add(javaPath);
// ── Forge-required JVM flags (from forge-gui-desktop/pom.xml) ──────
// Memory — Commander 3-player games need substantial heap
cmd.add("-Xmx4096m");
// NOTE: Do NOT add -Djava.awt.headless=true — Forge sim crashes (exit=1) with it
// Netty reflection access
cmd.add("-Dio.netty.tryReflectionSetAccessible=true");
// UTF-8 encoding
cmd.add("-Dfile.encoding=UTF-8");
// ── Module access flags required by Forge on Java 17+ ─────────────
String[] addOpens = {
"java.desktop/java.beans=ALL-UNNAMED",
"java.desktop/javax.swing.border=ALL-UNNAMED",
"java.desktop/javax.swing.event=ALL-UNNAMED",
"java.desktop/sun.swing=ALL-UNNAMED",
"java.desktop/java.awt.image=ALL-UNNAMED",
"java.desktop/java.awt.color=ALL-UNNAMED",
"java.desktop/sun.awt.image=ALL-UNNAMED",
"java.desktop/javax.swing=ALL-UNNAMED",
"java.desktop/java.awt=ALL-UNNAMED",
"java.base/java.util=ALL-UNNAMED",
"java.base/java.lang=ALL-UNNAMED",
"java.base/java.lang.reflect=ALL-UNNAMED",
"java.base/java.text=ALL-UNNAMED",
"java.desktop/java.awt.font=ALL-UNNAMED",
"java.base/jdk.internal.misc=ALL-UNNAMED",
"java.base/sun.nio.ch=ALL-UNNAMED",
"java.base/java.nio=ALL-UNNAMED",
"java.base/java.math=ALL-UNNAMED",
"java.base/java.util.concurrent=ALL-UNNAMED",
"java.base/java.net=ALL-UNNAMED",
};
for (String module : addOpens) {
cmd.add("--add-opens");
cmd.add(module);
}
cmd.add("-jar");
cmd.add(forgeJarPath);
cmd.add("sim");
// Deck arguments — append .dck so Forge loads from DECK_COMMANDER_DIR as files
// Without .dck, Forge uses FModel deck store which may fail in subprocess context
cmd.add("-d");
for (DeckInfo deck : decks) {
String name = deck.deckFile;
if (!name.endsWith(".dck")) {
name = name + ".dck";
}
cmd.add(name);
}
// Format
cmd.add("-f");
cmd.add("commander");
// Single game per subprocess call
cmd.add("-n");
cmd.add("1");
// Clock (max seconds per game)
cmd.add("-c");
cmd.add(String.valueOf(clockSeconds));
// Quiet mode for parseable output
if (quiet) {
cmd.add("-q");
}
return cmd;
}
/**
* Parse Forge's stdout output into a GameResult.
*
* Expected lines:
* Game Outcome: Turn 11
* Game Outcome: Ai(1)-Edgar Markov has won because all opponents have lost
* Game Outcome: Ai(2)-Grimgrin has lost because life total reached 0
* Game Outcome: Ai(3)-Xyris has lost because life total reached 0
* Game Result: Game 1 ended in 9201 ms. Ai(1)-Edgar Markov has won!
*/
private GameResult parseForgeOutput(int gameIndex, long gameSeed, String output, int exitCode) {
GameResult result = new GameResult();
result.gameIndex = gameIndex;
result.gameSeed = gameSeed;
result.winCondition = "unknown";
result.totalTurns = 0;
result.elapsedMs = 0;
// Initialize player results for all 3 seats
result.playerResults = new ArrayList<>();
for (int i = 0; i < 3; i++) {
PlayerResult pr = new PlayerResult();
pr.seatIndex = i;
pr.finalLife = 40; // Commander starting life
pr.mulligans = 0;
pr.isWinner = false;
pr.commanderDamageDealt = 0;
pr.commanderCasts = 0;
pr.landsPlayed = 0;
pr.spellsCast = 0;
pr.creaturesDestroyed = 0;
result.playerResults.add(pr);
}
if (output.isBlank()) {
result.winCondition = "timeout";
return result;
}
String[] lines = output.split("\n");
Map<String, String> lossReasons = new HashMap<>();
for (String line : lines) {
line = line.trim();
// Parse turn count: "Game Outcome: Turn 11"
Matcher turnMatcher = TURN_PATTERN.matcher(line);
if (turnMatcher.find()) {
result.totalTurns = Integer.parseInt(turnMatcher.group(1));
continue;
}
// Parse winner: "Game Outcome: Ai(1)-Edgar Markov has won because ..."
Matcher winMatcher = WINNER_PATTERN.matcher(line);
if (winMatcher.find()) {
int aiNumber = Integer.parseInt(winMatcher.group(1));
int seatIndex = aiNumber - 1; // Forge uses 1-based, we use 0-based
String winReason = winMatcher.group(3).trim();
if (seatIndex >= 0 && seatIndex < 3) {
result.winningSeat = seatIndex;
result.playerResults.get(seatIndex).isWinner = true;
}
continue;
}
// Parse loser: "Game Outcome: Ai(2)-Grimgrin has lost because life total reached 0"
Matcher loseMatcher = LOSER_PATTERN.matcher(line);
if (loseMatcher.find()) {
int aiNumber = Integer.parseInt(loseMatcher.group(1));
int seatIndex = aiNumber - 1;
String lossReason = loseMatcher.group(3).trim();
if (seatIndex >= 0 && seatIndex < 3) {
lossReasons.put(String.valueOf(seatIndex), lossReason);
// Try to extract final life from loss reason
if (lossReason.contains("life total reached 0")) {
result.playerResults.get(seatIndex).finalLife = 0;
} else if (lossReason.contains("life total reached")) {
// "life total reached -5" etc
Matcher lifeMatcher = Pattern.compile("life total reached (-?\\d+)").matcher(lossReason);
if (lifeMatcher.find()) {
result.playerResults.get(seatIndex).finalLife = Integer.parseInt(lifeMatcher.group(1));
}
}
}
continue;
}
// Parse game result timing: "Game Result: Game 1 ended in 9201 ms."
Matcher gameResultMatcher = GAME_RESULT_PATTERN.matcher(line);
if (gameResultMatcher.find()) {
result.elapsedMs = Long.parseLong(gameResultMatcher.group(2));
continue;
}
// Parse draw: "Game Result: Game 1 ended in ... draw"
Matcher drawMatcher = GAME_DRAW_PATTERN.matcher(line);
if (drawMatcher.find()) {
result.elapsedMs = Long.parseLong(drawMatcher.group(2));
result.winningSeat = null;
result.winCondition = "timeout";
continue;
}
// Count mulligans from non-quiet output
if (line.toLowerCase().contains("mulligan")) {
Matcher mullMatcher = Pattern.compile("Ai\\((\\d+)\\)").matcher(line);
if (mullMatcher.find()) {
int aiNum = Integer.parseInt(mullMatcher.group(1));
int seat = aiNum - 1;
if (seat >= 0 && seat < 3) {
result.playerResults.get(seat).mulligans++;
}
}
}
}
// Classify win condition from loss reasons
result.winCondition = classifyWinCondition(lossReasons, output);
// Default turn count if not parsed
if (result.totalTurns == 0) {
result.totalTurns = 1;
}
// ── Parse verbose game log for combat stats ─────────────────────
// These patterns match Forge's full game log (non-quiet mode)
// Track commander names for each seat to detect commander casts
String[] commanderNames = new String[3];
for (int ci = 0; ci < 3 && ci < decks.size(); ci++) {
commanderNames[ci] = decks.get(ci).commanderName;
}
for (String line : lines) {
line = line.trim();
if (line.isEmpty()) continue;
// Match spell casts: "Ai(1)-Name casts CardName."
Matcher castMatcher = CAST_PATTERN.matcher(line);
if (castMatcher.find()) {
int aiNum = Integer.parseInt(castMatcher.group(1));
int seat = aiNum - 1;
String cardName = castMatcher.group(2).trim();
if (seat >= 0 && seat < 3) {
result.playerResults.get(seat).spellsCast++;
// Check if this is the commander being cast
if (commanderNames[seat] != null &&
cardName.equalsIgnoreCase(commanderNames[seat])) {
result.playerResults.get(seat).commanderCasts++;
}
}
continue;
}
// Match land plays: "Ai(1)-Name plays LandName."
Matcher landMatcher = LAND_PLAY_PATTERN.matcher(line);
if (landMatcher.find()) {
int aiNum = Integer.parseInt(landMatcher.group(1));
int seat = aiNum - 1;
if (seat >= 0 && seat < 3) {
result.playerResults.get(seat).landsPlayed++;
}
continue;
}
// Match damage dealt: "deals N damage to Ai(X)"
Matcher dmgMatcher = DAMAGE_PATTERN.matcher(line);
while (dmgMatcher.find()) {
// Note: this captures damage TO a player, not FROM.
// We track it as creature/combat damage events
}
// Match creature deaths: "is destroyed" / "dies"
if (CREATURE_DESTROYED_PATTERN.matcher(line).find()) {
// Try to figure out which player's creature died
// Look for Ai(N) reference before the destruction text
Matcher aiRef = Pattern.compile("Ai\\((\\d+)\\)").matcher(line);
// We attribute destruction to the OPPOSING player (the one who caused it)
// But since we can't reliably determine the attacker, count it globally
// For each seat, count creatures they destroyed (opponent's creatures that died)
// Simple heuristic: if a creature controlled by Ai(X) dies, credit opponents
if (aiRef.find()) {
int aiNum = Integer.parseInt(aiRef.group(1));
int victimSeat = aiNum - 1;
// Credit all non-victim seats with 1 creature destroyed
for (int s = 0; s < 3; s++) {
if (s != victimSeat && s < result.playerResults.size()) {
// We can't know who did it, so we don't increment here
// Instead, use a simpler approach below
}
}
}
}
// Commander damage tracking from loss reasons (already captured above)
// Also try to parse "commander damage" mentions in verbose log
if (line.toLowerCase().contains("commander damage")) {
Matcher cdmg = Pattern.compile("(\\d+)\\s+commander\\s+damage").matcher(line.toLowerCase());
if (cdmg.find()) {
int amount = Integer.parseInt(cdmg.group(1));
// Try to find the source player
Matcher srcPlayer = Pattern.compile("Ai\\((\\d+)\\)").matcher(line);
if (srcPlayer.find()) {
int seat = Integer.parseInt(srcPlayer.group(1)) - 1;
if (seat >= 0 && seat < 3) {
result.playerResults.get(seat).commanderDamageDealt += amount;
}
}
}
}
}
// Estimate creatures destroyed from total turns if verbose parsing didn't catch specifics
// (Forge log format varies; this provides a reasonable fallback)
for (int seat = 0; seat < 3 && seat < result.playerResults.size(); seat++) {
PlayerResult pr = result.playerResults.get(seat);
// If we got no spell data from parsing, it means either quiet mode or no matches
// Leave at 0 rather than fabricating data
}
// ── Build per-card stats from verbose output (for coach analytics) ──
if (!quiet) {
try {
buildPerCardStats(result, lines);
} catch (Exception e) {
System.err.println("[COACH] Per-card stat tracking failed: " + e.getMessage());
// Non-fatal — game result is still valid without per-card data
}
}
// ── ML Decision extraction (for RL training data) ─────────────────
if (mlLoggingEnabled && !quiet && mlDecisionLogger != null) {
try {
int numPlayers = decks.size();
String gid = "game-" + gameIndex + "-" + gameSeed;
String[] cmdNames = new String[numPlayers];
List<List<String>> deckCardLists = new ArrayList<>();
for (int di = 0; di < numPlayers; di++) {
cmdNames[di] = decks.get(di).commanderName;
deckCardLists.add(readDeckCardNames(decks.get(di).deckFile));
}
DecisionExtractor extractor = new DecisionExtractor(
numPlayers, gid, cmdNames, deckCardLists);
List<DecisionSnapshot> decisions = extractor.processGameLog(lines);
// Build deck metadata map
Map<Integer, Map<String, String>> deckMeta = new HashMap<>();
for (int di = 0; di < numPlayers; di++) {
Map<String, String> meta = new HashMap<>();
meta.put("name", decks.get(di).deckName);
meta.put("commander", decks.get(di).commanderName);
meta.put("archetype", decks.get(di).archetype != null ? decks.get(di).archetype : "midrange");
deckMeta.put(di, meta);
}
// Determine game outcome
String outcome = result.winningSeat != null
? "win_seat_" + result.winningSeat
: "draw";
mlDecisionLogger.logGameDecisions(decisions, deckMeta, outcome);
if (!decisions.isEmpty()) {
System.out.printf("[ML] Game %d: %d decision snapshots extracted%n",
gameIndex, decisions.size());
}
} catch (Exception e) {
System.err.println("[ML] Decision extraction failed for game " + gameIndex + ": " + e.getMessage());
// Non-fatal
}
}
return result;
}
// ══════════════════════════════════════════════════════════════
// Per-Card Stat Tracking
// ══════════════════════════════════════════════════════════════
/**
* Read card names from a Forge .dck file.
* Format:
* [Commander]
* 1 Card Name|SET
* [Main]
* 1 Card Name|SET
* ...
*
* Returns all card names (Commander + Main), excluding sideboard.
*/
private List<String> readDeckCardNames(String deckFilePath) {
List<String> names = new ArrayList<>();
try {
Path path = Path.of(deckFilePath);
if (!Files.exists(path)) {
System.err.println("[COACH] Deck file not found: " + deckFilePath);
return names;
}
List<String> lines = Files.readAllLines(path);
String section = "Main";
Pattern cardLine = Pattern.compile("^(\\d+)\\s+(.+?)(?:\\|(.+))?$");
for (String line : lines) {
line = line.trim();
if (line.isEmpty() || line.startsWith("//")) continue;
if (line.startsWith("[") && line.endsWith("]")) {
section = line.substring(1, line.length() - 1);
continue;
}
if (line.startsWith("Name=")) continue;
// Skip sideboard
if (section.equalsIgnoreCase("Sideboard")) continue;
Matcher m = cardLine.matcher(line);
if (m.matches()) {
String cardName = m.group(2).trim();
int qty = Integer.parseInt(m.group(1));
// In Commander, qty is always 1, but just in case
for (int q = 0; q < qty; q++) {
names.add(cardName);
}
}
}
} catch (Exception e) {
System.err.println("[COACH] Failed to read deck file: " + deckFilePath + " - " + e.getMessage());
}
return names;
}
/**
* Build per-card game stats from verbose Forge log output.
*
* Tracks for each card in each player's deck:
* - drawn: was the card drawn (or in opening hand)
* - turnDrawn: first turn the card was drawn
* - cast: was the card cast
* - turnCast: turn it was cast
* - stuckInHand: drawn but never cast
* - damageDealt: damage attributed to this card (best effort)
* - inOpeningHand / keptInOpeningHand: opening-hand tracking
*/
private void buildPerCardStats(GameResult result, String[] lines) {
// Initialize per-card maps for each seat from deck files
@SuppressWarnings("unchecked")
Map<String, PerCardGameStats>[] seatCards = new Map[3];
for (int s = 0; s < 3 && s < decks.size(); s++) {
seatCards[s] = new LinkedHashMap<>();
List<String> cardNames = readDeckCardNames(decks.get(s).deckFile);
for (String name : cardNames) {
if (!seatCards[s].containsKey(name)) {
seatCards[s].put(name, new PerCardGameStats(name));
}
}
}
// Track current turn per seat
int globalTurn = 0;
boolean[] openingHandPhase = {true, true, true}; // before first turn
for (String rawLine : lines) {
String line = rawLine.trim();
if (line.isEmpty()) continue;
// Detect turn boundaries: "Turn 5 (Ai(1)-Name)"
Matcher turnMatch = VERBOSE_TURN_PATTERN.matcher(line);
if (turnMatch.find()) {
int turnNum = Integer.parseInt(turnMatch.group(1));
int aiNum = Integer.parseInt(turnMatch.group(2));
globalTurn = turnNum;
int seat = aiNum - 1;
if (seat >= 0 && seat < 3) {
openingHandPhase[seat] = false;
}
continue;
}
// Detect draws: "Ai(1)-Name draws CardName."
Matcher drawMatch = DRAW_PATTERN.matcher(line);
if (drawMatch.find()) {
int seat = Integer.parseInt(drawMatch.group(1)) - 1;
String cardName = drawMatch.group(2).trim();
if (seat >= 0 && seat < 3 && seatCards[seat] != null) {
PerCardGameStats stats = seatCards[seat].get(cardName);
if (stats == null) {
// Card not in deck list (token draw, etc.) — create entry
stats = new PerCardGameStats(cardName);
seatCards[seat].put(cardName, stats);
}
if (!stats.drawn) {
stats.drawn = true;
stats.turnDrawn = globalTurn;
}
if (openingHandPhase[seat]) {
stats.inOpeningHand = true;
stats.keptInOpeningHand = true; // assume kept unless mulligan detected
}
}
continue;
}
// Detect casts: "Ai(1)-Name casts CardName."
Matcher castMatch = CAST_PATTERN.matcher(line);
if (castMatch.find()) {
int seat = Integer.parseInt(castMatch.group(1)) - 1;
String cardName = castMatch.group(2).trim();
if (seat >= 0 && seat < 3 && seatCards[seat] != null) {
PerCardGameStats stats = seatCards[seat].get(cardName);
if (stats == null) {
stats = new PerCardGameStats(cardName);
seatCards[seat].put(cardName, stats);
}
if (!stats.cast) {
stats.cast = true;
stats.turnCast = globalTurn;
}
// Mark as drawn if not already (commander zone casts, etc.)
if (!stats.drawn) {
stats.drawn = true;
stats.turnDrawn = globalTurn;
}
}
continue;
}
// Detect land plays: "Ai(1)-Name plays LandName."
Matcher landMatch = LAND_PLAY_PATTERN.matcher(line);
if (landMatch.find()) {
int seat = Integer.parseInt(landMatch.group(1)) - 1;
String cardName = landMatch.group(2).trim();
if (seat >= 0 && seat < 3 && seatCards[seat] != null) {
PerCardGameStats stats = seatCards[seat].get(cardName);
if (stats == null) {
stats = new PerCardGameStats(cardName);
seatCards[seat].put(cardName, stats);
}
if (!stats.cast) {
stats.cast = true; // playing a land counts as "using" it
stats.turnCast = globalTurn;
}
if (!stats.drawn) {
stats.drawn = true;
stats.turnDrawn = globalTurn;
}
}
continue;
}
// Detect per-card damage: "CardName deals N damage"
Matcher cardDmgMatch = CARD_DAMAGE_PATTERN.matcher(line);
if (cardDmgMatch.find()) {
String cardName = cardDmgMatch.group(1).trim();
int amount = Integer.parseInt(cardDmgMatch.group(2));
// Try to find which seat owns this card
for (int s = 0; s < 3; s++) {
if (seatCards[s] != null && seatCards[s].containsKey(cardName)) {
seatCards[s].get(cardName).damageDealt += amount;
break; // attribute to first matching seat
}
}
}
}
// Finalize: compute stuckInHand and attach to PlayerResults
for (int s = 0; s < 3 && s < result.playerResults.size(); s++) {
if (seatCards[s] == null) continue;
List<PerCardGameStats> cardStatsList = new ArrayList<>();
for (PerCardGameStats stats : seatCards[s].values()) {
stats.computeStuckInHand();
cardStatsList.add(stats);
}
result.playerResults.get(s).cardStats = cardStatsList;
}
}
/**
* Classify win condition based on how opponents lost.
*
* Forge loss reasons seen in practice:
* "life total reached 0" → combat_damage or life_drain
* "ran out of cards" or "drew from empty library" → mill
* "received 21+ commander damage" → commander_damage
* "poison counters" → combo_alt_win
* "all opponents have lost" → check individual loss reasons
*/
private String classifyWinCondition(Map<String, String> lossReasons, String fullOutput) {
String combined = String.join(" ", lossReasons.values()).toLowerCase();
String lower = fullOutput.toLowerCase();
if (combined.contains("commander damage") || lower.contains("commander damage")) {
return "commander_damage";
}
if (combined.contains("ran out of cards") || combined.contains("empty library") ||
combined.contains("draw from empty") || lower.contains("milled")) {
return "mill";
}
if (combined.contains("poison") || lower.contains("poison counter")) {
return "combo_alt_win";
}
if (lower.contains("alternate win") || lower.contains("wins the game") ||
lower.contains("won the game")) {
return "combo_alt_win";
}
if (combined.contains("concede") || lower.contains("concede")) {
return "concession";
}
if (lower.contains("clock") || lower.contains("time limit") || lower.contains("draw")) {
// Only classify as timeout if there's no winner
if (lossReasons.isEmpty()) return "timeout";
}
if (combined.contains("life total reached")) {
return "combat_damage"; // Default for life-total kills
}
return "unknown";
}
/**
* Create a placeholder GameResult for a failed/crashed game.
*/
private GameResult createFailedGame(int gameIndex, long gameSeed, long elapsedMs) {
GameResult result = new GameResult();
result.gameIndex = gameIndex;
result.gameSeed = gameSeed;
result.winningSeat = null;
result.totalTurns = 0;
result.winCondition = "timeout";
result.elapsedMs = elapsedMs;
result.playerResults = new ArrayList<>();
for (int i = 0; i < 3; i++) {
PlayerResult pr = new PlayerResult();
pr.seatIndex = i;
pr.finalLife = 40;
pr.mulligans = 0;
pr.isWinner = false;
result.playerResults.add(pr);
}
return result;
}
}
@@ -0,0 +1,95 @@
package commanderailab.batch;
import commanderailab.ai.AiPolicy;
import commanderailab.schema.BatchResult.*;
import java.util.*;
import java.util.concurrent.*;
/**
* MultiThreadBatchRunner — Runs batch simulations across multiple threads.
*
* Each thread gets its own BatchRunner instance and a per-thread RNG seed
* derived from the master seed. Results are merged after all threads complete.
*/
public class MultiThreadBatchRunner {
private final String forgeJarPath;
private final String forgeWorkDir;
private final List<DeckInfo> decks;
private final AiPolicy policy;
private final int numThreads;
private final boolean quiet;
private final int clockSeconds;
private final String javaPath;
public MultiThreadBatchRunner(String forgeJarPath, String forgeWorkDir,
List<DeckInfo> decks, AiPolicy policy, int numThreads) {
this(forgeJarPath, forgeWorkDir, decks, policy, numThreads, true, 120, "java");
}
public MultiThreadBatchRunner(String forgeJarPath, String forgeWorkDir,
List<DeckInfo> decks, AiPolicy policy,
int numThreads, boolean quiet, int clockSeconds) {
this(forgeJarPath, forgeWorkDir, decks, policy, numThreads, quiet, clockSeconds, "java");
}
public MultiThreadBatchRunner(String forgeJarPath, String forgeWorkDir,
List<DeckInfo> decks, AiPolicy policy,
int numThreads, boolean quiet, int clockSeconds, String javaPath) {
this.forgeJarPath = forgeJarPath;
this.forgeWorkDir = forgeWorkDir;
this.decks = decks;
this.policy = policy;
this.numThreads = Math.max(1, numThreads);
this.quiet = quiet;
this.clockSeconds = clockSeconds;
this.javaPath = (javaPath != null && !javaPath.isEmpty()) ? javaPath : "java";
}
/**
* Run totalGames across numThreads workers.
*/
public List<GameResult> runBatch(int totalGames, Long masterSeed) throws InterruptedException, ExecutionException {
int gamesPerThread = totalGames / numThreads;
int remainder = totalGames % numThreads;
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
List<Future<List<GameResult>>> futures = new ArrayList<>();
int gameOffset = 0;
for (int t = 0; t < numThreads; t++) {
int chunkSize = gamesPerThread + (t < remainder ? 1 : 0);
Long threadSeed = (masterSeed != null) ? masterSeed + (long) gameOffset * 1000L : null;
int startIndex = gameOffset;
BatchRunner runner = new BatchRunner(forgeJarPath, forgeWorkDir, decks, policy, quiet, clockSeconds, javaPath);
futures.add(executor.submit(() -> {
List<GameResult> results = runner.runBatchSingleThread(chunkSize, threadSeed);
for (int i = 0; i < results.size(); i++) {
results.get(i).gameIndex = startIndex + i;
}
return results;
}));
gameOffset += chunkSize;
}
List<List<GameResult>> allResults = new ArrayList<>();
for (Future<List<GameResult>> future : futures) {
allResults.add(future.get());
}
executor.shutdown();
executor.awaitTermination(2, TimeUnit.HOURS);
List<GameResult> merged = new ArrayList<>();
for (List<GameResult> batch : allResults) {
merged.addAll(batch);
}
merged.sort(Comparator.comparingInt(g -> g.gameIndex));
return merged;
}
}
@@ -0,0 +1,159 @@
package commanderailab.bridge;
import commanderailab.schema.BatchResult;
import commanderailab.schema.BatchResult.*;
import commanderailab.schema.JsonExporter;
import commanderailab.stats.StatsAggregator;
import commanderailab.ai.AiPolicy;
import commanderailab.ai.ForgeBuiltinPolicy;
import commanderailab.batch.BatchRunner;
import commanderailab.batch.MultiThreadBatchRunner;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.time.Instant;
import java.util.*;
/**
* WebApiBridge — HTTP/WebSocket API layer for the web UI.
*
* This class provides methods that can be called from a web server
* (e.g., Javalin, Spring, or the existing Python FastAPI server)
* to trigger batch runs and retrieve results.
*/
public class WebApiBridge {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private final String forgeJarPath;
private final String forgeWorkDir;
private volatile BatchResult lastResult;
private volatile boolean isRunning;
private volatile int progress;
private String policyServerUrl = "http://localhost:8080";
public WebApiBridge(String forgeJarPath, String forgeWorkDir) {
this.forgeJarPath = forgeJarPath;
this.forgeWorkDir = forgeWorkDir;
this.isRunning = false;
this.progress = 0;
}
/**
* Start a batch run (backward-compatible, Forge AI only).
*/
public String startBatchAsync(String deck1, String deck2, String deck3,
int numGames, int threads, Long seed) {
return startBatchAsync(deck1, deck2, deck3, numGames, threads, seed, false, "midrange");
}
/**
* Start a batch with learned policy support.
*
* @param useLearnedPolicy If true, attempts to use the trained neural network policy
* @param policyStyle Playstyle for the learned policy ("aggro", "control", "midrange", "combo")
*/
public String startBatchAsync(String deck1, String deck2, String deck3,
int numGames, int threads, Long seed,
boolean useLearnedPolicy, String policyStyle) {
String batchId = UUID.randomUUID().toString();
Thread batchThread = new Thread(() -> {
try {
isRunning = true;
progress = 0;
List<DeckInfo> decks = buildDecks(deck1, deck2, deck3);
AiPolicy policy;
if (useLearnedPolicy) {
commanderailab.ml.LearnedPolicy learned =
new commanderailab.ml.LearnedPolicy(
policyServerUrl,
policyStyle != null ? policyStyle : "midrange",
true
);
if (learned.connect()) {
policy = learned;
System.out.println("[ML] Using learned policy for batch " + batchId);
} else {
System.out.println("[ML] Learned policy unavailable, using Forge AI");
policy = new ForgeBuiltinPolicy();
}
} else {
policy = new ForgeBuiltinPolicy();
}
long startTime = System.currentTimeMillis();
List<GameResult> games;
if (threads > 1) {
MultiThreadBatchRunner runner = new MultiThreadBatchRunner(
forgeJarPath, forgeWorkDir, decks, policy, threads);
games = runner.runBatch(numGames, seed);
} else {
BatchRunner runner = new BatchRunner(
forgeJarPath, forgeWorkDir, decks, policy);
games = runner.runBatchSingleThread(numGames, seed);
}
long elapsed = System.currentTimeMillis() - startTime;
Summary summary = StatsAggregator.computeSummary(games, decks, elapsed);
BatchResult result = new BatchResult();
result.metadata = new Metadata();
result.metadata.batchId = batchId;
result.metadata.timestamp = Instant.now().toString();
result.metadata.totalGames = numGames;
result.metadata.completedGames = games.size();
result.metadata.engineVersion = "forge-2.0.12-SNAPSHOT";
result.metadata.masterSeed = seed;
result.metadata.threads = threads;
result.metadata.elapsedMs = elapsed;
result.decks = decks;
result.games = games;
result.summary = summary;
lastResult = result;
progress = 100;
} catch (Exception e) {
System.err.println("Batch run failed: " + e.getMessage());
e.printStackTrace();
} finally {
isRunning = false;
}
}, "batch-runner-" + batchId);
batchThread.setDaemon(true);
batchThread.start();
return batchId;
}
public int getProgress() { return progress; }
public boolean isRunning() { return isRunning; }
public String getLastResultJson() {
if (lastResult == null) return "{}";
return JsonExporter.toJson(lastResult);
}
public BatchResult getLastResult() { return lastResult; }
private List<DeckInfo> buildDecks(String... deckNames) {
List<DeckInfo> decks = new ArrayList<>();
for (int i = 0; i < deckNames.length; i++) {
DeckInfo d = new DeckInfo();
d.seatIndex = i;
d.deckFile = deckNames[i];
d.deckName = deckNames[i].replace(".dck", "");
d.commanderName = d.deckName;
d.colorIdentity = List.of();
d.cardCount = 100;
decks.add(d);
}
return decks;
}
}
@@ -0,0 +1,619 @@
package commanderailab.cli;
import commanderailab.ai.*;
import commanderailab.analytics.DeckAnalyzer;
import commanderailab.analytics.DeckAnalyzer.DeckAnalysis;
import commanderailab.batch.*;
import commanderailab.db.LabDatabase;
import commanderailab.meta.*;
import commanderailab.meta.DeckProfile.DeckSource;
import commanderailab.schema.*;
import commanderailab.schema.BatchResult.*;
import commanderailab.stats.StatsAggregator;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import java.io.File;
import java.nio.file.*;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.Callable;
/**
* LabCli — Command-line entry point for Commander AI Lab v3.
*
* v3 adds:
* --import-url Import deck from URL (Archidekt, EDHREC)
* --import-text Import deck from text file (card list)
* --commander-meta Use EDHREC average deck for a commander name
* --meta-file Custom commander→meta mapping JSON
* --import-to Directory to save imported .dck files
*/
@Command(
name = "commander-ai-lab",
mixinStandardHelpOptions = true,
version = "Commander AI Lab v3.0.0",
description = "Headless batch simulation for 3-AI MTG Commander pods with deck import & meta lookup."
)
public class LabCli implements Callable<Integer> {
@Option(names = {"--forge-jar", "-F"}, required = true,
description = "Path to Forge desktop JAR (forge-gui-desktop-XXX-jar-with-dependencies.jar)")
private String forgeJarPath;
@Option(names = {"--forge-dir", "-W"}, required = true,
description = "Working directory for Forge (folder containing res/ — usually forge-gui/)")
private String forgeWorkDir;
@Option(names = {"--deck1", "-d1"}, defaultValue = "",
description = "Commander deck name for seat 0 (as it appears in Forge's deck list)")
private String deck1;
@Option(names = {"--deck2", "-d2"}, defaultValue = "",
description = "Commander deck name for seat 1")
private String deck2;
@Option(names = {"--deck3", "-d3"}, defaultValue = "",
description = "Commander deck name for seat 2")
private String deck3;
@Option(names = {"--commander1", "-c1"}, defaultValue = "",
description = "Commander card name for seat 0 (for display; uses deck name if blank)")
private String commander1;
@Option(names = {"--commander2", "-c2"}, defaultValue = "",
description = "Commander card name for seat 1")
private String commander2;
@Option(names = {"--commander3", "-c3"}, defaultValue = "",
description = "Commander card name for seat 2")
private String commander3;
@Option(names = {"--games", "-n"}, defaultValue = "10",
description = "Number of games to simulate (default: 10)")
private int numGames;
@Option(names = {"--threads", "-t"}, defaultValue = "1",
description = "Number of parallel threads (default: 1)")
private int threads;
@Option(names = {"--seed", "-s"}, defaultValue = "",
description = "Master RNG seed for reproducibility (blank for random)")
private String seed;
@Option(names = {"--output", "-o"}, defaultValue = "results/batch-latest.json",
description = "Output JSON file path")
private String outputPath;
@Option(names = {"--clock", "-c"}, defaultValue = "120",
description = "Max seconds per game before draw (default: 120)")
private int clockSeconds;
@Option(names = {"--verbose", "-v"}, defaultValue = "false",
description = "Show full Forge output (not just parsed results)")
private boolean verbose;
// ── v2 Options ──────────────────────────────────────────────
@Option(names = {"--profile", "-p"}, defaultValue = "default",
description = "AI behavior profile: default, aggro, control, combo, midrange")
private String profileName;
@Option(names = {"--analyze"}, defaultValue = "false",
description = "Run deck analysis before batch (shows mana curve, roles, health checks)")
private boolean analyzeDeck;
@Option(names = {"--db"}, defaultValue = "lab.db",
description = "SQLite database file for result persistence (default: lab.db)")
private String dbPath;
@Option(names = {"--no-db"}, defaultValue = "false",
description = "Disable SQLite persistence (results only saved to JSON file)")
private boolean noDb;
@Option(names = {"--decks-dir"}, defaultValue = "",
description = "Path to Commander decks folder (for --analyze, default: %%APPDATA%%/Forge/decks/commander)")
private String decksDir;
// ── v3 Options — Deck Import & Meta ─────────────────────────
@Option(names = {"--import-url"},
description = "Import deck from URL (Archidekt, EDHREC). Can specify 1-3 times for each seat.")
private List<String> importUrls;
@Option(names = {"--import-text"},
description = "Import deck from text file (card list). Can specify 1-3 times for each seat.")
private List<String> importTextFiles;
@Option(names = {"--commander-meta"},
description = "Fetch EDHREC average deck by commander name. Can specify 1-3 times for each seat.")
private List<String> commanderMeta;
@Option(names = {"--meta-file"}, defaultValue = "commander-meta.json",
description = "Path to commander→meta deck mapping JSON (default: commander-meta.json)")
private String metaFile;
@Option(names = {"--import-to"}, defaultValue = "",
description = "Directory to save imported .dck files (default: Forge decks/commander dir)")
private String importTo;
@Option(names = {"--list-meta"}, defaultValue = "false",
description = "List available commanders in the meta mapping and exit")
private boolean listMeta;
// ── v4 Options — ML Decision Logging ─────────────────────────
@Option(names = {"--ml-log"}, defaultValue = "false",
description = "Enable ML decision logging: extract state+action snapshots for RL training")
private boolean mlLog;
// ── v5 Options — Learned Policy ─────────────────────────────
@Option(names = {"--learned-policy"}, defaultValue = "false",
description = "Use trained neural network policy (requires running lab API server with model loaded)")
private boolean useLearnedPolicy;
@Option(names = {"--policy-server"}, defaultValue = "http://localhost:8080",
description = "Policy server URL (default: http://localhost:8080)")
private String policyServerUrl;
@Option(names = {"--policy-style"}, defaultValue = "midrange",
description = "Playstyle hint for learned policy: aggro, control, midrange, combo")
private String policyStyle;
@Option(names = {"--policy-greedy"}, defaultValue = "true",
description = "Use greedy (argmax) action selection for learned policy (default: true)")
private boolean policyGreedy;
@Option(names = {"--java17"}, defaultValue = "",
description = "Path to Java 17 executable for running Forge (Forge requires Java 17, not 25+)")
private String java17Path;
@Override
public Integer call() throws Exception {
System.out.println("╔══════════════════════════════════════════════════╗");
System.out.println("║ Commander AI Lab v3.0.0 ║");
System.out.println("║ 3-AI Headless Batch Sim + Deck Import/Meta ║");
System.out.println("╚══════════════════════════════════════════════════╝");
System.out.println();
// Load meta mapping
CommanderMetaService.loadMapping(metaFile);
// Handle --list-meta
if (listMeta) {
printMetaList();
return 0;
}
// Validate Forge paths
if (!new File(forgeJarPath).exists()) {
System.err.println("ERROR: Forge JAR not found: " + forgeJarPath);
return 1;
}
if (!new File(forgeWorkDir).isDirectory()) {
System.err.println("ERROR: Forge work directory not found: " + forgeWorkDir);
return 1;
}
// Resolve import-to directory
String importDir = resolveImportDir();
// Build deck info (with possible imports)
List<DeckInfo> decks = buildDeckInfoList(importDir);
if (decks == null) return 1; // Error already printed
System.out.printf("Pod: %s vs %s vs %s%n",
decks.get(0).deckName, decks.get(1).deckName, decks.get(2).deckName);
for (DeckInfo d : decks) {
if (d.source != null && !d.source.isEmpty()) {
System.out.printf(" Seat %d: %s → %s (%s)%n",
d.seatIndex, d.commanderName, d.source, d.sourceUrl != null ? d.sourceUrl : "");
}
}
System.out.printf("Games: %d%n", numGames);
System.out.printf("Threads: %d%n", threads);
System.out.printf("Clock: %ds per game%n", clockSeconds);
Long masterSeed = seed.isEmpty() ? null : Long.parseLong(seed);
if (masterSeed != null) {
System.out.printf("Seed: %d%n", masterSeed);
}
System.out.println();
// Choose AI policy and profile
AiProfile profile = AiProfile.byName(profileName);
AiPolicy policy;
if (useLearnedPolicy) {
commanderailab.ml.LearnedPolicy learned =
new commanderailab.ml.LearnedPolicy(policyServerUrl, policyStyle, policyGreedy);
if (learned.connect()) {
policy = learned;
System.out.printf("AI Policy: learned-policy (server=%s, style=%s, greedy=%s)%n",
policyServerUrl, policyStyle, policyGreedy);
} else {
System.out.println("[ML] Learned policy unavailable — falling back to Forge built-in AI");
policy = new ForgeBuiltinPolicy();
}
} else {
policy = new ForgeBuiltinPolicy();
}
System.out.printf("AI Policy: %s%n", policy.getName());
System.out.printf("AI Profile: %s — %s%n", profile.getName(), profile.getDescription());
System.out.printf("Engine: Forge sim (headless)%n");
System.out.println();
// v2: Deck analysis (if requested)
if (analyzeDeck) {
String resolvedDecksDir = decksDir.isEmpty() ? resolveForgeDecksDir() : decksDir;
if (resolvedDecksDir != null && !resolvedDecksDir.isEmpty()) {
System.out.println("═══ DECK ANALYSIS ═══");
for (DeckInfo deck : decks) {
try {
DeckAnalysis analysis = DeckAnalyzer.analyzeFromForge(resolvedDecksDir, deck.deckName);
DeckAnalyzer.printSummary(analysis);
System.out.println();
} catch (Exception e) {
System.out.printf(" [WARN] Could not analyze %s: %s%n", deck.deckName, e.getMessage());
}
}
} else {
System.out.println(" [WARN] --decks-dir not set and auto-detect failed. Skipping deck analysis.");
}
}
// Run simulations
long startTime = System.currentTimeMillis();
List<GameResult> games;
// Always run verbose (quiet=false) to capture combat stats from Forge game log.
// The --verbose flag now controls whether full output is echoed to console,
// but the parser always gets the full log for stat extraction.
boolean quietMode = false; // Never quiet — we need verbose output for combat stats
// Resolve Java 17 path for Forge subprocess
String resolvedJava = resolveJava17Path();
System.out.printf("Java: %s%n%n", resolvedJava);
if (threads > 1) {
System.out.printf("Running %d games across %d threads...%n%n", numGames, threads);
MultiThreadBatchRunner mtRunner = new MultiThreadBatchRunner(
forgeJarPath, forgeWorkDir, decks, policy, threads, quietMode, clockSeconds, resolvedJava);
games = mtRunner.runBatch(numGames, masterSeed);
} else {
System.out.printf("Running %d games (single thread)...%n%n", numGames);
BatchRunner runner = new BatchRunner(
forgeJarPath, forgeWorkDir, decks, policy, quietMode, clockSeconds, resolvedJava);
// v4: Enable ML decision logging if requested
if (mlLog) {
String batchId = UUID.randomUUID().toString().substring(0, 8);
runner.enableMlLogging("results", batchId);
System.out.println("[ML] Decision logging enabled — data will be saved to results/");
}
games = runner.runBatchSingleThread(numGames, masterSeed);
// Close ML logger
if (mlLog) {
runner.closeMlLogger();
}
}
long elapsedMs = System.currentTimeMillis() - startTime;
// Compute stats
Summary summary = StatsAggregator.computeSummary(games, decks, elapsedMs);
// Build full BatchResult
BatchResult result = new BatchResult();
result.metadata = new Metadata();
result.metadata.batchId = UUID.randomUUID().toString();
result.metadata.timestamp = Instant.now().toString();
result.metadata.totalGames = numGames;
result.metadata.completedGames = games.size();
result.metadata.engineVersion = "forge-2.0.12-SNAPSHOT";
result.metadata.masterSeed = masterSeed;
result.metadata.threads = threads;
result.metadata.elapsedMs = elapsedMs;
result.decks = decks;
result.games = games;
result.summary = summary;
// Export JSON
JsonExporter.writeToFile(result, outputPath);
System.out.println();
// Print summary to console
printSummary(result);
// Validate output
String json = JsonExporter.toJson(result);
boolean valid = JsonExporter.validateBasicStructure(json);
System.out.printf("%nJSON validation: %s%n", valid ? "PASSED" : "FAILED");
System.out.printf("Output written to: %s%n", outputPath);
// v2: Save to SQLite
if (!noDb) {
try (LabDatabase db = new LabDatabase(dbPath)) {
db.saveBatchResult(result);
System.out.printf("Saved to database: %s%n", dbPath);
// Also save deck analyses if we ran them
if (analyzeDeck) {
String resolvedDecksDir = decksDir.isEmpty() ? resolveForgeDecksDir() : decksDir;
if (resolvedDecksDir != null) {
for (DeckInfo deck : decks) {
try {
DeckAnalysis analysis = DeckAnalyzer.analyzeFromForge(resolvedDecksDir, deck.deckName);
db.saveDeckAnalysis(analysis);
} catch (Exception ignore) { }
}
}
}
// Print global stats
var globalStats = db.getGlobalStats();
System.out.printf("%n═══ LIFETIME STATS ═══%n");
System.out.printf(" Total Batches: %s | Total Games: %s | Unique Decks: %s%n",
globalStats.get("totalBatches"),
globalStats.get("totalGames"),
globalStats.get("uniqueDecks"));
} catch (Exception e) {
System.err.printf("WARNING: Database save failed: %s%n", e.getMessage());
}
}
return 0;
}
// ══════════════════════════════════════════════════════════
// Deck Info Construction (v3 — supports import)
// ══════════════════════════════════════════════════════════
private List<DeckInfo> buildDeckInfoList(String importDir) throws Exception {
String[] deckNames = {deck1, deck2, deck3};
String[] commanders = {commander1, commander2, commander3};
// Build import lists for each seat
DeckProfile[] imports = new DeckProfile[3];
// Process --commander-meta flags
if (commanderMeta != null) {
for (int i = 0; i < Math.min(commanderMeta.size(), 3); i++) {
String cmdrName = commanderMeta.get(i);
System.out.printf("═══ IMPORT SEAT %d: Commander Meta — %s ═══%n", i, cmdrName);
imports[i] = DeckImporter.importFromEdhrec(cmdrName);
}
}
// Process --import-url flags (overrides commander-meta for same seat)
if (importUrls != null) {
for (int i = 0; i < Math.min(importUrls.size(), 3); i++) {
if (imports[i] != null) continue; // Don't override if already set
String url = importUrls.get(i);
int seat = findNextEmptySeat(imports);
if (seat < 0) break;
System.out.printf("═══ IMPORT SEAT %d: URL — %s ═══%n", seat, url);
imports[seat] = DeckImporter.importFromUrl(url);
}
}
// Process --import-text flags
if (importTextFiles != null) {
for (int i = 0; i < Math.min(importTextFiles.size(), 3); i++) {
String filePath = importTextFiles.get(i);
int seat = findNextEmptySeat(imports);
if (seat < 0) break;
System.out.printf("═══ IMPORT SEAT %d: Text File — %s ═══%n", seat, filePath);
String text = Files.readString(Path.of(filePath));
imports[seat] = DeckImporter.importFromText(text, null);
}
}
// Save imported decks to .dck files and set deck names
for (int i = 0; i < 3; i++) {
if (imports[i] != null) {
DeckProfile profile = imports[i];
Path dckPath = DeckImporter.saveToDckFile(profile, importDir);
String savedName = dckPath.getFileName().toString().replace(".dck", "");
deckNames[i] = savedName;
if (profile.commander != null) {
commanders[i] = profile.commander;
}
System.out.printf(" Seat %d → saved as %s%n", i, dckPath);
System.out.println();
}
}
// Validate all 3 seats have decks
for (int i = 0; i < 3; i++) {
if (deckNames[i] == null || deckNames[i].isEmpty()) {
System.err.printf("ERROR: Seat %d has no deck. Use --deck%d, --import-url, --import-text, or --commander-meta.%n", i, i + 1);
return null;
}
}
// Build DeckInfo list
List<DeckInfo> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
DeckInfo d = new DeckInfo();
d.seatIndex = i;
d.deckFile = deckNames[i];
d.deckName = deckNames[i];
d.commanderName = commanders[i].isEmpty() ? deckNames[i] : commanders[i];
d.colorIdentity = List.of();
d.cardCount = 100;
// v3: Populate source metadata from import
if (imports[i] != null) {
DeckProfile p = imports[i];
d.source = p.source != null ? p.source.label() : null;
d.sourceUrl = p.sourceUrl;
d.archetype = p.archetype;
d.colorIdentity = p.colorIdentity != null ? p.colorIdentity : List.of();
d.cardCount = p.totalCards;
if (p.sampleSize != null) d.sampleSize = p.sampleSize;
d.importedAt = p.importedAt;
}
list.add(d);
}
return list;
}
private int findNextEmptySeat(DeckProfile[] imports) {
for (int i = 0; i < imports.length; i++) {
if (imports[i] == null) return i;
}
return -1;
}
// ══════════════════════════════════════════════════════════
// Helpers
// ══════════════════════════════════════════════════════════
private String resolveImportDir() {
if (!importTo.isEmpty()) return importTo;
// Try Forge decks/commander dir
String decksDir = resolveForgeDecksDir();
if (decksDir != null) return decksDir;
// Fallback to local directory
return "imported-decks";
}
private void printMetaList() {
System.out.println("═══ AVAILABLE COMMANDERS (Meta Mapping) ═══");
System.out.println();
for (String cmdr : CommanderMetaService.getAllCommanders()) {
var entries = CommanderMetaService.getMetaDecks(cmdr);
for (var entry : entries) {
System.out.printf(" %-35s %-20s %s%n",
cmdr,
entry.archetype != null ? entry.archetype : "",
entry.source);
}
}
System.out.printf("%n Total: %d commanders%n", CommanderMetaService.getAllCommanders().size());
System.out.println(" Use --commander-meta \"Commander Name\" to fetch the EDHREC average deck.");
}
private void printSummary(BatchResult result) {
System.out.println("╔══════════════════════════════════════════════════════════╗");
System.out.println("║ BATCH RESULTS ║");
System.out.println("╠══════════════════════════════════════════════════════════╣");
Summary s = result.summary;
for (DeckSummary ds : s.perDeck) {
DeckInfo deckInfo = result.decks.get(ds.seatIndex);
System.out.printf("║ Seat %d: %-40s ║%n", ds.seatIndex, ds.deckName);
if (deckInfo.source != null && !deckInfo.source.isEmpty()) {
System.out.printf("║ Source: %-36s ║%n", deckInfo.source);
}
System.out.printf("║ Win Rate: %5.1f%% (%d W / %d L / %d D)%n",
ds.winRate * 100, ds.wins, ds.losses, ds.draws);
System.out.printf("║ Avg Turns: %5s%n",
ds.avgTurnsToWin != null ? String.format("%.1f", ds.avgTurnsToWin) : "N/A");
System.out.printf("║ Avg Mulligan: %5.2f%n", ds.avgMulligans);
System.out.printf("║ Avg Life: %5.1f%n", ds.avgFinalLife);
if (ds.winConditionBreakdown != null && ds.wins > 0) {
WinConditionBreakdown b = ds.winConditionBreakdown;
System.out.printf("║ Win By: Combat=%d CmdrDmg=%d Combo=%d Drain=%d Mill=%d%n",
b.combat_damage, b.commander_damage, b.combo_alt_win, b.life_drain, b.mill);
}
System.out.println("║");
}
System.out.println("╠══════════════════════════════════════════════════════════╣");
System.out.printf("║ Games: %-5d Avg Turns: %-6.1f Sims/sec: %-6.2f%n",
result.metadata.completedGames, s.avgGameTurns, s.simsPerSecond);
System.out.printf("║ Wall Time: %.1fs%n", result.metadata.elapsedMs / 1000.0);
System.out.println("╚══════════════════════════════════════════════════════════╝");
}
public static void main(String[] args) {
int exitCode = new CommandLine(new LabCli()).execute(args);
System.exit(exitCode);
}
/**
* Resolve the Java 17 executable path for running Forge subprocesses.
* Forge requires Java 17 — newer versions (25+) cause ExceptionInInitializerError.
*
* Priority: --java17 flag > auto-detect Adoptium > auto-detect Oracle > system "java"
*/
private String resolveJava17Path() {
// 1. Explicit --java17 flag
if (java17Path != null && !java17Path.isEmpty()) {
File f = new File(java17Path);
if (f.exists()) return f.getAbsolutePath();
System.err.println("WARNING: --java17 path not found: " + java17Path);
}
// 2. Auto-detect common Java 17 locations on Windows
String[] candidates = {
"C:\\Program Files\\Eclipse Adoptium\\jdk-17.0.18.8-hotspot\\bin\\java.exe",
"C:\\Program Files\\Java\\jdk-17\\bin\\java.exe",
"C:\\Program Files\\Eclipse Adoptium\\jdk-17\\bin\\java.exe",
};
// Also scan for any jdk-17* in Adoptium and Java dirs
String[] searchDirs = {
"C:\\Program Files\\Eclipse Adoptium",
"C:\\Program Files\\Java",
};
for (String dir : searchDirs) {
File d = new File(dir);
if (d.isDirectory()) {
File[] children = d.listFiles();
if (children != null) {
for (File child : children) {
if (child.isDirectory() && child.getName().startsWith("jdk-17")) {
File java = new File(child, "bin/java.exe");
if (java.exists()) return java.getAbsolutePath();
// Linux/Mac
java = new File(child, "bin/java");
if (java.exists()) return java.getAbsolutePath();
}
}
}
}
}
// 3. Check explicit candidate paths
for (String path : candidates) {
File f = new File(path);
if (f.exists()) return f.getAbsolutePath();
}
// 4. Fallback to system java (may be wrong version)
System.err.println("WARNING: Java 17 not found. Forge may crash on Java 25+.");
System.err.println(" Install Adoptium JDK 17 or use --java17 <path>");
return "java";
}
/**
* Auto-detect Forge Commander decks directory.
*/
private String resolveForgeDecksDir() {
// Windows: %APPDATA%\Forge\decks\commander
String appdata = System.getenv("APPDATA");
if (appdata != null) {
File candidate = new File(appdata, "Forge/decks/commander");
if (candidate.isDirectory()) return candidate.getAbsolutePath();
}
// Linux/Mac
String home = System.getProperty("user.home");
for (String path : new String[]{"/.forge/decks/commander", "/Forge/decks/commander"}) {
File candidate = new File(home + path);
if (candidate.isDirectory()) return candidate.getAbsolutePath();
}
return null;
}
}
@@ -0,0 +1,478 @@
package commanderailab.db;
import commanderailab.schema.BatchResult;
import commanderailab.schema.BatchResult.*;
import commanderailab.schema.JsonExporter;
import commanderailab.analytics.DeckAnalyzer.DeckAnalysis;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.*;
import java.sql.*;
import java.time.Instant;
import java.util.*;
/**
* LabDatabase — SQLite persistence for Commander AI Lab.
*
* Stores:
* - Batch run metadata and results (full JSON + indexed columns)
* - Per-deck win rate history for trend tracking
* - Deck analysis snapshots
* - Matchup matrix data (deck A vs B vs C win rates)
*
* Schema auto-creates on first use. All operations are thread-safe
* via synchronized methods (SQLite doesn't handle concurrent writes well).
*/
public class LabDatabase implements AutoCloseable {
private static final String SCHEMA_VERSION = "2.0.0";
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private final Connection conn;
// ══════════════════════════════════════════════════════════
// Construction & Schema
// ══════════════════════════════════════════════════════════
public LabDatabase(String dbPath) throws SQLException {
this.conn = DriverManager.getConnection("jdbc:sqlite:" + dbPath);
conn.setAutoCommit(true);
// Enable WAL for better concurrent read performance
try (Statement s = conn.createStatement()) {
s.execute("PRAGMA journal_mode=WAL");
s.execute("PRAGMA foreign_keys=ON");
}
createSchema();
}
private void createSchema() throws SQLException {
try (Statement s = conn.createStatement()) {
// ── Batch Runs ─────────────────────────────────────
s.execute("""
CREATE TABLE IF NOT EXISTS batch_runs (
batch_id TEXT PRIMARY KEY,
timestamp TEXT NOT NULL,
total_games INTEGER NOT NULL,
completed_games INTEGER NOT NULL,
threads INTEGER DEFAULT 1,
elapsed_ms INTEGER NOT NULL,
master_seed INTEGER,
engine_version TEXT,
sims_per_sec REAL,
avg_game_turns REAL,
result_json TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now'))
)
""");
// ── Per-Deck Results (indexed for queries) ─────────
s.execute("""
CREATE TABLE IF NOT EXISTS deck_results (
id INTEGER PRIMARY KEY AUTOINCREMENT,
batch_id TEXT NOT NULL REFERENCES batch_runs(batch_id),
seat_index INTEGER NOT NULL,
deck_name TEXT NOT NULL,
commander_name TEXT,
wins INTEGER NOT NULL,
losses INTEGER NOT NULL,
draws INTEGER NOT NULL,
win_rate REAL NOT NULL,
avg_turns_to_win REAL,
avg_mulligans REAL,
avg_final_life REAL,
timestamp TEXT NOT NULL,
source TEXT,
source_url TEXT,
archetype TEXT
)
""");
// ── Matchup Data (3-deck pods) ─────────────────────
s.execute("""
CREATE TABLE IF NOT EXISTS matchups (
id INTEGER PRIMARY KEY AUTOINCREMENT,
batch_id TEXT NOT NULL REFERENCES batch_runs(batch_id),
deck_a TEXT NOT NULL,
deck_b TEXT NOT NULL,
deck_c TEXT NOT NULL,
deck_a_wins INTEGER NOT NULL,
deck_b_wins INTEGER NOT NULL,
deck_c_wins INTEGER NOT NULL,
total_games INTEGER NOT NULL,
timestamp TEXT NOT NULL
)
""");
// ── Deck Analysis Snapshots ────────────────────────
s.execute("""
CREATE TABLE IF NOT EXISTS deck_analyses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
deck_name TEXT NOT NULL,
commander_name TEXT,
total_cards INTEGER,
lands INTEGER,
creatures INTEGER,
ramp_cards INTEGER,
removal_cards INTEGER,
draw_cards INTEGER,
board_wipes INTEGER,
analysis_json TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now'))
)
""");
// ── Indexes ────────────────────────────────────────
s.execute("CREATE INDEX IF NOT EXISTS idx_deck_results_name ON deck_results(deck_name)");
s.execute("CREATE INDEX IF NOT EXISTS idx_deck_results_batch ON deck_results(batch_id)");
s.execute("CREATE INDEX IF NOT EXISTS idx_matchups_decks ON matchups(deck_a, deck_b, deck_c)");
s.execute("CREATE INDEX IF NOT EXISTS idx_batch_runs_timestamp ON batch_runs(timestamp)");
// ── Meta ───────────────────────────────────────────
s.execute("""
CREATE TABLE IF NOT EXISTS lab_meta (
key TEXT PRIMARY KEY,
value TEXT
)
""");
s.execute("INSERT OR REPLACE INTO lab_meta(key, value) VALUES('schema_version', '" + SCHEMA_VERSION + "')");
}
}
// ══════════════════════════════════════════════════════════
// Batch Run Storage
// ══════════════════════════════════════════════════════════
/**
* Store a complete batch result.
*/
public synchronized void saveBatchResult(BatchResult result) throws SQLException {
String json = JsonExporter.toJson(result);
Metadata m = result.metadata;
// Insert batch run
try (PreparedStatement ps = conn.prepareStatement("""
INSERT OR REPLACE INTO batch_runs
(batch_id, timestamp, total_games, completed_games, threads, elapsed_ms,
master_seed, engine_version, sims_per_sec, avg_game_turns, result_json)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""")) {
ps.setString(1, m.batchId);
ps.setString(2, m.timestamp);
ps.setInt(3, m.totalGames);
ps.setInt(4, m.completedGames);
ps.setInt(5, m.threads);
ps.setLong(6, m.elapsedMs);
if (m.masterSeed != null) ps.setLong(7, m.masterSeed);
else ps.setNull(7, Types.INTEGER);
ps.setString(8, m.engineVersion);
ps.setDouble(9, result.summary.simsPerSecond);
ps.setDouble(10, result.summary.avgGameTurns);
ps.setString(11, json);
ps.executeUpdate();
}
// Insert per-deck results
try (PreparedStatement ps = conn.prepareStatement("""
INSERT INTO deck_results
(batch_id, seat_index, deck_name, commander_name, wins, losses, draws,
win_rate, avg_turns_to_win, avg_mulligans, avg_final_life, timestamp,
source, source_url, archetype)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""")) {
for (DeckSummary ds : result.summary.perDeck) {
DeckInfo deck = result.decks.get(ds.seatIndex);
ps.setString(1, m.batchId);
ps.setInt(2, ds.seatIndex);
ps.setString(3, ds.deckName);
ps.setString(4, deck.commanderName);
ps.setInt(5, ds.wins);
ps.setInt(6, ds.losses);
ps.setInt(7, ds.draws);
ps.setDouble(8, ds.winRate);
if (ds.avgTurnsToWin != null) ps.setDouble(9, ds.avgTurnsToWin);
else ps.setNull(9, Types.REAL);
ps.setDouble(10, ds.avgMulligans);
ps.setDouble(11, ds.avgFinalLife);
ps.setString(12, m.timestamp);
ps.setString(13, deck.source);
ps.setString(14, deck.sourceUrl);
ps.setString(15, deck.archetype);
ps.addBatch();
}
ps.executeBatch();
}
// Insert matchup data
if (result.decks.size() == 3 && result.summary.perDeck.size() == 3) {
try (PreparedStatement ps = conn.prepareStatement("""
INSERT INTO matchups
(batch_id, deck_a, deck_b, deck_c, deck_a_wins, deck_b_wins, deck_c_wins, total_games, timestamp)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""")) {
ps.setString(1, m.batchId);
ps.setString(2, result.decks.get(0).deckName);
ps.setString(3, result.decks.get(1).deckName);
ps.setString(4, result.decks.get(2).deckName);
ps.setInt(5, result.summary.perDeck.get(0).wins);
ps.setInt(6, result.summary.perDeck.get(1).wins);
ps.setInt(7, result.summary.perDeck.get(2).wins);
ps.setInt(8, m.completedGames);
ps.setString(9, m.timestamp);
ps.executeUpdate();
}
}
}
// ══════════════════════════════════════════════════════════
// Queries
// ══════════════════════════════════════════════════════════
/**
* Get win rate history for a deck across all batches.
*/
public List<Map<String, Object>> getDeckWinRateHistory(String deckName) throws SQLException {
List<Map<String, Object>> history = new ArrayList<>();
try (PreparedStatement ps = conn.prepareStatement("""
SELECT batch_id, timestamp, wins, losses, draws, win_rate,
avg_turns_to_win, avg_mulligans, avg_final_life
FROM deck_results
WHERE deck_name = ?
ORDER BY timestamp ASC
""")) {
ps.setString(1, deckName);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Map<String, Object> row = new LinkedHashMap<>();
row.put("batchId", rs.getString("batch_id"));
row.put("timestamp", rs.getString("timestamp"));
row.put("wins", rs.getInt("wins"));
row.put("losses", rs.getInt("losses"));
row.put("draws", rs.getInt("draws"));
row.put("winRate", rs.getDouble("win_rate"));
row.put("avgTurnsToWin", rs.getObject("avg_turns_to_win"));
row.put("avgMulligans", rs.getDouble("avg_mulligans"));
row.put("avgFinalLife", rs.getDouble("avg_final_life"));
history.add(row);
}
}
return history;
}
/**
* Get overall stats for a deck (aggregated across all batches).
*/
public Map<String, Object> getDeckOverallStats(String deckName) throws SQLException {
Map<String, Object> stats = new LinkedHashMap<>();
try (PreparedStatement ps = conn.prepareStatement("""
SELECT
COUNT(*) as batch_count,
SUM(wins) as total_wins,
SUM(losses) as total_losses,
SUM(draws) as total_draws,
AVG(win_rate) as avg_win_rate,
MIN(win_rate) as min_win_rate,
MAX(win_rate) as max_win_rate,
AVG(avg_turns_to_win) as avg_turns,
AVG(avg_mulligans) as avg_mulligans
FROM deck_results WHERE deck_name = ?
""")) {
ps.setString(1, deckName);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
stats.put("deckName", deckName);
stats.put("batchCount", rs.getInt("batch_count"));
stats.put("totalWins", rs.getInt("total_wins"));
stats.put("totalLosses", rs.getInt("total_losses"));
stats.put("totalDraws", rs.getInt("total_draws"));
stats.put("avgWinRate", rs.getDouble("avg_win_rate"));
stats.put("minWinRate", rs.getDouble("min_win_rate"));
stats.put("maxWinRate", rs.getDouble("max_win_rate"));
stats.put("avgTurns", rs.getObject("avg_turns"));
stats.put("avgMulligans", rs.getDouble("avg_mulligans"));
}
}
return stats;
}
/**
* Get all unique deck names that have been tested.
*/
public List<String> getAllTestedDecks() throws SQLException {
List<String> decks = new ArrayList<>();
try (Statement s = conn.createStatement();
ResultSet rs = s.executeQuery(
"SELECT DISTINCT deck_name FROM deck_results ORDER BY deck_name")) {
while (rs.next()) {
decks.add(rs.getString("deck_name"));
}
}
return decks;
}
/**
* Get recent batch runs (most recent first).
*/
public List<Map<String, Object>> getRecentBatches(int limit) throws SQLException {
List<Map<String, Object>> batches = new ArrayList<>();
try (PreparedStatement ps = conn.prepareStatement("""
SELECT batch_id, timestamp, total_games, completed_games, threads,
elapsed_ms, sims_per_sec, avg_game_turns
FROM batch_runs ORDER BY timestamp DESC LIMIT ?
""")) {
ps.setInt(1, limit);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Map<String, Object> row = new LinkedHashMap<>();
row.put("batchId", rs.getString("batch_id"));
row.put("timestamp", rs.getString("timestamp"));
row.put("totalGames", rs.getInt("total_games"));
row.put("completedGames", rs.getInt("completed_games"));
row.put("threads", rs.getInt("threads"));
row.put("elapsedMs", rs.getLong("elapsed_ms"));
row.put("simsPerSec", rs.getDouble("sims_per_sec"));
row.put("avgGameTurns", rs.getDouble("avg_game_turns"));
batches.add(row);
}
}
return batches;
}
/**
* Get full batch result JSON by batchId.
*/
public String getBatchResultJson(String batchId) throws SQLException {
try (PreparedStatement ps = conn.prepareStatement(
"SELECT result_json FROM batch_runs WHERE batch_id = ?")) {
ps.setString(1, batchId);
ResultSet rs = ps.executeQuery();
if (rs.next()) return rs.getString("result_json");
}
return null;
}
/**
* Get matchup win rates for a specific 3-deck pod.
*/
public Map<String, Object> getMatchupStats(String deckA, String deckB, String deckC) throws SQLException {
Map<String, Object> stats = new LinkedHashMap<>();
try (PreparedStatement ps = conn.prepareStatement("""
SELECT
COUNT(*) as match_count,
SUM(total_games) as total_games,
SUM(deck_a_wins) as a_wins,
SUM(deck_b_wins) as b_wins,
SUM(deck_c_wins) as c_wins
FROM matchups
WHERE deck_a = ? AND deck_b = ? AND deck_c = ?
""")) {
ps.setString(1, deckA);
ps.setString(2, deckB);
ps.setString(3, deckC);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
int totalGames = rs.getInt("total_games");
stats.put("matchCount", rs.getInt("match_count"));
stats.put("totalGames", totalGames);
stats.put("deckAWins", rs.getInt("a_wins"));
stats.put("deckBWins", rs.getInt("b_wins"));
stats.put("deckCWins", rs.getInt("c_wins"));
if (totalGames > 0) {
stats.put("deckAWinRate", (double) rs.getInt("a_wins") / totalGames);
stats.put("deckBWinRate", (double) rs.getInt("b_wins") / totalGames);
stats.put("deckCWinRate", (double) rs.getInt("c_wins") / totalGames);
}
}
}
return stats;
}
// ══════════════════════════════════════════════════════════
// Deck Analysis Storage
// ══════════════════════════════════════════════════════════
/**
* Store a deck analysis snapshot.
*/
public synchronized void saveDeckAnalysis(DeckAnalysis analysis) throws SQLException {
String json = GSON.toJson(analysis);
try (PreparedStatement ps = conn.prepareStatement("""
INSERT INTO deck_analyses
(deck_name, commander_name, total_cards, lands, creatures,
ramp_cards, removal_cards, draw_cards, board_wipes, analysis_json)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""")) {
ps.setString(1, analysis.deckName);
ps.setString(2, analysis.commanderName);
ps.setInt(3, analysis.totalCards);
ps.setInt(4, analysis.lands);
ps.setInt(5, analysis.creatures);
ps.setInt(6, analysis.rampCards);
ps.setInt(7, analysis.removalCards);
ps.setInt(8, analysis.drawCards);
ps.setInt(9, analysis.boardWipes);
ps.setString(10, json);
ps.executeUpdate();
}
}
/**
* Get the latest deck analysis for a deck.
*/
public String getLatestDeckAnalysis(String deckName) throws SQLException {
try (PreparedStatement ps = conn.prepareStatement("""
SELECT analysis_json FROM deck_analyses
WHERE deck_name = ? ORDER BY created_at DESC LIMIT 1
""")) {
ps.setString(1, deckName);
ResultSet rs = ps.executeQuery();
if (rs.next()) return rs.getString("analysis_json");
}
return null;
}
// ══════════════════════════════════════════════════════════
// Stats Summary
// ══════════════════════════════════════════════════════════
/**
* Get a global stats summary across all batches.
*/
public Map<String, Object> getGlobalStats() throws SQLException {
Map<String, Object> stats = new LinkedHashMap<>();
try (Statement s = conn.createStatement()) {
ResultSet rs = s.executeQuery("""
SELECT
COUNT(*) as total_batches,
SUM(completed_games) as total_games,
AVG(sims_per_sec) as avg_sims_sec,
AVG(avg_game_turns) as avg_turns,
SUM(elapsed_ms) as total_time_ms
FROM batch_runs
""");
if (rs.next()) {
stats.put("totalBatches", rs.getInt("total_batches"));
stats.put("totalGames", rs.getInt("total_games"));
stats.put("avgSimsPerSec", rs.getDouble("avg_sims_sec"));
stats.put("avgGameTurns", rs.getDouble("avg_turns"));
stats.put("totalTimeMs", rs.getLong("total_time_ms"));
}
// Count unique decks tested
rs = s.executeQuery("SELECT COUNT(DISTINCT deck_name) as deck_count FROM deck_results");
if (rs.next()) {
stats.put("uniqueDecks", rs.getInt("deck_count"));
}
}
return stats;
}
@Override
public void close() throws SQLException {
if (conn != null && !conn.isClosed()) {
conn.close();
}
}
}
@@ -0,0 +1,217 @@
package commanderailab.meta;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import java.io.*;
import java.nio.file.*;
import java.util.*;
/**
* CommanderMetaService — Provides curated meta deck mappings for popular commanders.
*
* Maps commander names to recommended meta deck sources (EDHREC average, curated lists).
* The mapping is stored as a JSON file (commander-meta.json) alongside the JAR,
* and can be extended by the user.
*
* Usage:
* CommanderMetaService.loadMapping("commander-meta.json");
* List<MetaDeckEntry> decks = CommanderMetaService.getMetaDecks("Edgar Markov");
*/
public class CommanderMetaService {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
/** Commander name (lowercased) → list of meta deck entries */
private static Map<String, List<MetaDeckEntry>> mapping = new LinkedHashMap<>();
/** All known commanders (for autocomplete / listing) */
private static List<String> knownCommanders = new ArrayList<>();
// ── Data model ─────────────────────────────────────────
public static class MetaDeckEntry {
public String commander; // Canonical commander name
public String label; // Display label (e.g., "EDHREC Average", "High Power Aggro")
public String source; // Source type: "edhrec", "archidekt", "curated"
public String url; // URL to fetch/reference
public String archetype; // Optional: aggro, control, combo, midrange, stax
public String[] colorIdentity; // e.g., ["W","B","R"]
public String notes; // Optional notes
public MetaDeckEntry() {}
public MetaDeckEntry(String commander, String label, String source, String url) {
this.commander = commander;
this.label = label;
this.source = source;
this.url = url;
}
@Override
public String toString() {
return String.format("%s — %s (%s)", commander, label, source);
}
}
// ══════════════════════════════════════════════════════════
// Mapping Management
// ══════════════════════════════════════════════════════════
/**
* Load the commander→meta deck mapping from a JSON file.
*/
public static void loadMapping(String filePath) throws IOException {
if (!Files.exists(Path.of(filePath))) {
System.out.println(" [Meta] No commander-meta.json found, using built-in defaults.");
loadBuiltinDefaults();
return;
}
String json = Files.readString(Path.of(filePath));
loadFromJson(json);
System.out.printf(" [Meta] Loaded %d commanders from %s%n", knownCommanders.size(), filePath);
}
/**
* Load mapping from a JSON string.
*/
public static void loadFromJson(String json) {
JsonObject root = JsonParser.parseString(json).getAsJsonObject();
mapping.clear();
knownCommanders.clear();
for (var entry : root.entrySet()) {
String key = entry.getKey(); // Commander name (canonical)
JsonArray arr = entry.getValue().getAsJsonArray();
List<MetaDeckEntry> entries = new ArrayList<>();
for (JsonElement el : arr) {
MetaDeckEntry mde = GSON.fromJson(el, MetaDeckEntry.class);
if (mde.commander == null) mde.commander = key;
entries.add(mde);
}
mapping.put(key.toLowerCase(), entries);
knownCommanders.add(key);
}
}
/**
* Save the current mapping to a JSON file.
*/
public static void saveMapping(String filePath) throws IOException {
// Reconstruct with canonical names as keys
JsonObject root = new JsonObject();
for (String commander : knownCommanders) {
List<MetaDeckEntry> entries = mapping.get(commander.toLowerCase());
if (entries != null) {
root.add(commander, GSON.toJsonTree(entries));
}
}
Files.writeString(Path.of(filePath), GSON.toJson(root));
}
// ══════════════════════════════════════════════════════════
// Queries
// ══════════════════════════════════════════════════════════
/**
* Get meta deck entries for a commander.
*/
public static List<MetaDeckEntry> getMetaDecks(String commanderName) {
return mapping.getOrDefault(commanderName.toLowerCase(), List.of());
}
/**
* Check if a commander has meta deck entries.
*/
public static boolean hasMetaDecks(String commanderName) {
return mapping.containsKey(commanderName.toLowerCase());
}
/**
* Get all known commander names.
*/
public static List<String> getAllCommanders() {
return Collections.unmodifiableList(knownCommanders);
}
/**
* Search commanders by partial name match (case-insensitive).
*/
public static List<String> searchCommanders(String query) {
String lower = query.toLowerCase();
return knownCommanders.stream()
.filter(c -> c.toLowerCase().contains(lower))
.toList();
}
/**
* Get the first/default meta deck for a commander.
* Usually the EDHREC average deck.
*/
public static MetaDeckEntry getDefaultMetaDeck(String commanderName) {
List<MetaDeckEntry> entries = getMetaDecks(commanderName);
return entries.isEmpty() ? null : entries.get(0);
}
// ══════════════════════════════════════════════════════════
// Built-in Defaults
// ══════════════════════════════════════════════════════════
/**
* Load a curated set of popular commanders with EDHREC average deck links.
* These cover the most commonly tested commanders.
*/
public static void loadBuiltinDefaults() {
mapping.clear();
knownCommanders.clear();
addDefault("Edgar Markov", new String[]{"W","B","R"}, "aggro",
"https://edhrec.com/average-decks/edgar-markov");
addDefault("Atraxa, Praetors' Voice", new String[]{"W","U","B","G"}, "midrange",
"https://edhrec.com/average-decks/atraxa-praetors-voice");
addDefault("Korvold, Fae-Cursed King", new String[]{"B","R","G"}, "combo",
"https://edhrec.com/average-decks/korvold-fae-cursed-king");
addDefault("Muldrotha, the Gravetide", new String[]{"U","B","G"}, "midrange",
"https://edhrec.com/average-decks/muldrotha-the-gravetide");
addDefault("The Ur-Dragon", new String[]{"W","U","B","R","G"}, "midrange",
"https://edhrec.com/average-decks/the-ur-dragon");
addDefault("Yuriko, the Tiger's Shadow", new String[]{"U","B"}, "aggro",
"https://edhrec.com/average-decks/yuriko-the-tigers-shadow");
addDefault("Krenko, Mob Boss", new String[]{"R"}, "aggro",
"https://edhrec.com/average-decks/krenko-mob-boss");
addDefault("Meren of Clan Nel Toth", new String[]{"B","G"}, "midrange",
"https://edhrec.com/average-decks/meren-of-clan-nel-toth");
addDefault("Prossh, Skyraider of Kher", new String[]{"B","R","G"}, "combo",
"https://edhrec.com/average-decks/prossh-skyraider-of-kher");
addDefault("Kaalia of the Vast", new String[]{"W","B","R"}, "aggro",
"https://edhrec.com/average-decks/kaalia-of-the-vast");
addDefault("Windgrace", new String[]{"B","R","G"}, "midrange",
"https://edhrec.com/average-decks/lord-windgrace");
addDefault("Talrand, Sky Summoner", new String[]{"U"}, "control",
"https://edhrec.com/average-decks/talrand-sky-summoner");
addDefault("Omnath, Locus of Creation", new String[]{"W","U","R","G"}, "combo",
"https://edhrec.com/average-decks/omnath-locus-of-creation");
addDefault("Teysa Karlov", new String[]{"W","B"}, "combo",
"https://edhrec.com/average-decks/teysa-karlov");
addDefault("Lathril, Blade of the Elves", new String[]{"B","G"}, "aggro",
"https://edhrec.com/average-decks/lathril-blade-of-the-elves");
System.out.printf(" [Meta] Loaded %d built-in commander defaults%n", knownCommanders.size());
}
private static void addDefault(String commander, String[] colors, String archetype, String url) {
MetaDeckEntry entry = new MetaDeckEntry();
entry.commander = commander;
entry.label = "EDHREC Average";
entry.source = "edhrec";
entry.url = url;
entry.archetype = archetype;
entry.colorIdentity = colors;
mapping.put(commander.toLowerCase(), new ArrayList<>(List.of(entry)));
knownCommanders.add(commander);
}
}
@@ -0,0 +1,507 @@
package commanderailab.meta;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import java.io.*;
import java.net.URI;
import java.net.http.*;
import java.nio.file.*;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
/**
* DeckImporter — Fetches and parses decks from external sources.
*
* Supported sources:
* - EDHREC average deck: json.edhrec.com/pages/average-decks/{commander}.json
* - Archidekt deck: archidekt.com/api/decks/{id}/
* - Text import: Plain card list ("1 Card Name" per line)
* - Local .dck file: Forge deck format
*
* All imports produce a DeckProfile which can be converted to Forge .dck format.
*/
public class DeckImporter {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private static final HttpClient HTTP = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(15))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
private static final String USER_AGENT = "CommanderAILab/2.0";
// ══════════════════════════════════════════════════════════
// EDHREC Average Deck
// ══════════════════════════════════════════════════════════
/**
* Fetch the EDHREC average/recommended deck for a commander.
*
* @param commanderName e.g., "Edgar Markov", "Atraxa, Praetors' Voice"
* @return DeckProfile with ~100 cards
*/
public static DeckProfile importFromEdhrec(String commanderName) throws IOException, InterruptedException {
String slug = toEdhrecSlug(commanderName);
String url = "https://json.edhrec.com/pages/average-decks/" + slug + ".json";
System.out.printf(" [Import] Fetching EDHREC average deck: %s%n", url);
String json = httpGet(url);
JsonObject root = JsonParser.parseString(json).getAsJsonObject();
DeckProfile profile = new DeckProfile();
profile.source = DeckProfile.DeckSource.EDHREC_AVERAGE;
profile.sourceUrl = "https://edhrec.com/average-decks/" + slug;
profile.importedAt = Instant.now().toString();
// Get commander info
JsonObject container = root.getAsJsonObject("container");
JsonObject jsonDict = container.getAsJsonObject("json_dict");
JsonObject cardInfo = jsonDict.getAsJsonObject("card");
String realName = cardInfo.get("name").getAsString();
profile.commander = realName;
profile.name = realName + " — EDHREC Average";
// Parse color identity
if (cardInfo.has("color_identity") && cardInfo.get("color_identity").isJsonArray()) {
for (JsonElement ci : cardInfo.getAsJsonArray("color_identity")) {
profile.colorIdentity.add(ci.getAsString());
}
}
// Sample size
if (root.has("num_decks_avg")) {
profile.sampleSize = root.get("num_decks_avg").getAsInt();
}
// Build card list from cardlists (each tag is a category)
JsonArray cardlists = jsonDict.getAsJsonArray("cardlists");
profile.commanders.put(realName, 1);
for (JsonElement clEl : cardlists) {
JsonObject cl = clEl.getAsJsonObject();
String tag = cl.has("tag") ? cl.get("tag").getAsString() : "";
JsonArray cardviews = cl.getAsJsonArray("cardviews");
for (JsonElement cvEl : cardviews) {
JsonObject cv = cvEl.getAsJsonObject();
String cardName = cv.get("name").getAsString();
// Default quantity is 1 for non-basics
int qty = 1;
profile.mainboard.put(cardName, qty);
}
}
// Fix basic land quantities using the archidekt export data
if (root.has("archidekt") && root.get("archidekt").isJsonArray()) {
fixBasicLandQuantities(profile, root.getAsJsonArray("archidekt"), cardlists);
}
// Ensure we hit ~100 cards
profile.totalCards = profile.commanders.values().stream().mapToInt(Integer::intValue).sum()
+ profile.mainboard.values().stream().mapToInt(Integer::intValue).sum();
System.out.printf(" [Import] EDHREC deck loaded: %s (%d cards, %d decks sampled)%n",
profile.commander, profile.totalCards, profile.sampleSize != null ? profile.sampleSize : 0);
return profile;
}
/**
* Fix basic land quantities from EDHREC's archidekt export array.
* The archidekt array has {c, f, q, u} entries where q>1 for basics.
*/
private static void fixBasicLandQuantities(DeckProfile profile, JsonArray archidekt, JsonArray cardlists) {
// Build a name→uuid lookup from cardlists
// Also collect basic land names from cardlists
Set<String> basicLandNames = new HashSet<>();
for (JsonElement clEl : cardlists) {
JsonObject cl = clEl.getAsJsonObject();
String tag = cl.has("tag") ? cl.get("tag").getAsString() : "";
if (tag.equals("basics")) {
for (JsonElement cvEl : cl.getAsJsonArray("cardviews")) {
basicLandNames.add(cvEl.getAsJsonObject().get("name").getAsString());
}
}
}
// Count entries with q>1 — these are basic lands
int totalFromArchidekt = 0;
int nonBasicCards = 0;
Map<String, Integer> basicQuantities = new LinkedHashMap<>();
for (JsonElement ae : archidekt) {
JsonObject entry = ae.getAsJsonObject();
int qty = entry.get("q").getAsInt();
totalFromArchidekt += qty;
if (qty > 1) {
// This is a basic land — we'll match by position
basicQuantities.put(entry.get("u").getAsString(), qty);
} else {
nonBasicCards++;
}
}
// Update basic land quantities in the profile
// The basic lands in profile.mainboard currently have qty=1
// We need to update them with correct quantities
if (!basicQuantities.isEmpty() && !basicLandNames.isEmpty()) {
// Simple approach: distribute the excess cards among basic lands
int totalBasicQty = basicQuantities.values().stream().mapToInt(Integer::intValue).sum();
int numBasics = basicLandNames.size();
// Try to match by Scryfall UUID (expensive) or just use the quantities in order
List<String> basicNames = new ArrayList<>(basicLandNames);
List<Integer> quantities = new ArrayList<>(basicQuantities.values());
for (int i = 0; i < Math.min(basicNames.size(), quantities.size()); i++) {
profile.mainboard.put(basicNames.get(i), quantities.get(i));
}
}
}
// ══════════════════════════════════════════════════════════
// Archidekt Deck Import
// ══════════════════════════════════════════════════════════
/**
* Fetch a public deck from Archidekt by deck ID.
*
* @param deckId Archidekt deck ID (numeric)
* @return DeckProfile
*/
public static DeckProfile importFromArchidekt(String deckId) throws IOException, InterruptedException {
String url = "https://archidekt.com/api/decks/" + deckId + "/";
System.out.printf(" [Import] Fetching Archidekt deck: %s%n", url);
String json = httpGet(url);
JsonObject root = JsonParser.parseString(json).getAsJsonObject();
DeckProfile profile = new DeckProfile();
profile.source = DeckProfile.DeckSource.ARCHIDEKT;
profile.sourceUrl = "https://archidekt.com/decks/" + deckId;
profile.importedAt = Instant.now().toString();
profile.name = root.has("name") ? root.get("name").getAsString() : "Archidekt Deck " + deckId;
// Parse cards
JsonArray cards = root.getAsJsonArray("cards");
for (JsonElement cardEl : cards) {
JsonObject entry = cardEl.getAsJsonObject();
int qty = entry.get("quantity").getAsInt();
JsonObject card = entry.getAsJsonObject("card");
JsonObject oracle = card.getAsJsonObject("oracleCard");
String cardName = oracle.get("name").getAsString();
// Check categories for Commander
JsonArray categories = entry.getAsJsonArray("categories");
boolean isCommander = false;
for (JsonElement cat : categories) {
if (cat.getAsString().equalsIgnoreCase("Commander")) {
isCommander = true;
break;
}
}
if (isCommander) {
profile.commanders.put(cardName, qty);
if (profile.commander == null) {
profile.commander = cardName;
}
// Extract color identity from commander
if (oracle.has("colorIdentity") && oracle.get("colorIdentity").isJsonArray()) {
for (JsonElement ci : oracle.getAsJsonArray("colorIdentity")) {
String color = ci.getAsString();
if (!profile.colorIdentity.contains(color)) {
profile.colorIdentity.add(color);
}
}
}
} else {
profile.mainboard.put(cardName, qty);
}
}
profile.totalCards = profile.commanders.values().stream().mapToInt(Integer::intValue).sum()
+ profile.mainboard.values().stream().mapToInt(Integer::intValue).sum();
System.out.printf(" [Import] Archidekt deck loaded: %s — %s (%d cards)%n",
profile.name, profile.commander, profile.totalCards);
return profile;
}
// ══════════════════════════════════════════════════════════
// Text Import (MTGO / Arena / Generic Format)
// ══════════════════════════════════════════════════════════
/**
* Parse a plain text card list.
* Supports formats:
* 1 Card Name
* 1x Card Name
* 1 Card Name (SET) 123
*
* The first card or a line starting with "Commander:" / "[Commander]" is the commander.
*/
public static DeckProfile importFromText(String text, String commanderOverride) {
DeckProfile profile = new DeckProfile();
profile.source = DeckProfile.DeckSource.TEXT_IMPORT;
profile.importedAt = Instant.now().toString();
String currentSection = "main";
boolean commanderFound = false;
for (String line : text.split("\\n")) {
line = line.trim();
if (line.isEmpty() || line.startsWith("//") || line.startsWith("#")) continue;
// Section markers
if (line.toLowerCase().startsWith("commander") || line.equalsIgnoreCase("[Commander]")) {
currentSection = "commander";
continue;
}
if (line.toLowerCase().startsWith("main") || line.toLowerCase().startsWith("deck")
|| line.equalsIgnoreCase("[Main]") || line.equalsIgnoreCase("[Deck]")) {
currentSection = "main";
continue;
}
if (line.toLowerCase().startsWith("sideboard") || line.equalsIgnoreCase("[Sideboard]")) {
currentSection = "sideboard";
continue;
}
// Parse card entry: "1 Card Name", "1x Card Name", "1 Card Name (SET) 123"
String cleanLine = line
.replaceAll("\\(\\w+\\)\\s*\\d*$", "") // Remove "(SET) 123" suffix
.replaceAll("\\s*\\*.*$", "") // Remove "* F" foil markers
.trim();
int qty = 1;
String cardName;
var match = java.util.regex.Pattern.compile("^(\\d+)x?\\s+(.+)$").matcher(cleanLine);
if (match.matches()) {
qty = Integer.parseInt(match.group(1));
cardName = match.group(2).trim();
} else {
cardName = cleanLine;
}
if (cardName.isEmpty()) continue;
if (currentSection.equals("commander")) {
profile.commanders.put(cardName, qty);
if (!commanderFound) {
profile.commander = cardName;
commanderFound = true;
}
} else if (!currentSection.equals("sideboard")) {
profile.mainboard.put(cardName, qty);
}
}
// Commander override
if (commanderOverride != null && !commanderOverride.isBlank()) {
profile.commander = commanderOverride;
if (profile.commanders.isEmpty()) {
// Move from mainboard to commander zone if found
if (profile.mainboard.containsKey(commanderOverride)) {
int qty = profile.mainboard.remove(commanderOverride);
profile.commanders.put(commanderOverride, qty);
} else {
profile.commanders.put(commanderOverride, 1);
}
}
}
profile.name = profile.commander != null ? profile.commander + " — Text Import" : "Text Import";
profile.totalCards = profile.commanders.values().stream().mapToInt(Integer::intValue).sum()
+ profile.mainboard.values().stream().mapToInt(Integer::intValue).sum();
return profile;
}
// ══════════════════════════════════════════════════════════
// Local .dck File Import
// ══════════════════════════════════════════════════════════
/**
* Parse a Forge .dck file into a DeckProfile.
*/
public static DeckProfile importFromDckFile(String filePath) throws IOException {
List<String> lines = Files.readAllLines(Path.of(filePath));
DeckProfile profile = new DeckProfile();
profile.source = DeckProfile.DeckSource.LOCAL_FILE;
profile.sourceUrl = filePath;
profile.importedAt = Instant.now().toString();
String currentSection = "Main";
String deckName = Path.of(filePath).getFileName().toString().replace(".dck", "");
for (String line : lines) {
line = line.trim();
if (line.isEmpty() || line.startsWith("//")) continue;
if (line.startsWith("[") && line.endsWith("]")) {
currentSection = line.substring(1, line.length() - 1);
continue;
}
if (line.startsWith("Name=")) {
deckName = line.substring(5).trim();
continue;
}
var match = java.util.regex.Pattern.compile("^(\\d+)\\s+(.+?)(?:\\|(.+))?$").matcher(line);
if (match.matches()) {
int qty = Integer.parseInt(match.group(1));
String cardName = match.group(2).trim();
if (currentSection.equalsIgnoreCase("Commander")) {
profile.commanders.put(cardName, qty);
if (profile.commander == null) profile.commander = cardName;
} else if (currentSection.equalsIgnoreCase("Main")) {
profile.mainboard.put(cardName, qty);
}
}
}
profile.name = deckName;
profile.totalCards = profile.commanders.values().stream().mapToInt(Integer::intValue).sum()
+ profile.mainboard.values().stream().mapToInt(Integer::intValue).sum();
return profile;
}
// ══════════════════════════════════════════════════════════
// Auto-detect import from URL
// ══════════════════════════════════════════════════════════
/**
* Auto-detect the source from a URL and import.
*
* Supported URL patterns:
* https://archidekt.com/decks/12345/... → Archidekt
* https://edhrec.com/average-decks/edgar-markov → EDHREC
* https://edhrec.com/commanders/edgar-markov → EDHREC average
*/
public static DeckProfile importFromUrl(String url) throws IOException, InterruptedException {
url = url.trim();
// Archidekt: https://archidekt.com/decks/12345 or /decks/12345/name
if (url.contains("archidekt.com/decks/")) {
String id = url.replaceAll(".*/decks/(\\d+).*", "$1");
return importFromArchidekt(id);
}
// EDHREC average deck: https://edhrec.com/average-decks/edgar-markov
if (url.contains("edhrec.com/average-decks/")) {
String slug = url.replaceAll(".*/average-decks/([^/?#]+).*", "$1");
String commanderName = slug.replace("-", " ");
return importFromEdhrec(commanderName);
}
// EDHREC commander page: https://edhrec.com/commanders/edgar-markov
if (url.contains("edhrec.com/commanders/")) {
String slug = url.replaceAll(".*/commanders/([^/?#]+).*", "$1");
String commanderName = slug.replace("-", " ");
return importFromEdhrec(commanderName);
}
throw new IllegalArgumentException("Unsupported URL: " + url
+ "\nSupported: archidekt.com/decks/..., edhrec.com/average-decks/..., edhrec.com/commanders/...");
}
// ══════════════════════════════════════════════════════════
// Forge .dck Export
// ══════════════════════════════════════════════════════════
/**
* Convert a DeckProfile to Forge .dck format.
*
* Format:
* [metadata]
* Name=Edgar Markov — EDHREC Average
* [Commander]
* 1 Edgar Markov
* [Main]
* 1 Blood Artist
* 1 Sol Ring
* ...
*/
public static String toDckFormat(DeckProfile profile) {
StringBuilder sb = new StringBuilder();
sb.append("[metadata]\n");
sb.append("Name=").append(profile.name != null ? profile.name : "Imported Deck").append("\n");
sb.append("\n");
// Commander zone
sb.append("[Commander]\n");
for (var entry : profile.commanders.entrySet()) {
sb.append(entry.getValue()).append(" ").append(entry.getKey()).append("\n");
}
sb.append("\n");
// Mainboard
sb.append("[Main]\n");
for (var entry : profile.mainboard.entrySet()) {
sb.append(entry.getValue()).append(" ").append(entry.getKey()).append("\n");
}
return sb.toString();
}
/**
* Save a DeckProfile as a Forge .dck file.
*
* @param profile The deck to save
* @param outputDir Directory to save into
* @return Path to the saved .dck file
*/
public static Path saveToDckFile(DeckProfile profile, String outputDir) throws IOException {
String safeName = sanitizeFileName(profile.name);
Path outPath = Path.of(outputDir, safeName + ".dck");
Files.createDirectories(outPath.getParent());
Files.writeString(outPath, toDckFormat(profile));
System.out.printf(" [Export] Saved .dck file: %s%n", outPath);
return outPath;
}
// ══════════════════════════════════════════════════════════
// Helpers
// ══════════════════════════════════════════════════════════
/**
* Convert commander name to EDHREC URL slug.
* "Edgar Markov" → "edgar-markov"
* "Atraxa, Praetors' Voice" → "atraxa-praetors-voice"
*/
static String toEdhrecSlug(String commanderName) {
return commanderName.toLowerCase()
.replaceAll("[',.]", "")
.replaceAll("[^a-z0-9]+", "-")
.replaceAll("^-|-$", "");
}
private static String sanitizeFileName(String name) {
if (name == null) return "imported-deck";
return name.replaceAll("[^a-zA-Z0-9 _-]", "")
.replaceAll("\\s+", "_")
.trim();
}
private static String httpGet(String url) throws IOException, InterruptedException {
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("User-Agent", USER_AGENT)
.timeout(Duration.ofSeconds(30))
.GET()
.build();
HttpResponse<String> resp = HTTP.send(req, HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() != 200) {
throw new IOException("HTTP " + resp.statusCode() + " fetching " + url + ": " + resp.body().substring(0, Math.min(200, resp.body().length())));
}
return resp.body();
}
}
@@ -0,0 +1,110 @@
package commanderailab.meta;
import java.util.*;
/**
* DeckProfile — Represents an imported deck from an external source.
*
* Holds card list + metadata about where the deck came from
* (EDHREC average, Archidekt user deck, Moxfield paste, etc.)
*/
public class DeckProfile {
/** Display name for the deck (e.g., "Edgar Markov — EDHREC Average") */
public String name;
/** Commander card name */
public String commander;
/** Color identity (e.g., ["W","B","R"]) */
public List<String> colorIdentity = new ArrayList<>();
/** Where this deck came from */
public DeckSource source;
/** URL to the original deck (Archidekt/Moxfield/EDHREC page) */
public String sourceUrl;
/** Cards in the 99 (mainboard) — cardName → quantity */
public Map<String, Integer> mainboard = new LinkedHashMap<>();
/** Cards in the command zone — cardName → quantity (usually 1-2 for partners) */
public Map<String, Integer> commanders = new LinkedHashMap<>();
/** Total card count (should be 99 + commander(s) = 100) */
public int totalCards;
/** Timestamp of import */
public String importedAt;
/** Optional: EDHREC-specific — number of decks sampled */
public Integer sampleSize;
/** Optional: archetype tag (aggro, control, combo, etc.) */
public String archetype;
// ── Source enum ─────────────────────────────────────────
public enum DeckSource {
EDHREC_AVERAGE, // EDHREC average/recommended deck for a commander
ARCHIDEKT, // Archidekt public deck by ID
MOXFIELD, // Moxfield text import
TEXT_IMPORT, // Raw card list paste (MTGO/Arena format)
LOCAL_FILE, // Local .dck file
CURATED; // Hand-curated meta deck in JSON mapping
public String label() {
return switch (this) {
case EDHREC_AVERAGE -> "EDHREC Average";
case ARCHIDEKT -> "Archidekt";
case MOXFIELD -> "Moxfield";
case TEXT_IMPORT -> "Text Import";
case LOCAL_FILE -> "Local File";
case CURATED -> "Curated Meta";
};
}
}
// ── Helpers ─────────────────────────────────────────────
/**
* Get all cards (commanders + mainboard) as a flat list with quantities.
*/
public Map<String, Integer> allCards() {
Map<String, Integer> all = new LinkedHashMap<>();
all.putAll(commanders);
all.putAll(mainboard);
return all;
}
/**
* Validate the deck has a reasonable structure.
*/
public List<String> validate() {
List<String> issues = new ArrayList<>();
if (commander == null || commander.isBlank()) {
issues.add("No commander specified");
}
if (commanders.isEmpty()) {
issues.add("Commander zone is empty");
}
int total = commanders.values().stream().mapToInt(Integer::intValue).sum()
+ mainboard.values().stream().mapToInt(Integer::intValue).sum();
if (total < 90) {
issues.add("Deck has only " + total + " cards (expected ~100)");
}
if (total > 101) {
issues.add("Deck has " + total + " cards (expected 100)");
}
totalCards = total;
return issues;
}
@Override
public String toString() {
int mainCount = mainboard.values().stream().mapToInt(Integer::intValue).sum();
int cmdCount = commanders.values().stream().mapToInt(Integer::intValue).sum();
return String.format("DeckProfile{name='%s', commander='%s', source=%s, cards=%d+%d}",
name, commander, source, cmdCount, mainCount);
}
}
@@ -0,0 +1,397 @@
package commanderailab.ml;
import commanderailab.schema.DecisionSnapshot;
import commanderailab.schema.DecisionSnapshot.*;
import java.util.*;
import java.util.regex.*;
/**
* DecisionExtractor — Reconstructs game state and decisions from Forge verbose logs.
*
* Forge verbose output emits lines for each game event: draws, casts, attacks,
* damage, phase transitions, etc. This class maintains running game state and
* emits a DecisionSnapshot at each point where the AI made a meaningful choice.
*
* Key Forge log patterns:
* "== Turn 5 (Ai(1)-CommanderName) ==" → Turn/active player
* "Ai(1)-Name draws CardName." → Draw event
* "Ai(1)-Name casts CardName." → Spell cast decision
* "Ai(1)-Name plays LandName." → Land play decision
* "Ai(1)-Name attacks with [CreatureList]" → Attack declaration
* "Phase: Main 1" / "Phase: Combat" / etc. → Phase transition
* "Ai(1) life: 40 → 37" → Life change
*
* Limitations:
* - Hand contents must be inferred from draws and casts (Forge doesn't dump hands)
* - Mana available is estimated from land count and known mana rocks
* - Graveyard is tracked from death/destroy/discard events
*/
public class DecisionExtractor {
// ── Patterns ──────────────────────────────────────────────
// Turn boundary: "Turn 5 (Ai(1)-Name)" or "== Turn 5 (Ai(1)-Name) =="
private static final Pattern TURN_PATTERN =
Pattern.compile("Turn\\s+(\\d+)\\s+\\(Ai\\((\\d+)\\)-", Pattern.CASE_INSENSITIVE);
// Phase indicator: various Forge phase strings
private static final Pattern PHASE_PATTERN =
Pattern.compile("(?:Phase|Step):\\s*(.*?)(?:\\s*$|\\s*-)", Pattern.CASE_INSENSITIVE);
// Cast: "Ai(1)-Name casts CardName."
private static final Pattern CAST_PATTERN =
Pattern.compile("Ai\\((\\d+)\\)-[^\\s].*?\\s+casts\\s+(.+?)\\.", Pattern.CASE_INSENSITIVE);
// Land play: "Ai(1)-Name plays LandName."
private static final Pattern LAND_PATTERN =
Pattern.compile("Ai\\((\\d+)\\)-[^\\s].*?\\s+plays\\s+(.+?)\\.", Pattern.CASE_INSENSITIVE);
// Draw: "Ai(1)-Name draws CardName."
private static final Pattern DRAW_PATTERN =
Pattern.compile("Ai\\((\\d+)\\)-[^\\s].*?\\s+draws\\s+(.+?)\\.", Pattern.CASE_INSENSITIVE);
// Attack: "Ai(1)-Name attacks with" or "declares attackers"
private static final Pattern ATTACK_PATTERN =
Pattern.compile("Ai\\((\\d+)\\)-.*?(?:attacks|declares? attackers)", Pattern.CASE_INSENSITIVE);
// Life change: captures current life from various formats
private static final Pattern LIFE_PATTERN =
Pattern.compile("Ai\\((\\d+)\\).*?life.*?(\\d+)", Pattern.CASE_INSENSITIVE);
// Destroy/die: card leaves battlefield
private static final Pattern DESTROY_PATTERN =
Pattern.compile("(.+?)\\s+(?:is destroyed|dies|is put into .* graveyard)", Pattern.CASE_INSENSITIVE);
// Damage: "CardName deals N damage to Ai(X)"
private static final Pattern DAMAGE_TO_PLAYER =
Pattern.compile("deals\\s+(\\d+)\\s+(?:combat\\s+)?damage\\s+to\\s+Ai\\((\\d+)\\)", Pattern.CASE_INSENSITIVE);
// Commander damage: various formats
private static final Pattern CMDR_DMG_PATTERN =
Pattern.compile("(\\d+)\\s+commander\\s+damage", Pattern.CASE_INSENSITIVE);
// ── Running game state ─────────────────────────────────────
private final int numPlayers;
private final String gameId;
private final String[] commanderNames; // commander name per seat
// Per-seat mutable state
private final int[] lifeTotals;
private final int[] commanderDamage; // damage from opponent's commander
private final int[] commanderCasts;
private final List<List<String>> hands; // inferred hand contents
private final List<List<String>> battlefields;
private final List<List<String>> graveyards;
private final List<List<String>> commandZones;
// Turn tracking
private int currentTurn = 0;
private int activeSeat = 0;
private String currentPhase = "main_1";
// Output
private final List<DecisionSnapshot> decisions = new ArrayList<>();
// ══════════════════════════════════════════════════════════
// Constructor
// ══════════════════════════════════════════════════════════
/**
* @param numPlayers Number of players (2 for 1v1)
* @param gameId Unique identifier for this game
* @param commanderNames Commander name for each seat (0-indexed)
* @param deckCardNames Cards in each player's deck (for initial state)
*/
public DecisionExtractor(int numPlayers, String gameId,
String[] commanderNames,
List<List<String>> deckCardNames) {
this.numPlayers = numPlayers;
this.gameId = gameId;
this.commanderNames = commanderNames;
this.lifeTotals = new int[numPlayers];
this.commanderDamage = new int[numPlayers];
this.commanderCasts = new int[numPlayers];
this.hands = new ArrayList<>();
this.battlefields = new ArrayList<>();
this.graveyards = new ArrayList<>();
this.commandZones = new ArrayList<>();
for (int i = 0; i < numPlayers; i++) {
lifeTotals[i] = 40;
commanderDamage[i] = 0;
commanderCasts[i] = 0;
hands.add(new ArrayList<>());
battlefields.add(new ArrayList<>());
graveyards.add(new ArrayList<>());
// Commander starts in command zone
List<String> cmdZone = new ArrayList<>();
if (commanderNames[i] != null) {
cmdZone.add(commanderNames[i]);
}
commandZones.add(cmdZone);
}
}
// ══════════════════════════════════════════════════════════
// Main parsing entry point
// ══════════════════════════════════════════════════════════
/**
* Process all lines of a Forge verbose game log.
* Call this once with the full output; it populates the decisions list.
*
* @param lines Array of log lines (split from full output)
* @return List of decision snapshots extracted from this game
*/
public List<DecisionSnapshot> processGameLog(String[] lines) {
for (String rawLine : lines) {
String line = rawLine.trim();
if (line.isEmpty()) continue;
// ── Turn boundary ──────────────────────────────
Matcher turnM = TURN_PATTERN.matcher(line);
if (turnM.find()) {
currentTurn = Integer.parseInt(turnM.group(1));
activeSeat = Integer.parseInt(turnM.group(2)) - 1;
currentPhase = "main_1"; // Reset to main 1 at turn start
continue;
}
// ── Phase transition ───────────────────────────
Matcher phaseM = PHASE_PATTERN.matcher(line);
if (phaseM.find()) {
currentPhase = normalizePhase(phaseM.group(1).trim());
continue;
}
// ── Draw event (state update only, not a decision) ──
Matcher drawM = DRAW_PATTERN.matcher(line);
if (drawM.find()) {
int seat = Integer.parseInt(drawM.group(1)) - 1;
String card = drawM.group(2).trim();
if (seat >= 0 && seat < numPlayers) {
hands.get(seat).add(card);
}
continue;
}
// ── Cast spell → DECISION POINT ────────────────
Matcher castM = CAST_PATTERN.matcher(line);
if (castM.find()) {
int seat = Integer.parseInt(castM.group(1)) - 1;
String card = castM.group(2).trim();
if (seat >= 0 && seat < numPlayers) {
// Snapshot BEFORE the action changes state
ActionRecord action = new ActionRecord();
action.rawLogLine = line;
action.cardName = card;
// Determine action type
if (commanderNames[seat] != null &&
card.equalsIgnoreCase(commanderNames[seat])) {
action.type = "cast_commander";
commanderCasts[seat]++;
commandZones.get(seat).remove(card);
} else {
action.type = "cast";
}
// Emit decision snapshot
emitDecision(seat, action);
// Update state: card moves from hand to battlefield
hands.get(seat).remove(card);
battlefields.get(seat).add(card);
}
continue;
}
// ── Land play → DECISION POINT ─────────────────
Matcher landM = LAND_PATTERN.matcher(line);
if (landM.find()) {
int seat = Integer.parseInt(landM.group(1)) - 1;
String card = landM.group(2).trim();
if (seat >= 0 && seat < numPlayers) {
ActionRecord action = new ActionRecord();
action.type = "land";
action.cardName = card;
action.rawLogLine = line;
emitDecision(seat, action);
hands.get(seat).remove(card);
battlefields.get(seat).add(card);
}
continue;
}
// ── Attack declaration → DECISION POINT ────────
Matcher attackM = ATTACK_PATTERN.matcher(line);
if (attackM.find()) {
int seat = Integer.parseInt(attackM.group(1)) - 1;
if (seat >= 0 && seat < numPlayers) {
ActionRecord action = new ActionRecord();
action.type = "attack";
action.rawLogLine = line;
emitDecision(seat, action);
}
continue;
}
// ── Damage to player (state update) ────────────
Matcher dmgM = DAMAGE_TO_PLAYER.matcher(line);
if (dmgM.find()) {
int amount = Integer.parseInt(dmgM.group(1));
int targetSeat = Integer.parseInt(dmgM.group(2)) - 1;
if (targetSeat >= 0 && targetSeat < numPlayers) {
lifeTotals[targetSeat] -= amount;
}
// Check for commander damage
if (line.toLowerCase().contains("commander")) {
if (targetSeat >= 0 && targetSeat < numPlayers) {
commanderDamage[targetSeat] += amount;
}
}
continue;
}
// ── Card destroyed / dies (state update) ───────
Matcher destroyM = DESTROY_PATTERN.matcher(line);
if (destroyM.find()) {
String card = destroyM.group(1).trim();
// Move from battlefield to graveyard
for (int s = 0; s < numPlayers; s++) {
if (battlefields.get(s).remove(card)) {
graveyards.get(s).add(card);
// If it's the commander, it goes to command zone instead
if (commanderNames[s] != null &&
card.equalsIgnoreCase(commanderNames[s])) {
graveyards.get(s).remove(card);
commandZones.get(s).add(card);
}
break;
}
}
}
}
return decisions;
}
// ══════════════════════════════════════════════════════════
// Snapshot emission
// ══════════════════════════════════════════════════════════
private void emitDecision(int actingSeat, ActionRecord action) {
DecisionSnapshot snap = new DecisionSnapshot();
snap.gameId = gameId;
snap.turnNumber = currentTurn;
snap.phase = currentPhase;
snap.activeSeat = actingSeat;
snap.action = action;
// Build player snapshots
snap.players = new ArrayList<>();
for (int s = 0; s < numPlayers; s++) {
PlayerSnapshot ps = new PlayerSnapshot();
ps.seatIndex = s;
ps.lifeTotal = lifeTotals[s];
ps.commanderDamageTaken = commanderDamage[s];
ps.manaAvailable = estimateMana(s);
ps.commanderTax = commanderCasts[s] * 2;
ps.commanderCasts = commanderCasts[s];
ps.hand = new ArrayList<>(hands.get(s));
ps.battlefield = new ArrayList<>(battlefields.get(s));
ps.graveyard = new ArrayList<>(graveyards.get(s));
ps.commandZone = new ArrayList<>(commandZones.get(s));
// Compute board stats
ps.creaturesOnField = countType(battlefields.get(s), "creature");
ps.totalPowerOnBoard = 0; // Would need card DB — leave as 0 for now
ps.totalToughnessOnBoard = 0;
ps.artifactsOnField = 0;
ps.enchantmentsOnField = 0;
ps.landCount = countLands(battlefields.get(s));
snap.players.add(ps);
}
decisions.add(snap);
}
// ══════════════════════════════════════════════════════════
// Helpers
// ══════════════════════════════════════════════════════════
/**
* Estimate available mana from land count on battlefield.
* Simple heuristic: lands count ≈ mana available.
* (Mana rocks and dorks would improve this.)
*/
private int estimateMana(int seat) {
return countLands(battlefields.get(seat));
}
/**
* Count lands on battlefield.
* Heuristic: any card name containing typical land keywords.
*/
private int countLands(List<String> battlefield) {
int count = 0;
for (String card : battlefield) {
String lower = card.toLowerCase();
if (lower.contains("plains") || lower.contains("island") ||
lower.contains("swamp") || lower.contains("mountain") ||
lower.contains("forest") || lower.contains("land") ||
lower.contains("command tower") || lower.contains("sol ring") ||
lower.contains("temple") || lower.contains("shock") ||
lower.contains("fetch") || lower.endsWith(" gate")) {
count++;
}
}
return count;
}
/**
* Count cards of a given type on battlefield.
* Without a card database, we use name heuristics.
* TODO: Load card type data from Scryfall cache for accuracy.
*/
private int countType(List<String> battlefield, String type) {
// Without type data, return total non-land count as creature estimate
return battlefield.size() - countLands(battlefield);
}
/**
* Normalize Forge phase strings to our canonical names.
*/
private String normalizePhase(String forgePhase) {
String lower = forgePhase.toLowerCase();
if (lower.contains("main") && (lower.contains("1") || lower.contains("pre"))) {
return "main_1";
}
if (lower.contains("combat") || lower.contains("attack") || lower.contains("block") || lower.contains("damage")) {
return "combat";
}
if (lower.contains("main") && (lower.contains("2") || lower.contains("post"))) {
return "main_2";
}
if (lower.contains("end") || lower.contains("cleanup")) {
return "end";
}
return "main_1"; // Default
}
/**
* Get all extracted decisions (call after processGameLog).
*/
public List<DecisionSnapshot> getDecisions() {
return Collections.unmodifiableList(decisions);
}
}
@@ -0,0 +1,200 @@
package commanderailab.ml;
import commanderailab.schema.DecisionSnapshot;
import commanderailab.schema.JsonExporter;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
/**
* DecisionLogger — Writes decision snapshots to JSONL files for ML training.
*
* Each game's decisions are appended as JSON lines to a batch-specific file.
* Format: one DecisionSnapshot JSON object per line (JSONL/ndjson).
*
* Output path: results/ml-decisions-{batchId}.jsonl
*
* Usage from BatchRunner:
* DecisionLogger logger = new DecisionLogger(resultsDir, batchId);
* // After each game:
* logger.logGameDecisions(gameId, decisions, deckMeta);
* // After batch:
* logger.close();
*/
public class DecisionLogger {
private final Path outputPath;
private BufferedWriter writer;
private int totalDecisions = 0;
private int totalGames = 0;
/**
* @param resultsDir Directory to write JSONL files (e.g., "results")
* @param batchId Batch identifier for file naming
*/
public DecisionLogger(String resultsDir, String batchId) throws IOException {
Path dir = Path.of(resultsDir);
if (!Files.exists(dir)) {
Files.createDirectories(dir);
}
this.outputPath = dir.resolve("ml-decisions-" + batchId + ".jsonl");
this.writer = Files.newBufferedWriter(outputPath, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
System.out.println("[ML] Decision logger writing to: " + outputPath.toAbsolutePath());
}
/**
* Log all decisions from a single game.
*
* @param decisions Decision snapshots extracted from the game
* @param deckMeta Metadata to attach: {seatIndex → {deckName, commander, archetype}}
* @param gameOutcome "win_seat_0", "win_seat_1", "draw"
*/
public void logGameDecisions(List<DecisionSnapshot> decisions,
Map<Integer, Map<String, String>> deckMeta,
String gameOutcome) {
if (decisions == null || decisions.isEmpty()) return;
try {
for (DecisionSnapshot snap : decisions) {
// Serialize to JSON using our lightweight exporter
String json = serializeDecision(snap, deckMeta, gameOutcome);
writer.write(json);
writer.newLine();
totalDecisions++;
}
writer.flush();
totalGames++;
} catch (IOException e) {
System.err.println("[ML] Failed to write decisions: " + e.getMessage());
}
}
/**
* Serialize a DecisionSnapshot to a compact JSON string.
* Uses manual JSON building to avoid adding Gson/Jackson dependency.
*/
private String serializeDecision(DecisionSnapshot snap,
Map<Integer, Map<String, String>> deckMeta,
String gameOutcome) {
StringBuilder sb = new StringBuilder(2048);
sb.append("{");
// Game context
appendString(sb, "game_id", snap.gameId); sb.append(",");
appendInt(sb, "turn", snap.turnNumber); sb.append(",");
appendString(sb, "phase", snap.phase); sb.append(",");
appendInt(sb, "active_seat", snap.activeSeat); sb.append(",");
appendString(sb, "game_outcome", gameOutcome); sb.append(",");
// Deck metadata for active player
if (deckMeta != null && deckMeta.containsKey(snap.activeSeat)) {
Map<String, String> meta = deckMeta.get(snap.activeSeat);
sb.append("\"deck_name\":").append(jsonStr(meta.getOrDefault("name", ""))).append(",");
sb.append("\"commander\":").append(jsonStr(meta.getOrDefault("commander", ""))).append(",");
sb.append("\"archetype\":").append(jsonStr(meta.getOrDefault("archetype", "midrange"))).append(",");
}
// Players array
sb.append("\"players\":[");
for (int i = 0; i < snap.players.size(); i++) {
if (i > 0) sb.append(",");
serializePlayer(sb, snap.players.get(i));
}
sb.append("],");
// Action
sb.append("\"action\":{");
if (snap.action != null) {
appendString(sb, "type", snap.action.type); sb.append(",");
appendString(sb, "card", snap.action.cardName != null ? snap.action.cardName : ""); sb.append(",");
appendString(sb, "target", snap.action.targetDescription != null ? snap.action.targetDescription : ""); sb.append(",");
appendString(sb, "raw", truncate(snap.action.rawLogLine, 200));
}
sb.append("}");
sb.append("}");
return sb.toString();
}
private void serializePlayer(StringBuilder sb, DecisionSnapshot.PlayerSnapshot ps) {
sb.append("{");
appendInt(sb, "seat", ps.seatIndex); sb.append(",");
appendInt(sb, "life", ps.lifeTotal); sb.append(",");
appendInt(sb, "cmdr_dmg", ps.commanderDamageTaken); sb.append(",");
appendInt(sb, "mana", ps.manaAvailable); sb.append(",");
appendInt(sb, "cmdr_tax", ps.commanderTax); sb.append(",");
appendInt(sb, "creatures", ps.creaturesOnField); sb.append(",");
appendInt(sb, "lands", ps.landCount); sb.append(",");
// Zone card lists
sb.append("\"hand\":").append(jsonList(ps.hand)).append(",");
sb.append("\"battlefield\":").append(jsonList(ps.battlefield)).append(",");
sb.append("\"graveyard\":").append(jsonList(ps.graveyard)).append(",");
sb.append("\"command_zone\":").append(jsonList(ps.commandZone));
sb.append("}");
}
// ── JSON helpers ─────────────────────────────────────────
private void appendString(StringBuilder sb, String key, String value) {
sb.append("\"").append(key).append("\":").append(jsonStr(value));
}
private void appendInt(StringBuilder sb, String key, int value) {
sb.append("\"").append(key).append("\":").append(value);
}
private String jsonStr(String s) {
if (s == null) return "null";
return "\"" + s.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t") + "\"";
}
private String jsonList(List<String> items) {
if (items == null || items.isEmpty()) return "[]";
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < items.size(); i++) {
if (i > 0) sb.append(",");
sb.append(jsonStr(items.get(i)));
}
sb.append("]");
return sb.toString();
}
private String truncate(String s, int maxLen) {
if (s == null) return "";
return s.length() <= maxLen ? s : s.substring(0, maxLen);
}
/**
* Close the writer and print summary.
*/
public void close() {
try {
if (writer != null) {
writer.close();
}
System.out.printf("[ML] Decision log complete: %d decisions from %d games → %s%n",
totalDecisions, totalGames, outputPath.toAbsolutePath());
} catch (IOException e) {
System.err.println("[ML] Failed to close decision logger: " + e.getMessage());
}
}
public Path getOutputPath() {
return outputPath;
}
public int getTotalDecisions() {
return totalDecisions;
}
}
@@ -0,0 +1,269 @@
package commanderailab.ml;
import commanderailab.ai.AiPolicy;
import commanderailab.schema.DecisionSnapshot;
import java.util.*;
/**
* LearnedPolicy — AI policy backed by a trained neural network.
*
* Instead of using Forge's built-in heuristic AI, this policy queries
* the Python policy server (via PolicyServerClient) for macro-action
* decisions at each game decision point.
*
* The policy server runs the trained PolicyNetwork:
* game state → state encoder → neural network → macro-action
*
* If the policy server is unavailable, falls back to Forge's built-in AI.
*
* Usage:
* LearnedPolicy policy = new LearnedPolicy("http://localhost:8080");
* policy.setPlaystyle("aggro");
* policy.setGreedy(true);
*
* // In the game loop:
* DecisionSnapshot state = captureGameState();
* String macroAction = policy.decideAction(state);
* MacroActionExecutor.ActionResolution action =
* MacroActionExecutor.resolve(macroAction, hand, battlefield, ...);
*
* Integration with BatchRunner:
* When usesForgeBuiltinAi() returns false, the BatchRunner should
* intercept decisions and call decideAction() instead. For the
* initial version (Phase 7), this works alongside Forge's AI —
* the policy's decision is logged but Forge still executes the game.
* In Phase 8+, decisions will be fully intercepted.
*/
public class LearnedPolicy implements AiPolicy {
private final PolicyServerClient client;
private String playstyle;
private boolean greedy;
private boolean policyServerAvailable;
// Stats
private int totalQueries = 0;
private int successfulQueries = 0;
private int fallbackQueries = 0;
private long totalInferenceMs = 0;
// Cache the last prediction for logging
private PolicyServerClient.PolicyPrediction lastPrediction;
/**
* Create a learned policy connected to the lab API server.
*
* @param serverUrl Base URL (e.g., "http://localhost:8080")
*/
public LearnedPolicy(String serverUrl) {
this.client = new PolicyServerClient(serverUrl);
this.playstyle = "midrange";
this.greedy = true;
this.policyServerAvailable = false;
}
/**
* Create with explicit settings.
*/
public LearnedPolicy(String serverUrl, String playstyle, boolean greedy) {
this(serverUrl);
this.playstyle = playstyle;
this.greedy = greedy;
}
// ══════════════════════════════════════════════════════════
// Connection
// ══════════════════════════════════════════════════════════
/**
* Check if the policy server has a trained model loaded.
* Call this at startup to decide whether to use learned policy.
*/
public boolean connect() {
policyServerAvailable = client.isAvailable();
if (policyServerAvailable) {
System.out.println("[ML] Learned policy connected — server has model loaded");
} else {
System.out.println("[ML] Learned policy not available: " + client.getLastError());
System.out.println("[ML] Falling back to Forge built-in AI");
}
return policyServerAvailable;
}
/**
* Request the server to reload the model (after training).
*/
public boolean reloadModel() {
boolean ok = client.reloadModel();
if (ok) {
policyServerAvailable = true;
System.out.println("[ML] Model reloaded successfully");
}
return ok;
}
// ══════════════════════════════════════════════════════════
// Decision Making
// ══════════════════════════════════════════════════════════
/**
* Query the policy network for a macro-action decision.
*
* @param snapshot Current game state snapshot
* @return Macro-action name (e.g., "cast_creature"), or "pass" on failure
*/
public String decideAction(DecisionSnapshot snapshot) {
totalQueries++;
if (!policyServerAvailable) {
fallbackQueries++;
return MacroActionExecutor.PASS;
}
PolicyServerClient.PolicyPrediction pred = client.predict(snapshot, playstyle, greedy);
lastPrediction = pred;
if (pred.isValid()) {
successfulQueries++;
totalInferenceMs += (long) pred.inferenceMs;
return pred.action;
} else {
fallbackQueries++;
System.err.println("[ML] Prediction failed: " + pred.error);
return MacroActionExecutor.PASS;
}
}
/**
* Get the full prediction result for the last decision.
* Useful for logging probabilities alongside game actions.
*/
public PolicyServerClient.PolicyPrediction getLastPrediction() {
return lastPrediction;
}
/**
* Resolve the last decision to a concrete action.
* Convenience method that combines decideAction + MacroActionExecutor.
*/
public MacroActionExecutor.ActionResolution resolveAction(
DecisionSnapshot snapshot,
List<String> hand,
List<String> battlefield,
List<String> commandZone,
int manaAvailable,
String commanderName,
int commanderTax
) {
String macroAction = decideAction(snapshot);
return MacroActionExecutor.resolve(
macroAction, hand, battlefield, commandZone,
manaAvailable, commanderName, commanderTax
);
}
// ══════════════════════════════════════════════════════════
// AiPolicy Interface
// ══════════════════════════════════════════════════════════
@Override
public String getName() {
return "learned-policy";
}
@Override
public double getCardAdvantageWeight() {
// These weights are not used by the learned policy
// (the network learns its own weights)
return 0.5;
}
@Override
public double getTempoWeight() {
return 0.5;
}
@Override
public double getThreatScoringWeight() {
return 0.5;
}
@Override
public double getCombatWeight() {
return 0.5;
}
@Override
public boolean usesForgeBuiltinAi() {
// When policy server is not available, fall back to Forge AI
return !policyServerAvailable;
}
// ══════════════════════════════════════════════════════════
// Configuration
// ══════════════════════════════════════════════════════════
public void setPlaystyle(String playstyle) {
this.playstyle = playstyle;
}
public String getPlaystyle() {
return playstyle;
}
public void setGreedy(boolean greedy) {
this.greedy = greedy;
}
public boolean isGreedy() {
return greedy;
}
public boolean isPolicyServerAvailable() {
return policyServerAvailable;
}
// ══════════════════════════════════════════════════════════
// Stats
// ══════════════════════════════════════════════════════════
public int getTotalQueries() { return totalQueries; }
public int getSuccessfulQueries() { return successfulQueries; }
public int getFallbackQueries() { return fallbackQueries; }
public double getAverageInferenceMs() {
return successfulQueries > 0 ? (double) totalInferenceMs / successfulQueries : 0;
}
public double getSuccessRate() {
return totalQueries > 0 ? (double) successfulQueries / totalQueries : 0;
}
/**
* Get a summary of policy performance for logging.
*/
public String getStatsSummary() {
return String.format(
"LearnedPolicy[queries=%d, success=%d (%.1f%%), fallback=%d, avg_inference=%.1fms, style=%s, greedy=%s]",
totalQueries, successfulQueries,
getSuccessRate() * 100,
fallbackQueries, getAverageInferenceMs(),
playstyle, greedy
);
}
public void resetStats() {
totalQueries = 0;
successfulQueries = 0;
fallbackQueries = 0;
totalInferenceMs = 0;
}
@Override
public String toString() {
return String.format("LearnedPolicy[server=%s, available=%s, style=%s]",
policyServerAvailable ? "connected" : "disconnected",
policyServerAvailable, playstyle);
}
}
@@ -0,0 +1,287 @@
package commanderailab.ml;
import java.util.*;
/**
* MacroActionExecutor — Translates learned policy macro-actions into
* concrete Forge action descriptions.
*
* The policy network outputs one of 8 macro-actions. This class maps
* each macro-action to a heuristic that selects the best concrete
* Forge action from the available options.
*
* Macro-action space (matching ml/config/scope.py):
* 0: cast_creature — Play the best available creature from hand
* 1: cast_removal — Cast removal/interaction on biggest threat
* 2: cast_draw — Cast a card-draw or cantrip spell
* 3: cast_ramp — Cast a ramp spell or mana rock
* 4: cast_commander — Cast commander from command zone
* 5: attack_opponent — Attack with profitable attackers
* 6: hold_mana — Pass priority, keep mana open
* 7: pass — Pass with no action
*
* Integration:
* This is designed to work with Forge's game state. In Phase 8+,
* when we intercept Forge's decision loop, this class selects
* which concrete card/ability to use based on the macro-action.
*
* For now (Phase 7), it produces structured guidance that can be
* logged alongside the policy's decision for analysis.
*/
public class MacroActionExecutor {
// ── Macro-action constants (must match Python scope.py indices) ──
public static final String CAST_CREATURE = "cast_creature";
public static final String CAST_REMOVAL = "cast_removal";
public static final String CAST_DRAW = "cast_draw";
public static final String CAST_RAMP = "cast_ramp";
public static final String CAST_COMMANDER = "cast_commander";
public static final String ATTACK_OPPONENT = "attack_opponent";
public static final String HOLD_MANA = "hold_mana";
public static final String PASS = "pass";
/** All valid macro-action names in index order. */
public static final List<String> ALL_ACTIONS = List.of(
CAST_CREATURE, CAST_REMOVAL, CAST_DRAW, CAST_RAMP,
CAST_COMMANDER, ATTACK_OPPONENT, HOLD_MANA, PASS
);
// ── Known card role databases (matching Python labeler.py) ────────
private static final Set<String> REMOVAL_CARDS = Set.of(
"Swords to Plowshares", "Path to Exile", "Beast Within", "Chaos Warp",
"Counterspell", "Swan Song", "Cyclonic Rift", "Blasphemous Act",
"Wrath of God", "Generous Gift", "Terminate", "Go for the Throat",
"Doom Blade", "Rapid Hybridization", "Vandalblast", "Krosan Grip",
"Anguished Unmaking", "Vindicate", "Toxic Deluge", "Damnation",
"Supreme Verdict", "Austere Command", "Farewell", "Deadly Rollick",
"Force of Will", "Mana Drain", "Pongify", "Reality Shift",
"Ravenform", "Abrade", "Lightning Bolt", "Generous Gift"
);
private static final Set<String> DRAW_CARDS = Set.of(
"Rhystic Study", "Mystic Remora", "Harmonize", "Brainstorm",
"Ponder", "Preordain", "Night's Whisper", "Sign in Blood",
"Phyrexian Arena", "Sylvan Library", "Skullclamp", "Read the Bones",
"Blue Sun's Zenith", "Fact or Fiction", "Dig Through Time",
"Treasure Cruise", "Damnable Pact", "Pull from Tomorrow",
"Guardian Project", "Beast Whisperer", "Toski, Bearer of Secrets"
);
private static final Set<String> RAMP_CARDS = Set.of(
"Sol Ring", "Arcane Signet", "Cultivate", "Kodama's Reach",
"Rampant Growth", "Farseek", "Mind Stone", "Commander's Sphere",
"Fellwar Stone", "Thought Vessel", "Nature's Lore", "Solemn Simulacrum",
"Sakura-Tribe Elder", "Birds of Paradise", "Llanowar Elves",
"Elvish Mystic", "Mana Crypt", "Chrome Mox", "Mox Diamond",
"Jeweled Lotus", "Dockside Extortionist", "Smothering Tithe",
"Talismans", "Signets", "Three Visits", "Skyshroud Claim"
);
// ══════════════════════════════════════════════════════════
// Action Execution Result
// ══════════════════════════════════════════════════════════
/**
* Result of resolving a macro-action to a concrete action.
*/
public static class ActionResolution {
/** The original macro-action from the policy */
public String macroAction;
/** The concrete card to play (null for attack/hold/pass) */
public String selectedCard;
/** A description of what to do */
public String description;
/** Whether this action is actually executable right now */
public boolean executable;
/** Fallback macro-action if this one isn't executable */
public String fallbackAction;
public ActionResolution(String macroAction, String card, String desc, boolean executable) {
this.macroAction = macroAction;
this.selectedCard = card;
this.description = desc;
this.executable = executable;
}
@Override
public String toString() {
return String.format("[%s] %s → %s (%s)",
macroAction, selectedCard != null ? selectedCard : "-",
description, executable ? "OK" : "FALLBACK→" + fallbackAction);
}
}
// ══════════════════════════════════════════════════════════
// Resolution Logic
// ══════════════════════════════════════════════════════════
/**
* Resolve a macro-action to a concrete action given the current game state.
*
* @param macroAction The macro-action name from the policy (e.g., "cast_creature")
* @param hand Cards in the active player's hand
* @param battlefield Cards on the active player's battlefield
* @param commandZone Cards in the command zone
* @param manaAvailable Available mana
* @param commanderName The player's commander name
* @param commanderTax Commander tax amount
* @return ActionResolution with the concrete action to take
*/
public static ActionResolution resolve(
String macroAction,
List<String> hand,
List<String> battlefield,
List<String> commandZone,
int manaAvailable,
String commanderName,
int commanderTax
) {
return switch (macroAction) {
case CAST_CREATURE -> resolveCastCreature(hand, manaAvailable);
case CAST_REMOVAL -> resolveCastRemoval(hand, manaAvailable);
case CAST_DRAW -> resolveCastDraw(hand, manaAvailable);
case CAST_RAMP -> resolveCastRamp(hand, manaAvailable);
case CAST_COMMANDER -> resolveCastCommander(commandZone, commanderName, commanderTax, manaAvailable);
case ATTACK_OPPONENT -> resolveAttack(battlefield);
case HOLD_MANA -> new ActionResolution(HOLD_MANA, null, "Hold mana open, pass priority", true);
case PASS -> new ActionResolution(PASS, null, "Pass with no action", true);
default -> new ActionResolution(macroAction, null, "Unknown macro-action", false);
};
}
private static ActionResolution resolveCastCreature(List<String> hand, int mana) {
// Find castable creatures (those not in removal/draw/ramp databases)
List<String> creatures = new ArrayList<>();
for (String card : hand) {
if (!isRemoval(card) && !isDraw(card) && !isRamp(card)) {
creatures.add(card);
}
}
if (creatures.isEmpty()) {
ActionResolution r = new ActionResolution(CAST_CREATURE, null,
"No creatures in hand", false);
r.fallbackAction = HOLD_MANA;
return r;
}
// Pick a creature (heuristic: prefer variety, first one found)
String pick = creatures.get(0);
return new ActionResolution(CAST_CREATURE, pick,
"Cast creature: " + pick, true);
}
private static ActionResolution resolveCastRemoval(List<String> hand, int mana) {
for (String card : hand) {
if (isRemoval(card)) {
return new ActionResolution(CAST_REMOVAL, card,
"Cast removal: " + card, true);
}
}
ActionResolution r = new ActionResolution(CAST_REMOVAL, null,
"No removal in hand", false);
r.fallbackAction = HOLD_MANA;
return r;
}
private static ActionResolution resolveCastDraw(List<String> hand, int mana) {
for (String card : hand) {
if (isDraw(card)) {
return new ActionResolution(CAST_DRAW, card,
"Cast draw spell: " + card, true);
}
}
ActionResolution r = new ActionResolution(CAST_DRAW, null,
"No draw spells in hand", false);
r.fallbackAction = HOLD_MANA;
return r;
}
private static ActionResolution resolveCastRamp(List<String> hand, int mana) {
for (String card : hand) {
if (isRamp(card)) {
return new ActionResolution(CAST_RAMP, card,
"Cast ramp: " + card, true);
}
}
ActionResolution r = new ActionResolution(CAST_RAMP, null,
"No ramp in hand", false);
r.fallbackAction = HOLD_MANA;
return r;
}
private static ActionResolution resolveCastCommander(
List<String> commandZone, String commanderName, int tax, int mana) {
if (commandZone == null || commandZone.isEmpty() ||
!commandZone.contains(commanderName)) {
ActionResolution r = new ActionResolution(CAST_COMMANDER, null,
"Commander not in command zone", false);
r.fallbackAction = HOLD_MANA;
return r;
}
// Rough mana check (commander cost is ~4-6 average + tax)
int estimatedCost = 4 + tax;
if (mana < estimatedCost) {
ActionResolution r = new ActionResolution(CAST_COMMANDER, commanderName,
"Insufficient mana for commander (need ~" + estimatedCost + ", have " + mana + ")", false);
r.fallbackAction = HOLD_MANA;
return r;
}
return new ActionResolution(CAST_COMMANDER, commanderName,
"Cast commander: " + commanderName + " (tax=" + tax + ")", true);
}
private static ActionResolution resolveAttack(List<String> battlefield) {
if (battlefield == null || battlefield.isEmpty()) {
ActionResolution r = new ActionResolution(ATTACK_OPPONENT, null,
"No creatures on battlefield to attack with", false);
r.fallbackAction = PASS;
return r;
}
return new ActionResolution(ATTACK_OPPONENT, null,
"Attack with " + battlefield.size() + " permanent(s)", true);
}
// ── Card role checks ────────────────────────────────────
private static boolean isRemoval(String card) {
return REMOVAL_CARDS.contains(card);
}
private static boolean isDraw(String card) {
return DRAW_CARDS.contains(card);
}
private static boolean isRamp(String card) {
return RAMP_CARDS.contains(card);
}
/**
* Get the macro-action name from an index (matching Python IDX_TO_ACTION).
*/
public static String actionNameFromIndex(int index) {
if (index >= 0 && index < ALL_ACTIONS.size()) {
return ALL_ACTIONS.get(index);
}
return PASS;
}
/**
* Get the index from a macro-action name.
*/
public static int indexFromActionName(String name) {
int idx = ALL_ACTIONS.indexOf(name);
return idx >= 0 ? idx : 7; // default to PASS
}
}
@@ -0,0 +1,282 @@
package commanderailab.ml;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import commanderailab.schema.DecisionSnapshot;
/**
* PolicyServerClient — HTTP client for the Python policy inference server.
*
* Sends game state snapshots to POST /api/ml/predict and receives
* macro-action predictions from the trained PolicyNetwork.
*
* The client is designed to be lightweight and uses only java.net.HttpURLConnection
* (no additional dependencies beyond Gson for JSON serialization).
*
* Usage:
* PolicyServerClient client = new PolicyServerClient("http://localhost:8080");
* if (client.isAvailable()) {
* PolicyPrediction pred = client.predict(snapshot, "aggro", true);
* System.out.println("Action: " + pred.action);
* }
*/
public class PolicyServerClient {
private static final Gson GSON = new GsonBuilder().create();
private static final int CONNECT_TIMEOUT_MS = 2000;
private static final int READ_TIMEOUT_MS = 5000;
private final String baseUrl;
private volatile boolean available = false;
private volatile String lastError = "";
/**
* @param baseUrl Base URL of the lab API server (e.g., "http://localhost:8080")
*/
public PolicyServerClient(String baseUrl) {
this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
}
// ══════════════════════════════════════════════════════════
// Prediction Response
// ══════════════════════════════════════════════════════════
/**
* Result of a policy prediction.
*/
public static class PolicyPrediction {
/** Macro-action name (e.g., "cast_creature", "attack_opponent") */
public String action;
/** Action index (0-7) */
public int actionIndex;
/** Model confidence for the chosen action (0.0 - 1.0) */
public double confidence;
/** Full probability distribution over all actions */
public Map<String, Double> probabilities;
/** Inference time in milliseconds */
public double inferenceMs;
/** Error message if prediction failed */
public String error;
public boolean isValid() {
return action != null && !action.isEmpty() && error == null;
}
@Override
public String toString() {
if (error != null) return "PolicyPrediction[error=" + error + "]";
return String.format("PolicyPrediction[action=%s, conf=%.3f, %.1fms]",
action, confidence, inferenceMs);
}
}
// ══════════════════════════════════════════════════════════
// Model Status
// ══════════════════════════════════════════════════════════
public static class ModelStatus {
public boolean loaded;
public String error;
public String device;
public boolean torchAvailable;
}
// ══════════════════════════════════════════════════════════
// API Methods
// ══════════════════════════════════════════════════════════
/**
* Check if the policy server has a model loaded and ready.
*/
public boolean isAvailable() {
try {
String json = httpGet(baseUrl + "/api/ml/model");
ModelStatus status = GSON.fromJson(json, ModelStatus.class);
available = status.loaded;
if (!available) {
lastError = status.error != null ? status.error : "Model not loaded";
}
return available;
} catch (Exception e) {
available = false;
lastError = e.getMessage();
return false;
}
}
/**
* Predict a macro-action from a DecisionSnapshot.
*
* @param snapshot DecisionSnapshot object (will be serialized to JSON)
* @param playstyle Deck playstyle: "aggro", "control", "midrange", "combo"
* @param greedy If true, always pick the highest-probability action
* @return PolicyPrediction with the recommended action
*/
public PolicyPrediction predict(DecisionSnapshot snapshot, String playstyle, boolean greedy) {
try {
// Build request JSON from the snapshot
JsonObject request = buildPredictRequest(snapshot, playstyle, greedy);
String responseJson = httpPost(baseUrl + "/api/ml/predict", request.toString());
return GSON.fromJson(responseJson, PolicyPrediction.class);
} catch (Exception e) {
PolicyPrediction fail = new PolicyPrediction();
fail.error = e.getMessage();
lastError = e.getMessage();
return fail;
}
}
/**
* Predict with default settings (midrange playstyle, greedy).
*/
public PolicyPrediction predict(DecisionSnapshot snapshot) {
return predict(snapshot, "midrange", true);
}
/**
* Request the server to reload the model checkpoint.
* Useful after training a new model.
*/
public boolean reloadModel() {
try {
String json = httpPost(baseUrl + "/api/ml/reload", "{}");
JsonObject resp = JsonParser.parseString(json).getAsJsonObject();
return resp.has("success") && resp.get("success").getAsBoolean();
} catch (Exception e) {
lastError = e.getMessage();
return false;
}
}
/**
* Get the last error message.
*/
public String getLastError() {
return lastError;
}
// ══════════════════════════════════════════════════════════
// Request Building
// ══════════════════════════════════════════════════════════
/**
* Convert a DecisionSnapshot + inference params into the JSON body
* expected by POST /api/ml/predict.
*/
private JsonObject buildPredictRequest(DecisionSnapshot snapshot, String playstyle, boolean greedy) {
// Serialize the snapshot to JSON, then add inference params
String snapshotJson = GSON.toJson(snapshot);
JsonObject obj = JsonParser.parseString(snapshotJson).getAsJsonObject();
// Map Java field names to Python expected names
if (obj.has("turnNumber")) {
obj.addProperty("turn", obj.get("turnNumber").getAsInt());
obj.remove("turnNumber");
}
if (obj.has("activeSeat")) {
obj.addProperty("active_seat", obj.get("activeSeat").getAsInt());
obj.remove("activeSeat");
}
if (obj.has("gameId")) {
obj.addProperty("game_id", obj.get("gameId").getAsString());
obj.remove("gameId");
}
// Remap player fields from camelCase to snake_case
if (obj.has("players") && obj.get("players").isJsonArray()) {
for (var player : obj.getAsJsonArray("players")) {
if (!player.isJsonObject()) continue;
JsonObject p = player.getAsJsonObject();
renameField(p, "seatIndex", "seat");
renameField(p, "lifeTotal", "life");
renameField(p, "commanderDamageTaken", "cmdr_dmg");
renameField(p, "manaAvailable", "mana");
renameField(p, "commanderTax", "cmdr_tax");
renameField(p, "creaturesOnField", "creatures");
renameField(p, "commandZone", "command_zone");
renameField(p, "landCount", "lands");
}
}
// Add inference parameters
obj.addProperty("archetype", playstyle);
obj.addProperty("greedy", greedy);
obj.addProperty("temperature", 1.0);
return obj;
}
private void renameField(JsonObject obj, String from, String to) {
if (obj.has(from)) {
obj.add(to, obj.get(from));
obj.remove(from);
}
}
// ══════════════════════════════════════════════════════════
// HTTP Helpers
// ══════════════════════════════════════════════════════════
private String httpGet(String url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(CONNECT_TIMEOUT_MS);
conn.setReadTimeout(READ_TIMEOUT_MS);
conn.setRequestProperty("Accept", "application/json");
int code = conn.getResponseCode();
if (code != 200) {
String errorBody = readStream(conn.getErrorStream());
throw new IOException("HTTP " + code + ": " + errorBody);
}
return readStream(conn.getInputStream());
}
private String httpPost(String url, String jsonBody) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(CONNECT_TIMEOUT_MS);
conn.setReadTimeout(READ_TIMEOUT_MS);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
try (OutputStream os = conn.getOutputStream()) {
os.write(jsonBody.getBytes(StandardCharsets.UTF_8));
}
int code = conn.getResponseCode();
if (code != 200) {
String errorBody = readStream(conn.getErrorStream());
throw new IOException("HTTP " + code + ": " + errorBody);
}
return readStream(conn.getInputStream());
}
private String readStream(InputStream stream) throws IOException {
if (stream == null) return "";
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(stream, StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
}
}
@@ -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);
}
}
@@ -0,0 +1,101 @@
package commanderailab.stats;
import commanderailab.schema.BatchResult;
import commanderailab.schema.BatchResult.*;
import java.util.*;
/**
* StatsAggregator — Computes summary statistics from a list of GameResults.
*
* Thread-safe: call mergeStats() to combine results from multiple workers.
*/
public class StatsAggregator {
/**
* Compute summary from completed games.
*/
public static Summary computeSummary(List<GameResult> games, List<DeckInfo> decks, long totalElapsedMs) {
Summary summary = new Summary();
summary.perDeck = new ArrayList<>();
int podSize = decks.size();
// Initialize per-deck accumulators
int[] wins = new int[podSize];
int[] losses = new int[podSize];
int[] draws = new int[podSize];
long[] totalTurnsOnWin = new long[podSize];
long[] totalMulligans = new long[podSize];
long[] totalFinalLife = new long[podSize];
int[] gameCount = new int[podSize];
WinConditionBreakdown[] breakdowns = new WinConditionBreakdown[podSize];
for (int i = 0; i < podSize; i++) {
breakdowns[i] = new WinConditionBreakdown();
}
long totalTurnsAllGames = 0;
long totalGameTimeMs = 0;
for (GameResult game : games) {
totalTurnsAllGames += game.totalTurns;
totalGameTimeMs += game.elapsedMs;
for (PlayerResult pr : game.playerResults) {
int seat = pr.seatIndex;
gameCount[seat]++;
totalMulligans[seat] += pr.mulligans;
totalFinalLife[seat] += pr.finalLife;
if (pr.isWinner) {
wins[seat]++;
totalTurnsOnWin[seat] += game.totalTurns;
breakdowns[seat].increment(game.winCondition);
} else if (game.winningSeat == null) {
draws[seat]++;
} else {
losses[seat]++;
}
}
}
int completedGames = games.size();
for (int i = 0; i < podSize; i++) {
DeckSummary ds = new DeckSummary();
ds.seatIndex = i;
ds.deckName = decks.get(i).deckName;
ds.wins = wins[i];
ds.losses = losses[i];
ds.draws = draws[i];
ds.winRate = completedGames > 0 ? (double) wins[i] / completedGames : 0.0;
ds.avgTurnsToWin = wins[i] > 0 ? (double) totalTurnsOnWin[i] / wins[i] : null;
ds.avgMulligans = gameCount[i] > 0 ? (double) totalMulligans[i] / gameCount[i] : 0.0;
ds.avgFinalLife = gameCount[i] > 0 ? (double) totalFinalLife[i] / gameCount[i] : 0.0;
ds.winConditionBreakdown = breakdowns[i];
summary.perDeck.add(ds);
}
summary.avgGameTurns = completedGames > 0 ? (double) totalTurnsAllGames / completedGames : 0.0;
summary.avgGameTimeMs = completedGames > 0 ? (double) totalGameTimeMs / completedGames : 0.0;
summary.simsPerSecond = totalElapsedMs > 0 ? (double) completedGames / (totalElapsedMs / 1000.0) : 0.0;
return summary;
}
/**
* Merge game results from multiple worker threads into a single list.
* Thread-safe: each worker produces its own list; this combines them.
*/
public static List<GameResult> mergeStats(List<List<GameResult>> workerResults) {
List<GameResult> merged = new ArrayList<>();
for (List<GameResult> batch : workerResults) {
merged.addAll(batch);
}
// Re-index games sequentially
for (int i = 0; i < merged.size(); i++) {
merged.get(i).gameIndex = i;
}
return merged;
}
}