diff --git a/README.md b/README.md
index d1680f9..6848d78 100644
--- a/README.md
+++ b/README.md
@@ -161,6 +161,46 @@ configurations, datasets, and malformed labels.
Texel loss is not Elo: compare the selected HCE weights against the original
settings in fresh **paired SPRT matches** before changing production defaults.
+##
Replay a PGN4 game against your engine
+
+The `replay` command follows a single recorded four-player Teams game from a
+UTF-8 `.txt` file (e.g. `configs/phantom_mate_game.txt`), with the usual
+**Red, Blue, Yellow, Green** move order. Both coordinate and long-algebraic
+PGN4/SAN notation are accepted, including `Qg9xg2+` and move numbers.
+
+Select which *team* IronPhoenix controls:
+
+~~~powershell
+tunex -c configs/replay.example.json replay --file phantom_mate_game.txt --team BG --report results/phantom_mate_bg.json
+tunex -c configs/replay.example.json replay --file phantom_mate_game.txt --team RY
+~~~
+
+File and optional JSON report paths are resolved relative to the **config file
+directory**. Update `engine.path` in `configs/replay.example.json` first.
+The example uses `go depth 22`, `Threads=1`, and `UseNNUE=false`; adjust
+`search` and `engine.common_options` as required to reproduce an issue.
+
+- `RY`: Tunex searches Red and Yellow turns; Blue and Green play the PGN move.
+- `BG`: Tunex searches Blue and Green turns; Red and Yellow play the PGN move.
+- For engine-controlled turns, the **bestmove** is compared to the PGN move,
+ and the output shows `MATCH` or `DIFFERENT`, plus the engine's score.
+- **Regardless of match or mismatch**, the recorded PGN move is applied.
+ This keeps the replay on the original game line, never on an engine deviation.
+- Only **one** engine process is started and `ucinewgame` is sent **once**.
+ This preserves its history and transposition table across subsequent
+ *engine-controlled searches* (while other turns are forced from the PGN).
+- Every recorded move is checked against IronPhoenix's native legal moves.
+ The command stops with a ply-specific error on invalid or ambiguous notation.
+- The optional report contains all compared plies, the selected engine moves,
+ centipawn or mate scores, and match/mismatch counts.
+
+**Reproduction caveat:** forcing the other team's moves does not recreate
+search work originally performed by a separate opponent engine, and recorded
+moves for the selected team are not searched when the engine's turn is skipped.
+A game originally played with different threading or search limits may still
+produce different scores. This tool is a replay/debugging aid, not a statistical
+strength test.
+
##
Requirements
- Python **3.11+**
diff --git a/configs/phantom_mate_game.txt b/configs/phantom_mate_game.txt
new file mode 100644
index 0000000..8f5380f
--- /dev/null
+++ b/configs/phantom_mate_game.txt
@@ -0,0 +1,8 @@
+# Four-player Teams game: Red Blue Yellow Green
+1. h2-h3 .. b9-c9 .. g13-g12 .. m8-l8
+2. Qg1-j4 .. b7-c7 .. Qh14-g13 .. m6-l6
+3. k2-k4 .. Na10-c11 .. Ne14-f12 .. Qn7-l9
+4. Nj1-i3 .. Qa8-b9 .. Nj14-i12 .. Ql9-g9
+5. Bi1-h2 .. Na5-c6 .. Kg14-h14 .. Nn10-m8
+6. Qj4-j7 .. Qb9-f5 .. Ni12-k11 .. Kn8-n7
+7. d2-d4 .. Qf5xf2 .. Nk11-j9 .. Qg9xg2+
diff --git a/configs/replay.example.json b/configs/replay.example.json
new file mode 100644
index 0000000..6cea9bc
--- /dev/null
+++ b/configs/replay.example.json
@@ -0,0 +1,30 @@
+{
+ "variant": "four_player_teams",
+ "engine": {
+ "path": "C:/path/to/IronPhoenix/out/build/x64-release/ironphoenix.exe",
+ "startup_timeout": 10,
+ "move_timeout": 120,
+ "strict_options": true,
+ "common_options": {
+ "Hash": 64,
+ "MultiPV": 1,
+ "Threads": 1,
+ "UseNNUE": false
+ }
+ },
+ "search": {
+ "mode": "depth",
+ "value": 22
+ },
+ "match": {
+ "games": 2,
+ "paired": true
+ },
+ "baseline": {
+ "name": "unused"
+ },
+ "candidate": {
+ "name": "IronPhoenix PGN replay",
+ "options": {}
+ }
+}
diff --git a/src/tunex/cli.py b/src/tunex/cli.py
index 2584690..b268a34 100644
--- a/src/tunex/cli.py
+++ b/src/tunex/cli.py
@@ -11,6 +11,7 @@
from .match import GameRecord, GameSpec, MatchRunner
from .sprt import SprtState
from .spsa import SpsaRunner
+from .replay import replay_game
from .texel import TexelRunner
from .stats import WDL, format_summary
@@ -188,6 +189,33 @@ def command_texel(config: Config, epochs: int | None) -> int:
return 0
+def command_replay(config: Config, file: str, team: str, report: str | None) -> int:
+ from pathlib import Path
+
+ def progress(entry):
+ status = "MATCH" if entry.matched else "DIFFERENT"
+ print(
+ f"[Replay] ply {entry.ply:02d} {entry.seat} | "
+ f"PGN {entry.recorded} ({entry.recorded_uci}) | "
+ f"engine {entry.engine_move} | {status}"
+ + (f" | mate {entry.score_mate}" if entry.score_mate is not None
+ else f" | cp {entry.score_cp}" if entry.score_cp is not None else ""),
+ flush=True,
+ )
+
+ report_data = replay_game(config, Path(file), team, report_file=report,
+ on_comparison=progress)
+ print(
+ f"[Replay] {report_data.team}: matched {report_data.matched}/"
+ f"{report_data.compared}, different {report_data.mismatched}; "
+ f"forced {report_data.total_plies} recorded plies",
+ flush=True,
+ )
+ if report:
+ print(f"[Replay] JSON report: {report}")
+ return 0
+
+
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="tunex",
@@ -206,6 +234,16 @@ def build_parser() -> argparse.ArgumentParser:
match = sub.add_parser("match", help="run a fixed number of candidate-vs-baseline games")
match.add_argument("--games", type=int, default=None)
+ replay = sub.add_parser(
+ "replay", help="replay a PGN4 TXT game, search RY or BG, force recorded moves"
+ )
+ replay.add_argument("--file", required=True,
+ help="game TXT/PGN path, relative to the config directory")
+ replay.add_argument("--team", required=True, choices=["RY", "BG", "ry", "bg"],
+ help="team controlled by the tested engine")
+ replay.add_argument("--report", default=None,
+ help="optional JSON comparison output path")
+
sub.add_parser("sprt", help="run sequential candidate-vs-baseline testing")
spsa = sub.add_parser("spsa", help="run SPSA parameter tuning")
@@ -225,11 +263,21 @@ def main(argv: list[str] | None = None) -> int:
args = parser.parse_args(argv)
config = _load(args.config)
+ if args.command == "replay":
+ from pathlib import Path
+ config_dir = Path(args.config).resolve().parent
+ for attr in ("file", "report"):
+ value = getattr(args, attr, None)
+ if value and not Path(value).is_absolute():
+ setattr(args, attr, str((config_dir / value).resolve()))
+
try:
if args.command == "probe":
return command_probe(config)
if args.command == "match":
return command_match(config, args.games)
+ if args.command == "replay":
+ return command_replay(config, args.file, args.team, args.report)
if args.command == "sprt":
return command_sprt(config)
if args.command == "spsa":
diff --git a/src/tunex/replay.py b/src/tunex/replay.py
new file mode 100644
index 0000000..6016fb9
--- /dev/null
+++ b/src/tunex/replay.py
@@ -0,0 +1,154 @@
+"""Replay one 4PC PGN4 game and compare one team's searches to recorded moves.
+
+All four moves are *forced* from the game file, including when the tested
+engine disagrees. This preserves the recorded position while allowing the
+same engine process to accumulate search history between its turns.
+"""
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass
+import json
+from pathlib import Path
+import re
+from typing import Callable
+
+from .config import Config
+from .engine import EngineError, UciEngine
+from .match import _position_command, _start_side
+from .notation import coordinate_move, san_to_uci
+
+
+# One four-player round may be written as:
+# 1. h2-h3 .. b9-c9 .. g13-g12 .. m8-l8
+# or the usual spaced PGN numbering, including 1... for the next seat.
+_NUMBER = re.compile(r"^\d+\.(?:\.\.)?$")
+_NUMBER_PREFIX = re.compile(r"^\d+\.(?:\.\.)?")
+_RESULT = {"1-0", "0-1", "1/2-1/2", "*"}
+_TEAM_COLORS = {"RY": {0, 2}, "BG": {1, 3}}
+_SEAT_LABELS = ("R", "B", "Y", "G")
+
+
+@dataclass(frozen=True, slots=True)
+class ReplayComparison:
+ ply: int
+ seat: str
+ recorded: str
+ recorded_uci: str
+ engine_move: str | None
+ matched: bool
+ score_cp: int | None
+ score_mate: int | None
+
+
+@dataclass(frozen=True, slots=True)
+class ReplayReport:
+ team: str
+ total_plies: int
+ compared: int
+ matched: int
+ mismatched: int
+ comparisons: tuple[ReplayComparison, ...]
+
+
+def parse_game(text: str) -> tuple[str, ...]:
+ """Read one game with four moves per round, optional tags and comments.
+
+ A single file is one game, not a line-by-line opening book. Comments in
+ braces, semicolon-to-EOL comments and PGN tags are ignored; variations
+ are rejected to avoid silently replaying a side line.
+ """
+ text = re.sub(r"(?m)^\s*#[^\n]*", "", text)
+ text = re.sub(r";[^\n]*", "", text)
+ text = re.sub(r"\{[^}]*\}", " ", text, flags=re.S)
+ text = re.sub(r"(?m)^\s*\[[^\n]*\]\s*$", "", text)
+ if "(" in text or ")" in text:
+ raise ValueError("PGN variations are not supported; supply the main line only")
+ tokens: list[str] = []
+ for raw in text.split():
+ if raw in {"..", "..."} or _NUMBER.fullmatch(raw):
+ continue
+ token = _NUMBER_PREFIX.sub("", raw)
+ if not token:
+ continue
+ if token in _RESULT:
+ break
+ if token.startswith("$") and token[1:].isdigit():
+ continue
+ tokens.append(token)
+ if not tokens:
+ raise ValueError("PGN replay file contains no moves")
+ return tuple(tokens)
+
+
+def load_game(path: str | Path) -> tuple[str, ...]:
+ return parse_game(Path(path).read_text(encoding="utf-8-sig"))
+
+
+def replay_game(
+ config: Config, game_file: str | Path, team: str,
+ *, report_file: str | Path | None = None,
+ on_comparison: Callable[[ReplayComparison], None] | None = None,
+) -> ReplayReport:
+ if config.variant != "four_player_teams":
+ raise ValueError("PGN replay is supported for four_player_teams only")
+ team = team.upper()
+ if team not in _TEAM_COLORS:
+ raise ValueError("team must be RY or BG")
+ tokens = load_game(game_file)
+ options = dict(config.engine.common_options)
+ options.update(config.candidate.options)
+ comparisons: list[ReplayComparison] = []
+ moves: list[str] = []
+ with UciEngine(
+ config.candidate.path or config.engine.path,
+ name=config.candidate.name,
+ startup_timeout=config.engine.startup_timeout,
+ move_timeout=config.engine.move_timeout,
+ strict_options=config.engine.strict_options,
+ ) as engine:
+ engine.configure(options)
+ # Only reset once. Search history and TT survive across engine turns.
+ engine.new_game()
+ for ply, token in enumerate(tokens, 1):
+ position = _position_command(None, moves)
+ fen, legal = engine.opening_position(position)
+ side = _start_side(fen)
+ seat = _SEAT_LABELS[side]
+ try:
+ recorded = coordinate_move(token)
+ if recorded is None:
+ recorded = san_to_uci(token, fen, legal)
+ if recorded.lower() not in {move.lower() for move in legal}:
+ raise ValueError(f"recorded move {recorded!r} is not legal")
+ except (ValueError, EngineError) as exc:
+ raise EngineError(
+ f"PGN ply {ply} ({seat}), {token!r}: {exc}"
+ ) from exc
+
+ if side in _TEAM_COLORS[team]:
+ search = engine.search(position, config.search.go_command())
+ played = search.bestmove.lower()
+ match = played == recorded.lower()
+ entry = ReplayComparison(
+ ply=ply, seat=seat, recorded=token, recorded_uci=recorded.lower(),
+ engine_move=played, matched=match,
+ score_cp=search.score_cp, score_mate=search.score_mate,
+ )
+ comparisons.append(entry)
+ if on_comparison is not None:
+ on_comparison(entry)
+ # Always apply the PGN move, even when the engine disagrees.
+ # The next engine search includes the entire forced move history.
+ moves.append(recorded.lower())
+
+ matched = sum(entry.matched for entry in comparisons)
+ report = ReplayReport(
+ team=team, total_plies=len(moves), compared=len(comparisons),
+ matched=matched, mismatched=len(comparisons) - matched,
+ comparisons=tuple(comparisons),
+ )
+ if report_file is not None:
+ dest = Path(report_file)
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_text(json.dumps(asdict(report), indent=2) + "\n", encoding="utf-8")
+ return report
diff --git a/tests/test_replay.py b/tests/test_replay.py
new file mode 100644
index 0000000..57bf8c1
--- /dev/null
+++ b/tests/test_replay.py
@@ -0,0 +1,115 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+
+from tunex.config import Config
+from tunex.engine import EngineError, SearchResult
+from tunex.replay import load_game, parse_game, replay_game
+
+
+GAME = """
+1. h2-h3 .. b9-c9 .. g13-g12 .. m8-l8
+2. Qg1-j4 .. b7-c7 .. Qh14-g13 .. m6-l6
+3. k2-k4 .. Na10-c11 .. Ne14-f12 .. Qn7-l9
+4. Nj1-i3 .. Qa8-b9 .. Nj14-i12 .. Ql9-g9
+5. Bi1-h2 .. Na5-c6 .. Kg14-h14 .. Nn10-m8
+6. Qj4-j7 .. Qb9-f5 .. Ni12-k11 .. Kn8-n7
+7. d2-d4 .. Qf5xf2 .. Nk11-j9 .. Qg9xg2+
+"""
+
+
+def test_pgn4_rounds_and_comments():
+ assert len(parse_game(GAME)) == 28
+ assert parse_game('[Event "test"]\n1. e2-e3 .. b7-c7 {note} .. g13-g12 .. m7-l7') == (
+ "e2-e3", "b7-c7", "g13-g12", "m7-l7"
+ )
+ assert parse_game("1. e2-e3 .. b7-c7 .. g13-g12 .. m7-l7 1-0")[-1] == "m7-l7"
+ with pytest.raises(ValueError, match="variations"):
+ parse_game("1. e2-e3 (e2-e4) .. b7-c7")
+ with pytest.raises(ValueError, match="no moves"):
+ parse_game("# nothing")
+
+
+class FakeEngine:
+ instances = []
+
+ def __init__(self, *args, **kwargs):
+ self.commands = []
+ self.moves_seen = []
+ self.resets = 0
+ self.__class__.instances.append(self)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return None
+
+ def configure(self, options):
+ self.options = options
+
+ def new_game(self):
+ self.resets += 1
+
+ def opening_position(self, position):
+ self.commands.append(position)
+ move_count = 0 if " moves " not in position else len(position.split(" moves ", 1)[1].split())
+ seat = ("R", "B", "Y", "G")[move_count % 4]
+ legal = ("h2h3", "b9c9", "g13g12", "m8l8")
+ return seat + "-dummy", (legal[move_count % 4],)
+
+ def search(self, position, go_command):
+ self.moves_seen.append((position, go_command))
+ # Deliberately disagree with every Red+Yellow move except the first.
+ index = len(position.split(" moves ", 1)[1].split()) if " moves " in position else 0
+ return SearchResult(bestmove="h2h3" if index == 0 else "0000", score_mate=13)
+
+
+def test_replay_forces_pgn_and_only_searches_selected_team(tmp_path: Path):
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps({
+ "engine": {"path": "not-real"},
+ "search": {"mode": "depth", "value": 22},
+ }))
+ config = Config.load(config_path)
+ game_file = tmp_path / "game.txt"
+ # The fake engine exposes legal coordinate moves but not a complete FEN4
+ # board, so use UCI here; PGN4 parsing is covered by the test above.
+ game_file.write_text("1. h2h3 .. b9c9 .. g13g12 .. m8l8")
+ output = tmp_path / "report.json"
+ FakeEngine.instances.clear()
+ with patch("tunex.replay.UciEngine", FakeEngine):
+ result = replay_game(config, game_file, "RY", report_file=output)
+ engine = FakeEngine.instances[-1]
+ assert engine.resets == 1
+ assert len(engine.moves_seen) == 2
+ assert engine.moves_seen[0] == ("position startpos", "go depth 22")
+ assert engine.moves_seen[1][0] == "position startpos moves h2h3 b9c9"
+ assert result.matched == 1 and result.mismatched == 1
+ assert result.total_plies == 4
+ assert json.loads(output.read_text())["comparisons"][1]["recorded_uci"] == "g13g12"
+
+ with patch("tunex.replay.UciEngine", FakeEngine):
+ bg = replay_game(config, game_file, "BG")
+ assert bg.compared == 2
+ assert FakeEngine.instances[-1].moves_seen[0][0] == "position startpos moves h2h3"
+ assert FakeEngine.instances[-1].moves_seen[1][0] == (
+ "position startpos moves h2h3 b9c9 g13g12"
+ )
+
+
+def test_invalid_team_and_missing_file(tmp_path: Path):
+ config_path = tmp_path / "config.json"
+ config_path.write_text('{"engine": {"path": "not-real"}}')
+ config = Config.load(config_path)
+ game = tmp_path / "game.txt"
+ game.write_text("1. h2-h3")
+ with pytest.raises(ValueError, match="RY or BG"):
+ replay_game(config, game, "RB")
+ with pytest.raises(FileNotFoundError):
+ load_game(tmp_path / "missing.txt")