fix(io): add error handling for missing piece in PgnExporter replay

Replace unsafe fallback to Pawn with explicit exception on invariant
violation. This ensures data corruption in GameContext.moves is detected
immediately rather than producing silently incorrect PGN output.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-05 13:22:13 +02:00
parent 09a70ed435
commit 16a9632e69
@@ -22,7 +22,15 @@ object PgnExporter extends GameContextExport:
var ctx = GameContext.initial var ctx = GameContext.initial
for move <- context.moves do for move <- context.moves do
val color = ctx.turn val color = ctx.turn
val pieceType = ctx.board.pieceAt(move.from).map(_.pieceType).getOrElse(PieceType.Pawn) val pieceType = ctx.board.pieceAt(move.from)
.map(_.pieceType)
.getOrElse {
val fromStr = move.from.toString
val boardStr = ctx.board.pieces.keys.map(_.toString).mkString(",")
throw new IllegalStateException(
s"Invariant violation: no piece at $fromStr during PGN export replay. Board squares: $boardStr"
)
}
val isCapture = ctx.board.pieceAt(move.to).isDefined || move.moveType == MoveType.EnPassant val isCapture = ctx.board.pieceAt(move.to).isDefined || move.moveType == MoveType.EnPassant
val castleSide = move.moveType match val castleSide = move.moveType match
case MoveType.CastleKingside => Some("Kingside") case MoveType.CastleKingside => Some("Kingside")