using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Threading; using Newtonsoft.Json; using YGOLegacy.Bot; using YGOLegacy.Characters; using YGOLegacy.Engine; using YGOLegacy.Services; namespace YGOLegacy.Tools.BotArena { /// /// Standalone, parallel Bot Arena (TICKET-035). No Unity in the loop: the /// exe compiles the in-tree WindBot + the fork's brain, loads the engine /// (ygol-engine.dll) itself and runs N bot-vs-bot duels across `--parallel` worker PROCESSES /// (WindBot.Config is process-global, so one duel at a time per process). /// /// Two modes in one exe: /// parent — parses the CLI, resolves seats, spawns workers (this exe /// with `--worker`), hands out duel indices over their stdin, /// collects one JSON line per duel from their stdout, tallies /// and writes the same report the in-editor arena writes. /// worker — see Worker.cs. /// Exit codes: 0 = at least one duel played, 1 = none, 2 = bad arguments. /// internal static class Program { private const string LogPrefix = "[arena] "; private static Stopwatch wall; private static int Main(string[] args) { Options opts; try { opts = Options.Parse(args); } catch (ArgumentException e) { Console.Error.WriteLine("error: " + e.Message); Console.Error.WriteLine(); Console.Error.WriteLine(Options.Usage); return 2; } if (opts.help) { Console.WriteLine(Options.Usage); return 0; } if (opts.worker) return Worker.Run(opts); return RunParent(opts); } // ------------------------------------------------------------------ // Parent // ------------------------------------------------------------------ private static int RunParent(Options opts) { wall = Stopwatch.StartNew(); Directory.SetCurrentDirectory(opts.root); try { YgoServer.Locate(opts.root); Log("engine " + EngineBinding.CheckNative() + " (" + YgoServer.DllPath + ")"); } catch (Exception e) { Console.Error.WriteLine(LogPrefix + e.Message); return 1; } var result = new StandaloneArenaResult { startedAt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), config = opts.ToConfig(), workers = opts.parallel, status = "starting", }; var workers = new List(); try { if (!ValidateDeck(opts.deckA, out var whyA)) { result.status = "bad deck A: " + whyA; } else if (!ValidateDeck(opts.deckB, out var whyB)) { result.status = "bad deck B: " + whyB; } else { // Seats: the deck decides the brain (BotRoster.ForDeck), the // executor override rewrites Deck= — identical to BotArena.cs. Setup.LoadGameData(opts); var botA = BotRoster.ForDeck(opts.deckA); var botB = BotRoster.ForDeck(opts.deckB); result.nameA = ArenaReport.SeatName(botA, 0); result.nameB = ArenaReport.SeatName(botB, 1); result.commandA = ArenaReport.SeatCommand(botA, opts.deckA, opts.execA, result.nameA); result.commandB = ArenaReport.SeatCommand(botB, opts.deckB, opts.execB, result.nameB); Log("run: " + opts.n + " duel(s) on " + opts.parallel + " worker(s), host=" + opts.hostMode + ", A=" + result.commandA + " | B=" + result.commandB); if (!string.IsNullOrEmpty(opts.replaysDir)) { if (opts.hostMode == "local") Log("--replays is server-only: the in-process host has no ygoserver to send STOC_REPLAY, so no .yrp will be written (use --host server)"); Directory.CreateDirectory(opts.replaysDir); } if (!string.IsNullOrEmpty(opts.journalDir)) { // The run's own config next to the journals, so blunders.py // (and a human) can tell what produced them. Directory.CreateDirectory(opts.journalDir); var runInfo = new { startedAt = result.startedAt, config = result.config, workers = opts.parallel, nameA = result.nameA, nameB = result.nameB, commandA = result.commandA, commandB = result.commandB, journalFiles = "duel--.jsonl (Smart seats only)", }; File.WriteAllText(Path.Combine(opts.journalDir, "run.json"), JsonConvert.SerializeObject(runInfo, Formatting.Indented)); } RunDuels(opts, result, workers); result.status = "done"; } } catch (Exception e) { Console.Error.WriteLine(LogPrefix + "failed: " + e); result.status = "failed: " + e.Message; } finally { foreach (var w in workers) w.Kill(); result.totalSeconds = (float)wall.Elapsed.TotalSeconds; result.wallClockSeconds = result.totalSeconds; result.done = true; result.summary = ArenaReport.Summary(result); try { result.reportPath = WriteReport(result, opts.outPath); } catch (Exception e) { Console.Error.WriteLine(LogPrefix + "could not write report: " + e.Message); } Console.WriteLine(result.summary + (result.reportPath != null ? " -> " + result.reportPath : string.Empty)); } return result.Played > 0 ? 0 : 1; } /// /// Dynamic scheduling: every worker gets one duel index at a time and /// the next as soon as it reports, so a slow duel or a dead worker never /// stalls the run. A worker that dies mid-duel gets that duel re-queued /// once; with no worker left, what remains is recorded as errors. /// private static void RunDuels(Options opts, StandaloneArenaResult result, List workers) { var pending = new Queue(); for (var i = 1; i <= opts.n; i++) pending.Enqueue(i); if (pending.Count == 0) return; var count = Math.Min(opts.parallel, opts.n); var received = new Dictionary(); var retried = new HashSet(); var gate = new object(); var lastLog = 0; var respawns = 0; for (var w = 0; w < count; w++) { var handle = new WorkerHandle(w, opts, result, opts.portBase + w * 4, 0); handle.OnRecord = record => { lock (gate) { received[record.index] = record; Monitor.PulseAll(gate); } }; handle.Start(); workers.Add(handle); } // Assign / collect loop. var deadline = DateTime.UtcNow.AddSeconds(Math.Max(60, opts.timeoutSeconds + 120) * (double)Math.Max(1, (opts.n + count - 1) / count) + 120); while (true) { lock (gate) { // Feed idle, live workers. foreach (var w in workers) { if (!w.Alive || w.Busy != 0 || !w.Ready) continue; if (pending.Count == 0) break; var idx = pending.Dequeue(); w.Assign(idx); } // Collect anything that arrived. foreach (var w in workers) { if (w.Busy != 0 && received.TryGetValue(w.Busy, out var rec)) { received.Remove(w.Busy); w.Busy = 0; ArenaReport.Tally(result, rec); result.totalSeconds = (float)wall.Elapsed.TotalSeconds; Log("duel " + rec.index + " [w" + w.Index + "]: " + rec.winner + (rec.winnerName != null ? " (" + rec.winnerName + ")" : string.Empty) + " turns=" + rec.turns + " " + rec.durationSeconds.ToString("0.0", CultureInfo.InvariantCulture) + "s" + (rec.error != null ? " error=" + rec.error : string.Empty) + " | " + result.nameA + " " + result.winsA + " - " + result.winsB + " " + result.nameB + " (" + result.completed + "/" + opts.n + ")"); } } // Dead workers: requeue their duel once (else record an // error) and start a replacement while there is work left — // the engine's server can abort the whole process on a rare // teardown race, and one crash must not cost a seat. for (var i = 0; i < workers.Count; i++) { var w = workers[i]; if (w.Alive || w.Retired) continue; w.Retired = true; if (w.Busy != 0) { var idx = w.Busy; w.Busy = 0; if (retried.Add(idx)) pending.Enqueue(idx); else ArenaReport.Tally(result, new DuelRecord { index = idx, winner = "error", error = "worker " + w.Index + " died" }); } if (pending.Count > 0 && respawns < opts.parallel * 2) { respawns++; Log("worker " + w.Index + " died (see " + WorkerHandle.LogDir + "); starting a replacement"); var again = new WorkerHandle(w.Index, opts, result, w.Port, w.Generation + 1) { OnRecord = w.OnRecord }; again.Start(); workers.Add(again); } } var anyAlive = false; var anyBusy = false; foreach (var w in workers) { anyAlive |= w.Alive; anyBusy |= w.Busy != 0; } if (pending.Count == 0 && !anyBusy) break; if (!anyAlive) { while (pending.Count > 0) ArenaReport.Tally(result, new DuelRecord { index = pending.Dequeue(), winner = "error", error = "no worker alive (see " + WorkerHandle.LogDir + ")" }); break; } if (DateTime.UtcNow > deadline) { Log("global deadline hit; abandoning " + pending.Count + " pending duel(s)"); while (pending.Count > 0) ArenaReport.Tally(result, new DuelRecord { index = pending.Dequeue(), winner = "error", error = "run deadline" }); break; } if (++lastLog % 600 == 0 && result.completed == 0) Log("waiting for the first result (workers load the card databases and index Expansions/ first)..."); Monitor.Wait(gate, 100); } } result.duels.Sort((a, b) => a.index.CompareTo(b.index)); foreach (var w in workers) w.Quit(); } private static string WriteReport(ArenaResult result, string extra) { Directory.CreateDirectory(ArenaReport.OutputDir); var file = ArenaReport.ReportFileName(result, DateTime.Now); var json = JsonConvert.SerializeObject(result, Formatting.Indented); File.WriteAllText(file, json); if (!string.IsNullOrWhiteSpace(extra)) { var dir = Path.GetDirectoryName(Path.GetFullPath(extra)); if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); File.WriteAllText(extra, json); } return file; } /// Same resolution WindBot's Program.ReadFile("Decks", …, "ydk") does at /// join time, so a deck the tool accepts is a deck the bot will load. private static bool ValidateDeck(string path, out string why) { why = null; if (string.IsNullOrWhiteSpace(path)) { why = "empty"; return false; } if (Setup.ResolveDeckFile(path) != null) return true; why = "not found under Deck/ or Data/Windbot/Decks/: " + path; return false; } internal static void Log(string message) => Console.Error.WriteLine(LogPrefix + message); } /// The editor arena's report plus what only a parallel run knows. /// (JsonProperty Order keeps the two extra fields AFTER the shared ones, /// so a report diff against Data/BotArena/*.json is append-only.) public class StandaloneArenaResult : ArenaResult { [JsonProperty(Order = 1)] public int workers; [JsonProperty(Order = 1)] public float wallClockSeconds; } // ---------------------------------------------------------------------- // Worker process handle (parent side) // ---------------------------------------------------------------------- internal sealed class WorkerHandle { // Per-run folder (pid-stamped) so concurrent arena runs never share a worker-N.log // (a shared name made a second run fail to open the log while another was live). public static string LogDir = Path.Combine(ArenaReport.OutputDir, "logs", "run-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + "-" + Environment.ProcessId); public int Index { get; } public int Port { get; } /// 0 for the first process on this seat, +1 per replacement. public int Generation { get; } public int Busy; // duel index in flight, 0 = idle public volatile bool Ready; // worker finished loading and said so public bool Retired; // death already handled by the parent public Action OnRecord; private readonly Options opts; private readonly ArenaResult result; private readonly int port; private Process process; private StreamWriter log; public WorkerHandle(int index, Options opts, ArenaResult result, int port, int generation) { Index = index; Port = port; Generation = generation; this.opts = opts; this.result = result; this.port = port; } public bool Alive => process != null && !process.HasExited; public void Start() { Directory.CreateDirectory(LogDir); var logName = "worker-" + Index + (Generation > 0 ? "-r" + Generation : string.Empty) + ".log"; log = new StreamWriter(Path.Combine(LogDir, logName), false, new UTF8Encoding(false)) { AutoFlush = true }; var psi = new ProcessStartInfo { FileName = Environment.ProcessPath ?? Process.GetCurrentProcess().MainModule.FileName, UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, WorkingDirectory = opts.root, StandardOutputEncoding = new UTF8Encoding(false), StandardErrorEncoding = new UTF8Encoding(false), }; // ArgumentList quotes for us — the commands carry Name="…" tokens. var a = psi.ArgumentList; a.Add("--worker"); a.Add(Index.ToString()); a.Add("--root"); a.Add(opts.root); a.Add("--port"); a.Add(port.ToString()); a.Add("--nameA"); a.Add(result.nameA); a.Add("--nameB"); a.Add(result.nameB); a.Add("--commandA"); a.Add(result.commandA); a.Add("--commandB"); a.Add(result.commandB); a.Add("--seed"); a.Add(opts.seed.ToString()); a.Add("--timeout"); a.Add(opts.timeoutSeconds.ToString()); a.Add("--locale"); a.Add(opts.locale); a.Add("--host"); a.Add(opts.hostMode); if (opts.verbose) a.Add("--verbose"); if (!string.IsNullOrEmpty(opts.replaysDir)) { a.Add("--replays"); a.Add(opts.replaysDir); } if (!string.IsNullOrEmpty(opts.journalDir)) { a.Add("--journal"); a.Add(opts.journalDir); } if (opts.insightA.HasValue) { a.Add("--insightA"); a.Add(Insight.LevelName(opts.insightA.Value)); } if (opts.insightB.HasValue) { a.Add("--insightB"); a.Add(Insight.LevelName(opts.insightB.Value)); } if (opts.knobsA != null) { a.Add("--knobsA"); a.Add(Options.FormatKnobs(opts.knobsA)); } if (opts.knobsB != null) { a.Add("--knobsB"); a.Add(Options.FormatKnobs(opts.knobsB)); } process = new Process { StartInfo = psi, EnableRaisingEvents = true }; process.OutputDataReceived += (_, e) => { if (e.Data != null) OnLine(e.Data); }; process.ErrorDataReceived += (_, e) => { if (e.Data != null) log.WriteLine(e.Data); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); } private void OnLine(string line) { // Anything not JSON is the native server's own printf (it prints the // port it bound) or stray chatter — log it, don't parse it. if (line.Length == 0 || line[0] != '{') { log.WriteLine("[stdout] " + line); return; } WorkerMessage msg; try { msg = JsonConvert.DeserializeObject(line); } catch (Exception e) { log.WriteLine("[stdout?] " + line + " (" + e.Message + ")"); return; } if (msg == null) return; switch (msg.type) { case "ready": Ready = true; break; case "duel": if (msg.record != null) OnRecord?.Invoke(msg.record); break; case "fatal": log.WriteLine("[fatal] " + msg.error); Program.Log("worker " + Index + " failed: " + msg.error); break; default: log.WriteLine("[stdout] " + line); break; } } public void Assign(int duelIndex) { Busy = duelIndex; try { process.StandardInput.WriteLine(duelIndex.ToString()); process.StandardInput.Flush(); } catch (Exception e) { log.WriteLine("[parent] could not assign duel " + duelIndex + ": " + e.Message); } } public void Quit() { try { if (Alive) { process.StandardInput.WriteLine("quit"); process.StandardInput.Flush(); } } catch { } try { if (process != null && !process.WaitForExit(5000)) process.Kill(true); } catch { } } public void Kill() { try { if (Alive) process.Kill(true); } catch { } try { log?.Dispose(); } catch { } } } /// One stdout line from a worker. public class WorkerMessage { public string type; // ready | duel | fatal public DuelRecord record; public string error; } // ---------------------------------------------------------------------- // CLI // ---------------------------------------------------------------------- internal sealed class Options { public const string Usage = @"BotArena — headless, parallel bot-vs-bot duels (no Unity). BotArena --deckA ""group/name"" --deckB ""group/name"" [options] Decks are Deck/ paths without .ydk (root-group decks are just ""name""); Data/Windbot/Decks/ names work too. The DECK decides the brain (the owning character in Data/Characters/); --execA/--execB force a WindBot executor. Options: --root game/repo root (Deck/, Data/, Expansions/ live here). Default: cwd --execA WindBot Deck= override for seat A (Smart, Lucky, ...). Default: the deck's own --execB same for seat B --n duels to play. Default 10 --parallel worker processes (one server + two bots each). Default 1 --seed base of the per-duel SmartExecutor noise seed (0 = brains seed themselves) --timeout per-duel timeout. Default 300 --out extra copy of the JSON report (canonical copy: Data/BotArena/) --replays save every duel's .yrp there --journal SmartExecutor decision journal: /duel--.jsonl per Smart seat + run.json (feed the dir to .claude/skills/bot-brain/blunders.py) --port first server port (workers take base, base+4, ...). Default 7920 --locale Data/locales// for cards.cdb + bot.conf. Default en-US --verbose keep [YGOL bot] decision logging (goes to Data/BotArena/logs/run--/worker-N.log) --insightA duel state bus insight for seat A: none | hand | full (TICKET-042). Overrides that deck brain's `insight` knob. Default: the knob (none) --insightB same for seat B --host local|server in-process core (default) or the engine's server over TCP (TICKET-045) --knobsA per-seat SmartExecutor knob overrides for seat A, applied ON TOP of the deck brain's knobs: ""name=value,name=value"" (e.g. ""lookahead=8,lookaheadTurns=6""). Setting `lookahead` above 0 also installs the arena's perfect-information rollout oracle for that seat (TICKET-050, --host local only) --knobsB same for seat B -h, --help Exit codes: 0 = at least one duel played, 1 = none played, 2 = bad arguments."; public bool help; public string root = Directory.GetCurrentDirectory(); public string deckA, deckB, execA, execB; public int n = 10; public int parallel = 1; public int seed; public int timeoutSeconds = 300; public string outPath; public string replaysDir; public string journalDir; public int portBase = 7920; public string locale = "en-US"; public bool verbose; /// TICKET-045: "local" = YGOLegacy.Bot.LocalDuelHost drives the engine's core /// in this process (no server, no sockets); "server" = the original /// start_server path, kept for A/B comparisons. public string hostMode = "local"; /// TICKET-042 per-seat insight override; null = the deck brain decides. public InsightLevel? insightA, insightB; /// TICKET-050 per-seat knob overrides (--knobsA/--knobsB); null = none. public Dictionary knobsA, knobsB; /// TICKET-050: does this seat's override switch lookahead on? public bool LookaheadOn(Dictionary knobs) => knobs != null && knobs.TryGetValue("lookahead", out var v) && v > 0f && hostMode == "local"; /// "a=1,b=2" -> a dictionary; empty/null -> null. public static Dictionary ParseKnobs(string flag, string value) { if (string.IsNullOrWhiteSpace(value)) return null; var map = new Dictionary(StringComparer.Ordinal); foreach (var part in value.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)) { var eq = part.IndexOf('='); if (eq <= 0) throw new ArgumentException(flag + " expects name=value pairs, got '" + part.Trim() + "'"); var name = part.Substring(0, eq).Trim(); if (!float.TryParse(part.Substring(eq + 1).Trim(), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var v)) throw new ArgumentException(flag + ": '" + part.Trim() + "' is not a number"); map[name] = v; } return map.Count == 0 ? null : map; } /// Round-trip form for the worker command line. public static string FormatKnobs(Dictionary knobs) { if (knobs == null || knobs.Count == 0) return string.Empty; var parts = new List(knobs.Count); foreach (var kv in knobs) parts.Add(kv.Key + "=" + kv.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)); return string.Join(",", parts); } // worker-only public bool worker; public int workerIndex; public int port; public string nameA, nameB, commandA, commandB; public ArenaConfig ToConfig() => new() { deckA = deckA, deckB = deckB, executorA = execA ?? string.Empty, executorB = execB ?? string.Empty, n = n, seed = seed, timeoutSeconds = timeoutSeconds, verboseBots = verbose, outPath = outPath ?? string.Empty, journalDir = journalDir ?? string.Empty, insightA = insightA.HasValue ? Insight.LevelName(insightA.Value) : string.Empty, insightB = insightB.HasValue ? Insight.LevelName(insightB.Value) : string.Empty, hostMode = hostMode, }; private static InsightLevel ParseInsight(string flag, string value) { if (!Insight.TryParseLevel(value, out var level)) throw new ArgumentException(flag + " expects none|hand|full, got '" + value + "'"); return level; } public static Options Parse(string[] args) { var o = new Options(); for (var i = 0; i < args.Length; i++) { var a = args[i]; string Next() { if (i + 1 >= args.Length) throw new ArgumentException(a + " needs a value"); return args[++i]; } int NextInt() { var v = Next(); if (!int.TryParse(v, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n)) throw new ArgumentException(a + " expects an integer, got '" + v + "'"); return n; } switch (a) { case "-h": case "--help": case "/?": o.help = true; break; case "--root": o.root = Next(); break; case "--deckA": o.deckA = Next(); break; case "--deckB": o.deckB = Next(); break; case "--execA": o.execA = Next(); break; case "--execB": o.execB = Next(); break; case "--n": o.n = NextInt(); break; case "--parallel": o.parallel = NextInt(); break; case "--seed": o.seed = NextInt(); break; case "--timeout": o.timeoutSeconds = NextInt(); break; case "--out": o.outPath = Next(); break; case "--replays": o.replaysDir = Next(); break; case "--journal": o.journalDir = Next(); break; case "--port": o.portBase = NextInt(); break; case "--locale": o.locale = Next(); break; case "--verbose": o.verbose = true; break; case "--host": o.hostMode = Next().Trim().ToLowerInvariant(); break; case "--insightA": o.insightA = ParseInsight(a, Next()); break; case "--insightB": o.insightB = ParseInsight(a, Next()); break; case "--knobsA": o.knobsA = ParseKnobs(a, Next()); break; case "--knobsB": o.knobsB = ParseKnobs(a, Next()); break; case "--worker": o.worker = true; o.workerIndex = NextInt(); break; case "--nameA": o.nameA = Next(); break; case "--nameB": o.nameB = Next(); break; case "--commandA": o.commandA = Next(); break; case "--commandB": o.commandB = Next(); break; default: throw new ArgumentException("unknown argument '" + a + "'"); } } if (o.help) return o; o.root = Path.GetFullPath(o.root); if (!Directory.Exists(o.root)) throw new ArgumentException("--root does not exist: " + o.root); if (o.hostMode != "local" && o.hostMode != "server") throw new ArgumentException("--host expects local|server, got '" + o.hostMode + "'"); if (o.worker) { o.port = o.portBase; if (string.IsNullOrEmpty(o.commandA) || string.IsNullOrEmpty(o.commandB)) throw new ArgumentException("worker needs --commandA/--commandB"); if (!string.IsNullOrEmpty(o.journalDir)) o.journalDir = Path.GetFullPath(o.journalDir); return o; } if (string.IsNullOrEmpty(o.deckA)) throw new ArgumentException("--deckA is required"); if (string.IsNullOrEmpty(o.deckB)) throw new ArgumentException("--deckB is required"); if (o.n < 0) throw new ArgumentException("--n must be >= 0"); if (o.parallel < 1) throw new ArgumentException("--parallel must be >= 1"); if (o.timeoutSeconds < 10) throw new ArgumentException("--timeout must be >= 10"); if (o.portBase < 1024 || o.portBase > 60000) throw new ArgumentException("--port must be in 1024..60000"); if (o.hostMode != "local" && o.hostMode != "server") throw new ArgumentException("--host expects local|server, got '" + o.hostMode + "'"); if (!string.IsNullOrEmpty(o.replaysDir)) o.replaysDir = Path.GetFullPath(o.replaysDir); if (!string.IsNullOrEmpty(o.journalDir)) o.journalDir = Path.GetFullPath(o.journalDir); if (!string.IsNullOrEmpty(o.outPath)) o.outPath = Path.GetFullPath(o.outPath); return o; } } }