From 126684bb9423d9b9594b1ed473e16a07a5f360e7 Mon Sep 17 00:00:00 2001 From: KoalaTrapLord <265133236+KoalaTrapLord@users.noreply.github.com> Date: Sun, 29 Mar 2026 04:31:49 -0400 Subject: [PATCH] =?UTF-8?q?feat(bridge):=20Phase=202.3=20=E2=80=94=20wire?= =?UTF-8?q?=20GameSession=20to=20real=20Forge=20IPC=20subprocess=20(issue?= =?UTF-8?q?=20#83)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replaces synthetic stub loop with a live Forge process: - Spawns Forge with --policy + --policyServer flags so Forge calls back to /api/policy/decide at each AI decision point - Reads Forge stdout line-by-line and parses zone/phase/life updates via the same regex patterns used in BatchRunner - Syncs full board state (battlefield, hand, graveyard, exile, command zone, stack) on every Forge state-change line - Routes human input from humanActionQueue via a side-channel HTTP POST to /api/policy/override on the policy server - Handles activePlayer + priorityPlayer correctly for 3-4 player pods - Falls back to synthetic stub loop if Forge subprocess fails to start - Watchdog thread kills stalled Forge process after 10 min --- .../commanderailab/bridge/GameSession.java | 1026 ++++++++++------- 1 file changed, 641 insertions(+), 385 deletions(-) diff --git a/src/main/java/commanderailab/bridge/GameSession.java b/src/main/java/commanderailab/bridge/GameSession.java index f0a485f..e2ecd2f 100644 --- a/src/main/java/commanderailab/bridge/GameSession.java +++ b/src/main/java/commanderailab/bridge/GameSession.java @@ -2,425 +2,720 @@ package commanderailab.bridge; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import commanderailab.ai.PolicyClient; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; import java.util.*; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; +import java.util.regex.*; /** - * GameSession — holds state for one live interactive Commander game. + * GameSession — Phase 2.3: real Forge IPC for live interactive Commander games. * - * PHASE 2: integrates PolicyClient for bidirectional sync between - * the Java game loop and the Python policy server. + * Architecture: + * 1. Spawns a Forge subprocess with {@code --policy midrange --policyServer } + * so Forge calls POST /api/policy/decide at every AI decision point. + * 2. Reads Forge stdout line-by-line to track zone contents, life totals, + * phase transitions, and game outcome. + * 3. Human actions (seat 0) are intercepted before Forge asks; the session + * waits on {@code humanActionQueue}, converts the action to the + * macro-action string expected by /api/policy/decide, and injects it + * via POST /api/policy/override so the policy server returns it. + * 4. Publishes a full state snapshot to the WebSocket frontend after every + * meaningful Forge output event. + * 5. Falls back to the synthetic stub loop if Forge cannot be started + * (e.g., missing JAR, wrong Java version). * - * AI turns now consult the policy server for macro-action decisions - * instead of using random stub logic. + * Zone sync model: + * Forge verbose log lines are parsed with the same regex patterns used + * in BatchRunner. Each recognised event mutates the mutable per-seat + * zone lists; the snapshot is rebuilt and pushed on every change. * - * STATE VECTOR (Issue #83 Step 1) - * buildStateVector(seat) emits a float[29] global scalar block that - * matches the STATE_DIMS layout defined in ml/config/scope.py: - * - * Per-player block — 14 features × 2 players = 28 floats - * indices [0..13] = active seat ("self") - * indices [14..27] = averaged opponent seats - * index [28] = turn_number / MAX_TURNS - * - * Per-player feature layout (offset 0 within each block): - * [0] life_total / 40.0 - * [1] commander_damage / 21.0 (stub 0.0 — wire from Forge in Step 4) - * [2] mana_available / 20.0 (stub 0.0 — wire from Forge in Step 4) - * [3] commander_tax / 10.0 - * [4] cards_in_hand / 15.0 - * [5] cards_in_graveyard / 100.0 - * [6] creatures_on_battlefield / 30.0 - * [7] total_power_on_board / 100.0 (stub = creature count — wire P/T in Step 4) - * [8] is_active_player (0.0 or 1.0) - * [9] phase_onehot[main1] (0.0 or 1.0) - * [10] phase_onehot[combat] (0.0 or 1.0) - * [11] phase_onehot[main2] (0.0 or 1.0) - * [12] phase_onehot[end] (0.0 or 1.0) - * [13] (reserved / padding — always 0.0) - * - * buildStateSnapshot() appends "state_vector": [...] so PolicyClient - * sends a machine-readable vector directly usable by the Python encoder - * without re-parsing nested human-readable fields. + * Phase 2.3 — Issue #83 */ public class GameSession { + // ---------------------------------------------------------------- + // Constants + // ---------------------------------------------------------------- + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + private static final int STALL_LIMIT_SECONDS = 600; // 10 min + private static final int HUMAN_TIMEOUT_SECONDS = 120; + private static final String DEFAULT_POLICY_SERVER = "http://localhost:8080"; + + // Forge verbose-log regex (mirror of BatchRunner patterns) + private static final Pattern P_TURN = + Pattern.compile("Turn\\s+(\\d+)\\s+\\(Ai\\(?(\\d+)\\)?", Pattern.CASE_INSENSITIVE); + private static final Pattern P_PHASE = + Pattern.compile("Phase:\\s*(.+)", Pattern.CASE_INSENSITIVE); + private static final Pattern P_LIFE_CHANGE = + Pattern.compile("Life:\\s*Life:\\s*Ai\\(?(\\d+)\\)?-.+?\\s+(\\d+)\\s*>\\s*(-?\\d+)"); + private static final Pattern P_LIFE_NOW = + Pattern.compile("Ai\\(?(\\d+)\\)?-.+?'s\\s+life(?:\\s+total)?\\s+is\\s+now\\s+(-?\\d+)", Pattern.CASE_INSENSITIVE); + private static final Pattern P_CAST = + Pattern.compile("(?:Add To Stack:\\s*)?Ai\\(?(\\d+)\\)?-[^\\s].*?\\s+casts?\\s+(.+?)(?:\\s+targeting.*)?$", Pattern.CASE_INSENSITIVE); + private static final Pattern P_LAND = + Pattern.compile("(?:Land:\\s*)?Ai\\(?(\\d+)\\)?-[^\\s].*?\\s+play(?:s|ed)\\s+(.+?)(?:\\s+\\(\\d+\\))?(?:\\.|$)", Pattern.CASE_INSENSITIVE); + private static final Pattern P_ZONE_BF = + Pattern.compile("Zone Change:\\s*(.+?)\\s+(?:\\(\\d+\\)\\s+)?was put into Battlefield", Pattern.CASE_INSENSITIVE); + private static final Pattern P_ZONE_GY = + Pattern.compile("Zone Change:\\s*(.+?)\\s+(?:\\(\\d+\\)\\s+)?was put into Graveyard", Pattern.CASE_INSENSITIVE); + private static final Pattern P_ZONE_EXILE = + Pattern.compile("Zone Change:\\s*(.+?)\\s+(?:\\(\\d+\\)\\s+)?was put into Exile", Pattern.CASE_INSENSITIVE); + private static final Pattern P_WINNER = + Pattern.compile("Game Outcome:\\s*Ai\\(?(\\d+)\\)?-.+?\\s+has won", Pattern.CASE_INSENSITIVE); + private static final Pattern P_LOSER = + Pattern.compile("Game Outcome:\\s*Ai\\(?(\\d+)\\)?-.+?\\s+has lost", Pattern.CASE_INSENSITIVE); + private static final Pattern P_PRIORITY = + Pattern.compile("Priority:\\s*Ai\\(?(\\d+)\\)?", Pattern.CASE_INSENSITIVE); + private static final Pattern P_STACK_ADD = + Pattern.compile("Stack:\\s*(.+?)\\s+added to stack", Pattern.CASE_INSENSITIVE); + private static final Pattern P_STACK_RESOLVE = + Pattern.compile("Stack:\\s*(.+?)\\s+resolves", Pattern.CASE_INSENSITIVE); + private static final Pattern P_HAND_ADD = + Pattern.compile("Hand:\\s*Ai\\(?(\\d+)\\)?-.+?\\s+adds?\\s+(.+?)\\s+to hand", Pattern.CASE_INSENSITIVE); + private static final Pattern P_HAND_REMOVE = + Pattern.compile("Hand:\\s*Ai\\(?(\\d+)\\)?-.+?\\s+removes?\\s+(.+?)\\s+from hand", Pattern.CASE_INSENSITIVE); + private static final Pattern P_CMDR_TAX = + Pattern.compile("Ai\\(?(\\d+)\\)?.*?commander tax.*?(\\d+)", Pattern.CASE_INSENSITIVE); + private static final Pattern P_GAME_RESULT = + Pattern.compile("Game Result:\\s*Game\\s+(\\d+)\\s+ended in\\s+(\\d+)\\s*ms"); // ---------------------------------------------------------------- - // State vector constants — must mirror ml/config/scope.py STATE_DIMS + // Configuration // ---------------------------------------------------------------- - private static final int PER_PLAYER_FEATURES = 14; - private static final int NUM_PLAYERS_IN_VECTOR = 2; // self + opponents - private static final int GLOBAL_SCALAR_DIM = PER_PLAYER_FEATURES * NUM_PLAYERS_IN_VECTOR + 1; // 29 - private static final float MAX_LIFE = 40.0f; - private static final float MAX_COMMANDER_DAMAGE = 21.0f; - private static final float MAX_MANA = 20.0f; - private static final float MAX_COMMANDER_TAX = 10.0f; - private static final float MAX_HAND = 15.0f; - private static final float MAX_GRAVEYARD = 100.0f; - private static final float MAX_CREATURES = 30.0f; - private static final float MAX_POWER = 100.0f; - private static final float MAX_TURNS = 25.0f; - - // Phase name → one-hot index (matches PHASE_TO_IDX in scope.py) - private static final Map PHASE_ONEHOT_IDX; - static { - PHASE_ONEHOT_IDX = new HashMap<>(); - PHASE_ONEHOT_IDX.put("MAIN1", 0); - PHASE_ONEHOT_IDX.put("BEGIN_COMBAT", 1); - PHASE_ONEHOT_IDX.put("DECLARE_ATTACKERS", 1); - PHASE_ONEHOT_IDX.put("DECLARE_BLOCKERS", 1); - PHASE_ONEHOT_IDX.put("DAMAGE", 1); - PHASE_ONEHOT_IDX.put("END_COMBAT", 1); - PHASE_ONEHOT_IDX.put("MAIN2", 2); - PHASE_ONEHOT_IDX.put("END", 3); - PHASE_ONEHOT_IDX.put("CLEANUP", 3); - // UNTAP, UPKEEP, DRAW all map to no active slot (all zeros) - } private final List deckNames; + private final List deckFiles; private final Long seed; private final String forgeJarPath; private final String forgeWorkDir; + private final String javaPath; private final BlockingQueue humanActionQueue; private final PolicyClient policyClient; + private final String policyServerUrl; + private final int clockSeconds; + + // ---------------------------------------------------------------- + // Mutable game state (updated by Forge log parser) + // ---------------------------------------------------------------- private volatile boolean running = false; private volatile int turnNumber = 1; + private volatile String phase = "UNTAP"; + private volatile int activePlayer = 0; + private volatile int priorityPlayer = 0; + private volatile boolean awaitingHumanInput = false; + private volatile Integer winningSeat = null; + private volatile boolean gameOver = false; + private volatile long elapsedMs = 0; - // Mutable game state - private String phase = "UNTAP"; - private int activePlayer = 0; - private int priorityPlayer = 0; + private final int numSeats; private final int[] life; private final int[] poison; + private final int[] commanderTax; private final List[] hands; private final List[] battlefields; private final List[] graveyards; + private final List[] exiles; private final List[] commandZones; - private final int[] commanderTax; - private boolean awaitingHumanInput = false; + private final List stack = new ArrayList<>(); + private final List logLines = new ArrayList<>(); - private static final String[] PHASES = { - "UNTAP", "UPKEEP", "DRAW", - "MAIN1", "BEGIN_COMBAT", "DECLARE_ATTACKERS", - "DECLARE_BLOCKERS", "DAMAGE", "END_COMBAT", - "MAIN2", "END", "CLEANUP" - }; - private int phaseIndex = 0; + // ---------------------------------------------------------------- + // Internal machinery + // ---------------------------------------------------------------- + + private Process forgeProcess; + private final AtomicBoolean forgeFailed = new AtomicBoolean(false); + private final AtomicInteger lastActivityEpoch = new AtomicInteger(0); + + // ---------------------------------------------------------------- + // Constructors + // ---------------------------------------------------------------- @SuppressWarnings("unchecked") - public GameSession(List deckNames, Long seed, - String forgeJarPath, String forgeWorkDir, - BlockingQueue humanActionQueue) { - this(deckNames, seed, forgeJarPath, forgeWorkDir, humanActionQueue, - new PolicyClient("http://localhost:8080")); + public GameSession( + List deckNames, + Long seed, + String forgeJarPath, + String forgeWorkDir, + BlockingQueue humanActionQueue + ) { + this(deckNames, deckNames, seed, forgeJarPath, forgeWorkDir, + "java", humanActionQueue, + new PolicyClient(DEFAULT_POLICY_SERVER), + DEFAULT_POLICY_SERVER, 300); } @SuppressWarnings("unchecked") - public GameSession(List deckNames, Long seed, - String forgeJarPath, String forgeWorkDir, - BlockingQueue humanActionQueue, - PolicyClient policyClient) { - this.deckNames = deckNames; + public GameSession( + List deckNames, + Long seed, + String forgeJarPath, + String forgeWorkDir, + BlockingQueue humanActionQueue, + PolicyClient policyClient + ) { + this(deckNames, deckNames, seed, forgeJarPath, forgeWorkDir, + "java", humanActionQueue, policyClient, + DEFAULT_POLICY_SERVER, 300); + } + + @SuppressWarnings("unchecked") + public GameSession( + List deckNames, + List deckFiles, + Long seed, + String forgeJarPath, + String forgeWorkDir, + String javaPath, + BlockingQueue humanActionQueue, + PolicyClient policyClient, + String policyServerUrl, + int clockSeconds + ) { + this.deckNames = new ArrayList<>(deckNames); + this.deckFiles = new ArrayList<>(deckFiles); this.seed = seed; this.forgeJarPath = forgeJarPath; this.forgeWorkDir = forgeWorkDir; + this.javaPath = (javaPath != null && !javaPath.isEmpty()) ? javaPath : "java"; this.humanActionQueue = humanActionQueue; this.policyClient = policyClient; + this.policyServerUrl = policyServerUrl; + this.clockSeconds = clockSeconds; + this.numSeats = Math.min(deckNames.size(), 4); - int seats = Math.min(deckNames.size(), 4); - life = new int[seats]; - poison = new int[seats]; - hands = new List[seats]; - battlefields = new List[seats]; - graveyards = new List[seats]; - commandZones = new List[seats]; - commanderTax = new int[seats]; + life = new int[numSeats]; + poison = new int[numSeats]; + commanderTax = new int[numSeats]; + hands = new List[numSeats]; + battlefields = new List[numSeats]; + graveyards = new List[numSeats]; + exiles = new List[numSeats]; + commandZones = new List[numSeats]; - for (int i = 0; i < seats; i++) { + for (int i = 0; i < numSeats; i++) { life[i] = 40; - hands[i] = new ArrayList<>(List.of( - "card_stub_1", "card_stub_2", "card_stub_3", - "card_stub_4", "card_stub_5", "card_stub_6", "card_stub_7" - )); + hands[i] = new ArrayList<>(); battlefields[i] = new ArrayList<>(); graveyards[i] = new ArrayList<>(); - commandZones[i] = new ArrayList<>(List.of(deckNames.get(i) + "_commander")); + exiles[i] = new ArrayList<>(); + commandZones[i] = new ArrayList<>(List.of( + (i < deckNames.size() ? deckNames.get(i) : "Unknown") + " (Commander)" + )); } } - public boolean isRunning() { return running; } - public int getTurnNumber() { return turnNumber; } - public void stop() { running = false; } + // ---------------------------------------------------------------- + // Public accessors + // ---------------------------------------------------------------- - // ================================================================ - // Game loop - // ================================================================ + public boolean isRunning() { return running; } + public int getTurnNumber() { return turnNumber; } + public String getPhase() { return phase; } + public Integer getWinningSeat() { return winningSeat; } + public List getLog() { return Collections.unmodifiableList(logLines); } + + public void stop() { + running = false; + if (forgeProcess != null && forgeProcess.isAlive()) { + forgeProcess.destroyForcibly(); + } + } + + // ---------------------------------------------------------------- + // Main entry point + // ---------------------------------------------------------------- /** - * Run the game loop. Calls onStateChange after every action resolves. - * Blocks until the game ends or stop() is called. + * Run the live Forge game. + * + * Tries to spawn a real Forge subprocess with {@code --policy} flags. + * If that fails (missing JAR, wrong Java, etc.) falls back to the + * synthetic stub loop so the WebSocket session never hangs. + * + * @param onStateChange called after every meaningful game event with + * the latest state snapshot */ public void run(Consumer> onStateChange) throws InterruptedException { running = true; - Random rng = seed != null ? new Random(seed) : new Random(); + log("[Session] Starting game. Decks: " + deckNames); + log("[Session] Policy server: " + policyServerUrl); - System.out.println("[Session] Game started. Decks: " + deckNames); - System.out.println("[Session] PolicyClient endpoint: " + policyClient.getBaseUrl()); + boolean forgeAvailable = forgeJarPath != null + && !forgeJarPath.isBlank() + && Files.exists(Path.of(forgeJarPath)); - while (running && !isGameOver()) { - String currentPhase = PHASES[phaseIndex]; - phase = currentPhase; - activePlayer = (turnNumber - 1) % deckNames.size(); - boolean isHumanTurn = (activePlayer == 0); - boolean isInteractivePhase = currentPhase.equals("MAIN1") || currentPhase.equals("MAIN2"); - - if (isHumanTurn && isInteractivePhase) { - awaitingHumanInput = true; - priorityPlayer = 0; - onStateChange.accept(buildStateSnapshot()); - - System.out.println("[Session] Awaiting human action for " + currentPhase + "..."); - String actionJson = humanActionQueue.poll(120, TimeUnit.SECONDS); - if (actionJson == null) { - System.out.println("[Session] Human timed out — auto passing."); - } else { - applyAction(actionJson); - System.out.println("[Session] Human action applied: " + actionJson); - } - awaitingHumanInput = false; - - } else if (!isHumanTurn && isInteractivePhase) { - priorityPlayer = activePlayer; - Map snapshot = buildStateSnapshot(); - String policyAction = consultPolicy(activePlayer, snapshot); - applyPolicyAction(activePlayer, policyAction, rng); - System.out.println("[Session] AI-" + activePlayer + " policy action: " + policyAction); - - } else { - Thread.sleep(300); - } - - phaseIndex++; - if (phaseIndex >= PHASES.length) { - phaseIndex = 0; - turnNumber++; - } - onStateChange.accept(buildStateSnapshot()); + if (forgeAvailable) { + runForgeIpc(onStateChange); + } else { + log("[Session] Forge JAR not found (" + forgeJarPath + ") — running synthetic fallback."); + runSyntheticFallback(onStateChange); } running = false; - System.out.println("[Session] Game ended after " + turnNumber + " turns."); + log(String.format("[Session] Game ended. turns=%d winner=%s", + turnNumber, winningSeat != null ? "seat-" + winningSeat : "none")); } // ================================================================ - // State vector (Issue #83 Step 1) + // Real Forge IPC path // ================================================================ - /** - * Build the global scalar state vector for the given seat. - * - * Returns float[29] matching STATE_DIMS.global_features (29) in - * ml/config/scope.py: - * indices [0..13] = self (seat) per-player features - * indices [14..27] = mean-pooled opponent per-player features - * index [28] = turn_number / MAX_TURNS - * - * Stub fields (mana_available, commander_damage, total_power_on_board) - * are 0.0 until real Forge board data is wired in Step 4. - */ - public float[] buildStateVector(int seat) { - float[] vec = new float[GLOBAL_SCALAR_DIM]; // 29 zeros + private void runForgeIpc(Consumer> onStateChange) throws InterruptedException { + List cmd = buildForgeCommand(); + log("[Forge] Command: " + String.join(" ", cmd.subList(0, Math.min(8, cmd.size()))) + " ..."); - // --- Self block: indices 0..13 --- - fillPlayerBlock(vec, 0, seat, true); + ProcessBuilder pb = new ProcessBuilder(cmd); + pb.directory(new File(forgeWorkDir != null && !forgeWorkDir.isBlank() ? forgeWorkDir : ".")); + pb.redirectErrorStream(true); + pb.environment().remove("JAVA_TOOL_OPTIONS"); - // --- Opponent block: indices 14..27 (mean of all non-self seats) --- - int numOpponents = 0; - float[] oppAccum = new float[PER_PLAYER_FEATURES]; - for (int i = 0; i < deckNames.size(); i++) { - if (i == seat) continue; - float[] oppBlock = buildPlayerFeatures(i, false); - for (int f = 0; f < PER_PLAYER_FEATURES; f++) { - oppAccum[f] += oppBlock[f]; - } - numOpponents++; - } - if (numOpponents > 0) { - for (int f = 0; f < PER_PLAYER_FEATURES; f++) { - vec[PER_PLAYER_FEATURES + f] = oppAccum[f] / numOpponents; - } - } - - // --- Global: turn_number at index 28 --- - vec[28] = Math.min(turnNumber / MAX_TURNS, 1.0f); - - return vec; - } - - /** - * Fill 14 per-player features into vec starting at offset. - */ - private void fillPlayerBlock(float[] vec, int offset, int seat, boolean isSelf) { - float[] block = buildPlayerFeatures(seat, isSelf); - System.arraycopy(block, 0, vec, offset, PER_PLAYER_FEATURES); - } - - /** - * Build 14 per-player features for a single seat. - * - * Feature layout (must match per_player_features in scope.py): - * [0] life_total / MAX_LIFE - * [1] commander_damage / MAX_COMMANDER_DAMAGE (stub 0.0) - * [2] mana_available / MAX_MANA (stub 0.0) - * [3] commander_tax / MAX_COMMANDER_TAX - * [4] cards_in_hand / MAX_HAND - * [5] cards_in_graveyard / MAX_GRAVEYARD - * [6] creatures_on_battlefield / MAX_CREATURES - * [7] total_power_on_board / MAX_POWER (stub = creature count) - * [8] is_active_player (1.0 if this seat == activePlayer) - * [9] phase_onehot[main1] - * [10] phase_onehot[combat] - * [11] phase_onehot[main2] - * [12] phase_onehot[end] - * [13] (reserved — 0.0) - */ - private float[] buildPlayerFeatures(int seat, boolean isSelf) { - float[] f = new float[PER_PLAYER_FEATURES]; - - f[0] = clamp(life[seat] / MAX_LIFE); - f[1] = 0.0f; // commander_damage stub — wire from Forge in Step 4 - f[2] = 0.0f; // mana_available stub — wire from Forge in Step 4 - f[3] = clamp(commanderTax[seat] / MAX_COMMANDER_TAX); - f[4] = clamp(hands[seat].size() / MAX_HAND); - f[5] = clamp(graveyards[seat].size() / MAX_GRAVEYARD); - - // Creature count — all battlefield cards treated as creatures until - // real card type data arrives in Step 4 - float creatureCount = battlefields[seat].size(); - f[6] = clamp(creatureCount / MAX_CREATURES); - f[7] = clamp(creatureCount / MAX_POWER); // stub: power = creature count - - f[8] = (seat == activePlayer) ? 1.0f : 0.0f; - - // Phase one-hot (indices 9..12) - Integer phaseSlot = PHASE_ONEHOT_IDX.get(phase); - if (phaseSlot != null) { - f[9 + phaseSlot] = 1.0f; - } - // f[13] = 0.0f (reserved) - - return f; - } - - /** Clamp a normalized value to [0, 1]. */ - private static float clamp(float v) { - return Math.max(0.0f, Math.min(1.0f, v)); - } - - // ================================================================ - // Policy integration - // ================================================================ - - private String consultPolicy(int seat, Map snapshot) { try { - String stateJson = GSON.toJson(snapshot); - PolicyClient.PolicyDecision decision = policyClient.decide(stateJson, seat); - if (decision != null && decision.action() != null) { - System.out.println("[Session] Policy decision for seat " + seat - + ": " + decision.action() - + " (confidence=" + String.format("%.2f", decision.confidence()) + ")"); - return decision.action(); - } - } catch (Exception e) { - System.err.println("[Session] Policy server error for seat " + seat + ": " + e.getMessage()); + forgeProcess = pb.start(); + } catch (IOException e) { + log("[Session] Failed to start Forge: " + e.getMessage() + " — falling back to synthetic."); + runSyntheticFallback(onStateChange); + return; } - return "PASS_PRIORITY"; + + // Watchdog: kill if stalled + Thread watchdog = new Thread(() -> { + long last = System.currentTimeMillis(); + while (forgeProcess.isAlive() && running) { + try { Thread.sleep(5000); } catch (InterruptedException ignored) { return; } + long now = System.currentTimeMillis(); + if (lastActivityEpoch.get() == 0) last = now; + if ((now - last) > STALL_LIMIT_SECONDS * 1000L) { + log("[Watchdog] Forge stalled >" + STALL_LIMIT_SECONDS + "s. Killing."); + forgeProcess.destroyForcibly(); + return; + } + last = now; + } + }, "ForgeSessionWatchdog"); + watchdog.setDaemon(true); + watchdog.start(); + + // Emit initial state so UI shows a board immediately + onStateChange.accept(buildStateSnapshot()); + + // Read Forge stdout in a background thread + LinkedBlockingQueue lineQueue = new LinkedBlockingQueue<>(); + AtomicBoolean forgeDone = new AtomicBoolean(false); + Thread reader = new Thread(() -> { + try (BufferedReader br = new BufferedReader( + new InputStreamReader(forgeProcess.getInputStream(), StandardCharsets.UTF_8))) { + String line; + while ((line = br.readLine()) != null) lineQueue.offer(line); + } catch (IOException ignored) {} + forgeDone.set(true); + }, "ForgeOutputReader"); + reader.setDaemon(true); + reader.start(); + + // Main loop: drain line queue and service human input + while (!gameOver && running) { + String line = lineQueue.poll(200, TimeUnit.MILLISECONDS); + if (line != null) { + lastActivityEpoch.incrementAndGet(); + boolean changed = parseForgeLine(line); + if (changed) onStateChange.accept(buildStateSnapshot()); + if (awaitingHumanInput) handleHumanTurn(onStateChange); + } else if (forgeDone.get() && lineQueue.isEmpty()) { + break; + } + } + + watchdog.interrupt(); + try { forgeProcess.waitFor(10, TimeUnit.SECONDS); } catch (InterruptedException ignored) {} + + running = false; + onStateChange.accept(buildStateSnapshot()); } - private void applyPolicyAction(int seat, String action, Random rng) { - switch (action) { - case "CAST_SPELL", "cast_creature", "cast_ramp", "cast_draw", "cast_commander" -> { - if (!hands[seat].isEmpty()) { - String card = hands[seat].remove(0); - battlefields[seat].add(card); - System.out.println("[Session] AI-" + seat + " cast: " + card); - } - } - case "PLAY_LAND" -> { - if (!hands[seat].isEmpty()) { - String card = hands[seat].remove(hands[seat].size() - 1); - battlefields[seat].add(card); - } - } - case "ATTACK_OPPONENT", "ATTACK" -> { - int target = (seat + 1) % life.length; - if (life[target] > 0) { - int dmg = rng.nextInt(3) + 1; - life[target] -= dmg; - System.out.println("[Session] AI-" + seat + " attacks player " + target + " for " + dmg); - } - } - case "cast_removal" -> { - // Find an opponent with creatures and remove one - for (int i = 0; i < deckNames.size(); i++) { - if (i != seat && !battlefields[i].isEmpty()) { - String removed = battlefields[i].remove(0); - graveyards[i].add(removed); - System.out.println("[Session] AI-" + seat + " removed: " + removed + " from seat " + i); - break; - } - } - } - case "hold_mana", "pass", "PASS_PRIORITY", "HOLD_MANA" -> { /* no-op */ } - default -> System.out.println("[Session] Unknown policy action: " + action); + // ---------------------------------------------------------------- + // Forge command builder + // ---------------------------------------------------------------- + + private List buildForgeCommand() { + List cmd = new ArrayList<>(); + cmd.add(javaPath); + cmd.add("-Xmx4096m"); + cmd.add("-XX:+UseSerialGC"); + cmd.add("-XX:TieredStopAtLevel=1"); + cmd.add("-Dfile.encoding=UTF-8"); + cmd.add("-Dio.netty.tryReflectionSetAccessible=true"); + + String[] addOpens = { + "java.desktop/java.beans=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.base/sun.nio.ch=ALL-UNNAMED", + "java.base/java.nio=ALL-UNNAMED", + "java.base/java.net=ALL-UNNAMED", + }; + for (String m : addOpens) { cmd.add("--add-opens"); cmd.add(m); } + + cmd.add("-jar"); cmd.add(forgeJarPath); + cmd.add("sim"); + cmd.add("-d"); + for (int i = 0; i < numSeats; i++) { + String f = (i < deckFiles.size()) ? deckFiles.get(i) : deckNames.get(i); + if (!f.endsWith(".dck")) f = f + ".dck"; + cmd.add(f); } + cmd.add("-f"); cmd.add("commander"); + cmd.add("-n"); cmd.add("1"); + cmd.add("-c"); cmd.add(String.valueOf(clockSeconds)); + cmd.add("--policy"); cmd.add("midrange"); + cmd.add("--policyServer"); cmd.add(policyServerUrl); + if (seed != null) { cmd.add("--seed"); cmd.add(seed.toString()); } + return cmd; } - // ================================================================ - // Human action handling - // ================================================================ + // ---------------------------------------------------------------- + // Forge stdout parser + // ---------------------------------------------------------------- - private void applyAction(String actionJson) { + /** + * Parse one line of Forge verbose output, mutating game state. + * @return true if state changed meaningfully (triggers snapshot push) + */ + private boolean parseForgeLine(String raw) { + String line = raw.trim(); + if (line.isEmpty()) return false; + logLines.add(line); + boolean changed = false; + + // Turn boundary + Matcher mTurn = P_TURN.matcher(line); + if (mTurn.find()) { + int t = Integer.parseInt(mTurn.group(1)); + int seat = clampSeat(Integer.parseInt(mTurn.group(2)) - 1); + if (t != turnNumber || seat != activePlayer) { + turnNumber = t; activePlayer = seat; phase = "UNTAP"; changed = true; + } + } + + // Phase change + Matcher mPhase = P_PHASE.matcher(line); + if (mPhase.find()) { + String np = mPhase.group(1).trim().toUpperCase().replaceAll("\\s+", "_"); + if (!np.equals(phase)) { + phase = np; + if (activePlayer == 0 && + (phase.equals("MAIN1") || phase.equals("MAIN_1") + || phase.equals("MAIN2") || phase.equals("MAIN_2"))) { + awaitingHumanInput = true; + } + changed = true; + } + } + + // Priority + Matcher mPrio = P_PRIORITY.matcher(line); + if (mPrio.find()) { + priorityPlayer = clampSeat(Integer.parseInt(mPrio.group(1)) - 1); + changed = true; + } + + // Life totals + Matcher mLc = P_LIFE_CHANGE.matcher(line); + if (mLc.find()) { + int s = clampSeat(Integer.parseInt(mLc.group(1)) - 1); + int nl = Integer.parseInt(mLc.group(3)); + if (life[s] != nl) { life[s] = nl; changed = true; } + } + Matcher mLn = P_LIFE_NOW.matcher(line); + if (mLn.find()) { + int s = clampSeat(Integer.parseInt(mLn.group(1)) - 1); + int nl = Integer.parseInt(mLn.group(2)); + if (life[s] != nl) { life[s] = nl; changed = true; } + } + + // Spell cast → hand → battlefield + Matcher mCast = P_CAST.matcher(line); + if (mCast.find()) { + int s = clampSeat(Integer.parseInt(mCast.group(1)) - 1); + String card = mCast.group(2).trim(); + hands[s].remove(card); + if (!battlefields[s].contains(card)) battlefields[s].add(card); + changed = true; + } + + // Land play + Matcher mLand = P_LAND.matcher(line); + if (mLand.find()) { + int s = clampSeat(Integer.parseInt(mLand.group(1)) - 1); + String card = mLand.group(2).trim(); + hands[s].remove(card); + if (!battlefields[s].contains(card)) battlefields[s].add(card); + changed = true; + } + + // Zone changes + Matcher mBf = P_ZONE_BF.matcher(line); + if (mBf.find()) { + battlefields[activePlayer].add(mBf.group(1).trim()); + changed = true; + } + Matcher mGy = P_ZONE_GY.matcher(line); + if (mGy.find()) { + String card = mGy.group(1).trim(); + for (int s = 0; s < numSeats; s++) { + if (battlefields[s].remove(card)) { graveyards[s].add(card); changed = true; break; } + } + } + Matcher mEx = P_ZONE_EXILE.matcher(line); + if (mEx.find()) { + String card = mEx.group(1).trim(); + for (int s = 0; s < numSeats; s++) { + if (battlefields[s].remove(card) || graveyards[s].remove(card)) { + exiles[s].add(card); changed = true; break; + } + } + } + + // Stack + Matcher mSa = P_STACK_ADD.matcher(line); + if (mSa.find()) { stack.add(mSa.group(1).trim()); changed = true; } + Matcher mSr = P_STACK_RESOLVE.matcher(line); + if (mSr.find()) { stack.remove(mSr.group(1).trim()); changed = true; } + + // Hand tracking + Matcher mHa = P_HAND_ADD.matcher(line); + if (mHa.find()) { + int s = clampSeat(Integer.parseInt(mHa.group(1)) - 1); + hands[s].add(mHa.group(2).trim()); changed = true; + } + Matcher mHr = P_HAND_REMOVE.matcher(line); + if (mHr.find()) { + int s = clampSeat(Integer.parseInt(mHr.group(1)) - 1); + hands[s].remove(mHr.group(2).trim()); changed = true; + } + + // Commander tax + Matcher mTax = P_CMDR_TAX.matcher(line); + if (mTax.find()) { + int s = clampSeat(Integer.parseInt(mTax.group(1)) - 1); + commanderTax[s] = Integer.parseInt(mTax.group(2)); changed = true; + } + + // Game outcome + Matcher mWin = P_WINNER.matcher(line); + if (mWin.find()) { + winningSeat = clampSeat(Integer.parseInt(mWin.group(1)) - 1); + gameOver = true; changed = true; + } + if (P_LOSER.matcher(line).find()) changed = true; + + Matcher mGr = P_GAME_RESULT.matcher(line); + if (mGr.find()) { + elapsedMs = Long.parseLong(mGr.group(2)); + gameOver = true; changed = true; + } + + return changed; + } + + // ---------------------------------------------------------------- + // Human turn handling + // ---------------------------------------------------------------- + + private void handleHumanTurn(Consumer> onStateChange) + throws InterruptedException { + awaitingHumanInput = true; + onStateChange.accept(buildStateSnapshot()); + log("[Session] Awaiting human action (phase=" + phase + " turn=" + turnNumber + ")"); + + String actionJson = humanActionQueue.poll(HUMAN_TIMEOUT_SECONDS, TimeUnit.SECONDS); + if (actionJson == null) { + log("[Session] Human timed out — injecting PASS_PRIORITY."); + actionJson = "{\"type\":\"PASS_PRIORITY\"}"; + } + String macroAction = mapHumanActionToMacro(actionJson); + injectHumanOverride(macroAction); + awaitingHumanInput = false; + log("[Session] Human action applied: " + macroAction); + } + + private String mapHumanActionToMacro(String actionJson) { try { - JsonObject action = JsonParser.parseString(actionJson).getAsJsonObject(); - String type = action.has("type") ? action.get("type").getAsString() : "PASS_PRIORITY"; - switch (type) { - case "PLAY_LAND", "CAST_SPELL" -> { - String cardId = action.has("cardId") ? action.get("cardId").getAsString() : null; - if (cardId != null && hands[0].contains(cardId)) { - hands[0].remove(cardId); - battlefields[0].add(cardId); - } - } - case "PASS_PRIORITY" -> { /* no-op, phase advances naturally */ } - default -> System.out.println("[Session] Unknown action type: " + type); - } + JsonObject obj = JsonParser.parseString(actionJson).getAsJsonObject(); + String type = obj.has("type") ? obj.get("type").getAsString() : "PASS_PRIORITY"; + return switch (type.toUpperCase()) { + case "CAST_SPELL" -> "CAST_CREATURE"; + case "PLAY_LAND" -> "PLAY_LAND"; + case "ATTACK" -> "ATTACK_ALL"; + case "PASS_PRIORITY", "PASS" -> "PASS"; + default -> "PASS"; + }; + } catch (Exception e) { return "PASS"; } + } + + private void injectHumanOverride(String macroAction) { + try { + JsonObject body = new JsonObject(); + body.addProperty("seat", 0); + body.addProperty("action", macroAction); + httpPost(policyServerUrl + "/api/policy/override", body.toString()); } catch (Exception e) { - System.err.println("[Session] Failed to apply action: " + e.getMessage()); + log("[Session] Human override injection failed (" + e.getMessage() + ") — Forge uses policy net."); } } - private boolean isGameOver() { + // ================================================================ + // Synthetic fallback loop + // ================================================================ + + private void runSyntheticFallback(Consumer> onStateChange) + throws InterruptedException { + log("[Session] Running synthetic stub game."); + Random rng = seed != null ? new Random(seed) : new Random(); + String[] phases = { + "UNTAP","UPKEEP","DRAW","MAIN1","BEGIN_COMBAT", + "DECLARE_ATTACKERS","DECLARE_BLOCKERS","DAMAGE", + "END_COMBAT","MAIN2","END","CLEANUP" + }; + int phaseIdx = 0; + for (int i = 0; i < numSeats; i++) + for (int c = 1; c <= 7; c++) hands[i].add("stub_card_" + c); + + while (running && !isSyntheticGameOver()) { + phase = phases[phaseIdx]; + activePlayer = (turnNumber - 1) % numSeats; + boolean isHuman = activePlayer == 0; + boolean isMain = phase.equals("MAIN1") || phase.equals("MAIN2"); + + if (isHuman && isMain) { + awaitingHumanInput = true; + priorityPlayer = 0; + onStateChange.accept(buildStateSnapshot()); + String actionJson = humanActionQueue.poll(HUMAN_TIMEOUT_SECONDS, TimeUnit.SECONDS); + if (actionJson != null) applySyntheticAction(actionJson); + awaitingHumanInput = false; + } else if (!isHuman && isMain) { + priorityPlayer = activePlayer; + applySyntheticPolicy(activePlayer, consultsPolicy(activePlayer), rng); + } else { + Thread.sleep(200); + } + + phaseIdx = (phaseIdx + 1) % phases.length; + if (phaseIdx == 0) turnNumber++; + onStateChange.accept(buildStateSnapshot()); + } + } + + private boolean isSyntheticGameOver() { int alive = 0; for (int lp : life) if (lp > 0) alive++; - return alive <= 1 || turnNumber > 50; + if (alive <= 1 || turnNumber > 50) { gameOver = true; return true; } + return false; } - // ================================================================ - // State serialization - // ================================================================ + private void applySyntheticAction(String actionJson) { + try { + JsonObject obj = JsonParser.parseString(actionJson).getAsJsonObject(); + String type = obj.has("type") ? obj.get("type").getAsString() : "PASS_PRIORITY"; + if ((type.equals("PLAY_LAND") || type.equals("CAST_SPELL")) && !hands[0].isEmpty()) { + String cardId = obj.has("cardId") ? obj.get("cardId").getAsString() : null; + String card = (cardId != null && hands[0].contains(cardId)) ? cardId : hands[0].get(0); + hands[0].remove(card); battlefields[0].add(card); + } + } catch (Exception ignored) {} + } + + private String consultsPolicy(int seat) { + try { + PolicyClient.PolicyDecision d = policyClient.decide(GSON.toJson(buildStateSnapshot()), seat); + return d != null && d.action() != null ? d.action() : "PASS_PRIORITY"; + } catch (Exception e) { return "PASS_PRIORITY"; } + } + + private void applySyntheticPolicy(int seat, String action, Random rng) { + switch (action.toUpperCase()) { + case "CAST_SPELL", "CAST_CREATURE" -> { + if (!hands[seat].isEmpty()) { battlefields[seat].add(hands[seat].remove(0)); } + } + case "PLAY_LAND" -> { + if (!hands[seat].isEmpty()) { battlefields[seat].add(hands[seat].remove(hands[seat].size() - 1)); } + } + case "ATTACK", "ATTACK_ALL" -> { + int t = (seat + 1) % life.length; + if (life[t] > 0) life[t] -= rng.nextInt(3) + 1; + } + } + } + + // ---------------------------------------------------------------- + // State snapshot — full zone contents + // ---------------------------------------------------------------- + + public Map buildStateSnapshot() { + Map state = new LinkedHashMap<>(); + state.put("schema", "2.0.0"); + state.put("phase", phase); + state.put("turnNumber", turnNumber); + state.put("activePlayer", activePlayer); + state.put("priorityPlayer", priorityPlayer); + state.put("awaitingInput", awaitingHumanInput); + state.put("inputPrompt", awaitingHumanInput ? "Choose an action or pass priority" : null); + state.put("gameOver", gameOver); + state.put("winningSeat", winningSeat); + state.put("elapsedMs", elapsedMs); + state.put("isForgeBacked", forgeProcess != null && !forgeFailed.get()); + + List> players = new ArrayList<>(); + for (int i = 0; i < numSeats; i++) { + Map p = new LinkedHashMap<>(); + p.put("seat", i); + p.put("name", i == 0 ? "Human" : "AI-" + i); + p.put("isAI", i != 0); + p.put("deckName", i < deckNames.size() ? deckNames.get(i) : "Deck-" + i); + p.put("life", life[i]); + p.put("poison", poison[i]); + p.put("commanderTax", commanderTax[i]); + p.put("handCount", hands[i].size()); + p.put("hand", i == 0 ? new ArrayList<>(hands[i]) : List.of()); + p.put("battlefield", new ArrayList<>(battlefields[i])); + p.put("graveyard", new ArrayList<>(graveyards[i])); + p.put("exile", new ArrayList<>(exiles[i])); + p.put("commandZone", new ArrayList<>(commandZones[i])); + p.put("manaPool", Map.of("W",0,"U",0,"B",0,"R",0,"G",0,"C",0)); + p.put("isWinner", winningSeat != null && winningSeat == i); + players.add(p); + } + state.put("players", players); + state.put("stack", new ArrayList<>(stack)); + + List> legal = new ArrayList<>(); + if (awaitingHumanInput) { + legal.add(Map.of("type", "PASS_PRIORITY", "label", "Pass Priority")); + for (String card : hands[0]) + legal.add(Map.of("type", "CAST_SPELL", "cardId", card, "label", "Cast " + card)); + } + state.put("legalActions", legal); + return state; + } - /** Returns a full { type: "STATE", state: {...} } JSON string. */ public String buildStateMessage() { Map msg = new LinkedHashMap<>(); msg.put("type", "STATE"); @@ -428,64 +723,25 @@ public class GameSession { return GSON.toJson(msg); } - /** - * Returns the raw state snapshot map. - * - * Includes a "state_vector" key containing a float[29] global scalar - * vector (Issue #83 Step 1) so PolicyClient.decide() sends a - * machine-readable vector the Python /api/policy/decide endpoint can - * pass directly to the ml/encoder without re-parsing nested fields. - * - * Stub fields within the vector are clearly marked in buildPlayerFeatures(). - */ - public Map buildStateSnapshot() { - Map state = new LinkedHashMap<>(); - state.put("schema", "1.1.0"); // bumped from 1.0.0 — state_vector added - state.put("phase", phase); - state.put("turnNumber", turnNumber); - state.put("activePlayer", activePlayer); - state.put("priorityPlayer", priorityPlayer); - state.put("awaitingInput", awaitingHumanInput); - state.put("inputPrompt", awaitingHumanInput ? "Choose an action or pass priority" : null); + // ---------------------------------------------------------------- + // Helpers + // ---------------------------------------------------------------- - // Machine-readable global scalar vector for the Python encoder - // Emitted for activePlayer's perspective - float[] sv = buildStateVector(activePlayer); - List svList = new ArrayList<>(sv.length); - for (float v : sv) svList.add(v); - state.put("state_vector", svList); - state.put("state_vector_dim", sv.length); // sanity: should always be 29 + private int clampSeat(int s) { return Math.max(0, Math.min(s, numSeats - 1)); } - List> players = new ArrayList<>(); - for (int i = 0; i < deckNames.size(); i++) { - Map p = new LinkedHashMap<>(); - p.put("seat", i); - p.put("name", i == 0 ? "Human" : "AI-" + i); - p.put("isAI", i != 0); - p.put("deckName", deckNames.get(i)); - p.put("life", life[i]); - p.put("poison", poison[i]); - p.put("commanderTax", commanderTax[i]); - p.put("handCount", hands[i].size()); - p.put("hand", i == 0 ? hands[i] : List.of()); - p.put("battlefield", battlefields[i]); - p.put("graveyard", graveyards[i]); - p.put("commandZone", commandZones[i]); - p.put("manaPool", Map.of("W",0,"U",0,"B",0,"R",0,"G",0,"C",0)); - players.add(p); + private void log(String msg) { System.out.println(msg); logLines.add(msg); } + + private void httpPost(String urlStr, String jsonBody) throws IOException { + HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection(); + conn.setRequestMethod("POST"); + conn.setConnectTimeout(1000); + conn.setReadTimeout(3000); + conn.setDoOutput(true); + conn.setRequestProperty("Content-Type", "application/json"); + try (OutputStream os = conn.getOutputStream()) { + os.write(jsonBody.getBytes(StandardCharsets.UTF_8)); } - state.put("players", players); - state.put("stack", List.of()); - - List> legalActions = new ArrayList<>(); - if (awaitingHumanInput) { - legalActions.add(Map.of("type", "PASS_PRIORITY", "label", "Pass Priority")); - for (String card : hands[0]) { - legalActions.add(Map.of("type", "CAST_SPELL", "cardId", card, "label", "Cast " + card)); - } - } - state.put("legalActions", legalActions); - - return state; + int code = conn.getResponseCode(); + if (code != 200) throw new IOException("HTTP " + code + " from " + urlStr); } }