From 609e00afa152d4c52b243c44f2d410cd650ca0e0 Mon Sep 17 00:00:00 2001 From: arcestia Date: Wed, 25 Feb 2026 13:29:07 +0700 Subject: [PATCH] :recycle: Refactor protocol into uci package Move protocol handler into internal/protocol/uci, removing the old handler.go and protocol_test.go. Update main import and add StartFEN constant to the engine board. --- internal/engine/board.go | 2 + internal/protocol/handler.go | 670 ----------------------------- internal/protocol/protocol_test.go | 187 -------- internal/protocol/uci/misc.go | 56 +++ internal/protocol/uci/options.go | 86 ++++ internal/protocol/uci/position.go | 49 +++ internal/protocol/uci/search.go | 239 ++++++++++ internal/protocol/uci/uci.go | 98 +++++ internal/protocol/uci/uci_test.go | 146 +++++++ main.go | 6 +- 10 files changed, 679 insertions(+), 860 deletions(-) delete mode 100644 internal/protocol/handler.go delete mode 100644 internal/protocol/protocol_test.go create mode 100644 internal/protocol/uci/misc.go create mode 100644 internal/protocol/uci/options.go create mode 100644 internal/protocol/uci/position.go create mode 100644 internal/protocol/uci/search.go create mode 100644 internal/protocol/uci/uci.go create mode 100644 internal/protocol/uci/uci_test.go diff --git a/internal/engine/board.go b/internal/engine/board.go index 2202578..72284b3 100644 --- a/internal/engine/board.go +++ b/internal/engine/board.go @@ -10,6 +10,8 @@ import ( type CastlingRights uint8 +const StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" + // State represents the irreversible state of the board, used for unmaking moves. type State struct { Move Move diff --git a/internal/protocol/handler.go b/internal/protocol/handler.go deleted file mode 100644 index bd93aeb..0000000 --- a/internal/protocol/handler.go +++ /dev/null @@ -1,670 +0,0 @@ -package protocol - -import ( - "bufio" - "fmt" - "io" - "strconv" - "strings" - "sync/atomic" - "time" - - "github.com/Skiddle-Labs/axon-engine/internal/engine" - "github.com/Skiddle-Labs/axon-engine/internal/eval" - "github.com/Skiddle-Labs/axon-engine/internal/logger" - "github.com/Skiddle-Labs/axon-engine/internal/search" - "github.com/Skiddle-Labs/axon-engine/internal/types" -) - -const startFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" - -// Protocol manages UCI protocol communication. -type Protocol struct { - reader *bufio.Scanner - writer io.Writer - board *engine.Board - search *search.Engine - threads int - multiPV int - moveOverhead int - slowMover int - analyseMode bool - isPondering bool - pendingTimeLimit time.Duration - book *engine.PolyglotBook - bookBestMove bool - bookDepth int - - // Persistent Search Heuristics - historyTable [2][7][64]int - counterMoves [64][64]engine.Move -} - -// NewProtocol creates a new Protocol handler. -func NewProtocol(input io.Reader, output io.Writer) *Protocol { - b := engine.NewBoard() - b.SetFEN(startFEN) - - return &Protocol{ - reader: bufio.NewScanner(input), - writer: output, - board: b, - threads: 1, - multiPV: 1, - moveOverhead: 10, - slowMover: 100, - bookDepth: 255, - } -} - -// Start begins the main loop for processing UCI commands. -func (p *Protocol) Start() { - logger.Info("UCI Protocol handler started") - for p.reader.Scan() { - line := strings.TrimSpace(p.reader.Text()) - if line == "" { - continue - } - - logger.Debug("<< %s", line) - parts := strings.Fields(line) - command := parts[0] - - switch command { - case "uci": - p.handleUCI() - case "isready": - p.handleIsReady() - case "bench": - p.handleBench() - case "position": - p.handlePosition(parts) - case "go": - p.handleGo(parts) - case "stop": - p.handleStop() - case "ponderhit": - p.handlePonderHit() - case "ucinewgame": - p.handleUCINewGame() - case "setoption": - p.handleSetOption(parts) - case "d": - p.handleDisplay() - case "eval": - p.handleEval() - case "quit": - return - default: - // Ignore unknown commands for now - } - } -} - -func (p *Protocol) handleUCI() { - p.send("id name Axon Engine") - p.send("id author Axon Team") - p.send("option name Hash type spin default 64 min 1 max 65536") - p.send("option name Threads type spin default 1 min 1 max 128") - p.send("option name MultiPV type spin default 1 min 1 max 128") - p.send("option name Ponder type check default false") - p.send("option name Move Overhead type spin default 10 min 0 max 5000") - p.send("option name Slow Mover type spin default 100 min 10 max 1000") - p.send("option name Clear Hash type button") - p.send("option name UCI_AnalyseMode type check default false") - p.send("option name UCI_Opponent type string") - p.send("option name Book File type string default ") - p.send("option name Book Best Move type check default false") - p.send("option name Book Depth type spin default 255 min 0 max 255") - p.send("option name Log File type string default ") - p.send("option name Aspiration Delta type spin default 15 min 0 max 500") - p.send("option name RFP Margin type spin default 75 min 0 max 1000") - p.send("option name FP Margin type spin default 100 min 0 max 1000") - p.send("option name NMP Base type spin default 3 min 1 max 10") - p.send("option name NMP Divisor type spin default 6 min 1 max 20") - p.send("option name LMR Base type spin default 75 min 0 max 500") - p.send("option name LMR Divisor type spin default 225 min 10 max 1000") - p.send("uciok") -} - -func (p *Protocol) handleIsReady() { - p.send("readyok") -} - -func (p *Protocol) handlePosition(parts []string) { - if len(parts) < 2 { - return - } - - var fen string - moveIndex := -1 - - for i, part := range parts { - if part == "moves" { - moveIndex = i - break - } - } - - if parts[1] == "startpos" { - fen = startFEN - } else if parts[1] == "fen" { - endIndex := len(parts) - if moveIndex != -1 { - endIndex = moveIndex - } - if endIndex <= 2 { - return - } - fen = strings.Join(parts[2:endIndex], " ") - } else { - return - } - - p.board.SetFEN(fen) - - if moveIndex != -1 { - for i := moveIndex + 1; i < len(parts); i++ { - move := p.parseMove(parts[i]) - if move != engine.NoMove { - p.board.MakeMove(move) - } - } - } -} - -func (p *Protocol) parseMove(moveStr string) engine.Move { - ml := p.board.GenerateMoves() - for i := 0; i < ml.Count; i++ { - m := ml.Moves[i] - - // Verify legality by making and unmaking the move - if !p.board.MakeMove(m) { - continue - } - p.board.UnmakeMove(m) - - s := fmt.Sprintf("%s%s", m.From().String(), m.To().String()) - - if len(moveStr) == 5 { - var pStr string - switch m.Flags() & 0xB000 { - case engine.PromoQueen: - pStr = "q" - case engine.PromoRook: - pStr = "r" - case engine.PromoBishop: - pStr = "b" - case engine.PromoKnight: - pStr = "n" - } - if s+pStr == moveStr { - return m - } - } else if s == moveStr { - return m - } - } - return engine.NoMove -} - -func (p *Protocol) handleGo(parts []string) { - // Probe opening book - if p.board.Ply <= p.bookDepth { - if move, ok := p.book.GetMove(p.board); ok { - p.send(fmt.Sprintf("info depth 1 score cp 0 nodes 0 pv %s", move.String())) - p.send(fmt.Sprintf("bestmove %s", move.String())) - return - } - } - - if p.search != nil { - atomic.StoreInt32(p.search.Stopped, 1) - } - - p.search = search.NewEngine(p.board) - p.search.Threads = p.threads - p.search.MultiPV = p.multiPV - p.search.HistoryTable = &p.historyTable - p.search.CounterMoves = &p.counterMoves - p.isPondering = false - p.pendingTimeLimit = 0 - - ml := p.board.GenerateMoves() - legalCount := 0 - var lastLegal engine.Move - for i := 0; i < ml.Count; i++ { - if p.board.MakeMove(ml.Moves[i]) { - p.board.UnmakeMove(ml.Moves[i]) - legalCount++ - lastLegal = ml.Moves[i] - } - } - - // Optimization: Instant move if only one legal move is available and not pondering - isPonder := false - for _, part := range parts { - if part == "ponder" { - isPonder = true - break - } - } - - if legalCount == 1 && !isPonder { - score := eval.Evaluate(p.board) - p.send(fmt.Sprintf("info depth 1 score cp %d nodes 0 pv %s", score, lastLegal.String())) - p.send(fmt.Sprintf("bestmove %s", lastLegal.String())) - return - } - - p.send(fmt.Sprintf("info string searching with %d threads", p.threads)) - - depth := 128 - var timeLimit time.Duration - - wtime, btime := -1, -1 - winc, binc := 0, 0 - movestogo := 0 - movetime := -1 - nodesLimit := uint64(0) - - for i := 1; i < len(parts); i++ { - switch parts[i] { - case "ponder": - p.isPondering = true - case "depth": - if i+1 < len(parts) { - if d, err := strconv.Atoi(parts[i+1]); err == nil { - depth = d - } - i++ - } - case "wtime": - if i+1 < len(parts) { - wtime, _ = strconv.Atoi(parts[i+1]) - i++ - } - case "btime": - if i+1 < len(parts) { - btime, _ = strconv.Atoi(parts[i+1]) - i++ - } - case "winc": - if i+1 < len(parts) { - winc, _ = strconv.Atoi(parts[i+1]) - i++ - } - case "binc": - if i+1 < len(parts) { - binc, _ = strconv.Atoi(parts[i+1]) - i++ - } - case "movestogo": - if i+1 < len(parts) { - movestogo, _ = strconv.Atoi(parts[i+1]) - i++ - } - case "movetime": - if i+1 < len(parts) { - movetime, _ = strconv.Atoi(parts[i+1]) - i++ - } - case "nodes": - if i+1 < len(parts) { - if n, err := strconv.ParseUint(parts[i+1], 10, 64); err == nil { - nodesLimit = n - } - i++ - } - case "infinite": - depth = 128 - } - } - - if movetime > 0 { - timeLimit = time.Duration(movetime) * time.Millisecond - } else { - myTime := wtime - myInc := winc - if p.board.SideToMove == types.Black { - myTime = btime - myInc = binc - } - - if myTime >= 0 { - mtg := movestogo - if mtg <= 0 { - // Dynamic moves-to-go allocation: be more aggressive in midgame - // (higher piece count -> lower mtg) and more conservative in endgame - // (lower piece count -> higher mtg) to maintain a safer reserve. - occCount := p.board.Occupancy().Count() - mtg = 50 - occCount - if mtg < 20 { - mtg = 20 - } - } - - // Allocate time, leaving a safety buffer from the increment. - timeLimit = time.Duration(myTime/mtg)*time.Millisecond + time.Duration(myInc)*8/10*time.Millisecond - } - } - - if timeLimit > 0 { - timeLimit = (timeLimit * time.Duration(p.slowMover)) / 100 - timeLimit -= time.Duration(p.moveOverhead) * time.Millisecond - if timeLimit < 1*time.Millisecond { - timeLimit = 1 * time.Millisecond - } - - logger.Info("Time allocation: %v (Soft limit: %v)", timeLimit, (timeLimit*6)/10) - - if !p.isPondering { - p.search.TimeLimit = timeLimit - p.search.SoftLimit = (timeLimit * 6) / 10 - } else { - p.pendingTimeLimit = timeLimit - } - } - - p.search.NodesLimit = nodesLimit - - go func(e *search.Engine, d int) { - bestMove := e.Search(d) - - for p.isPondering { - time.Sleep(10 * time.Millisecond) - if atomic.LoadInt32(e.Stopped) != 0 { - break - } - } - - if bestMove == engine.NoMove { - ml := e.Board.GenerateMoves() - if ml.Count > 0 { - bestMove = ml.Moves[0] - score := eval.Evaluate(e.Board) - p.send(fmt.Sprintf("info depth 1 score cp %d nodes %d pv %s", score, atomic.LoadUint64(e.Nodes), bestMove.String())) - } else { - return - } - } - - moveStr := bestMove.String() - - // Get ponder move from TT - ponderMoveStr := "" - tempBoard := *e.Board - if tempBoard.MakeMove(bestMove) { - _, ponderMove, found := search.GlobalTT.Probe(tempBoard.Hash, 0, -search.Infinity, search.Infinity, tempBoard.Ply) - if found && ponderMove != engine.NoMove { - // Verify legality - ml := tempBoard.GenerateMoves() - for i := 0; i < ml.Count; i++ { - if ml.Moves[i] == ponderMove { - if tempBoard.MakeMove(ponderMove) { - ponderMoveStr = ponderMove.String() - } - break - } - } - } - } - - if ponderMoveStr != "" { - p.send(fmt.Sprintf("bestmove %s ponder %s", moveStr, ponderMoveStr)) - } else { - p.send(fmt.Sprintf("bestmove %s", moveStr)) - } - logger.Info("Search finished. Best move: %s", moveStr) - - // Age persistent history table to favor more recent search results - for c := 0; c < 2; c++ { - for pt := 0; pt < 7; pt++ { - for sq := 0; sq < 64; sq++ { - p.historyTable[c][pt][sq] /= 2 - } - } - } - }(p.search, depth) -} - -func (p *Protocol) handleStop() { - p.isPondering = false - if p.search != nil { - atomic.StoreInt32(p.search.Stopped, 1) - } -} - -func (p *Protocol) handlePonderHit() { - if !p.isPondering { - return - } - p.isPondering = false - if p.search != nil && p.pendingTimeLimit > 0 { - p.search.TimeLimit = p.pendingTimeLimit - p.search.StartTime = time.Now() - } -} - -func (p *Protocol) handleUCINewGame() { - p.board.Clear() - p.board.SetFEN(startFEN) - search.GlobalTT.Clear() - eval.GlobalPawnTable.Clear() - - // Reset persistent heuristics for a new game - p.historyTable = [2][7][64]int{} - p.counterMoves = [64][64]engine.Move{} -} - -func (p *Protocol) handleSetOption(parts []string) { - logger.Info("SetOption: %v", parts) - namePart := "" - valuePart := "" - parsingName := false - parsingValue := false - - for i := 0; i < len(parts); i++ { - if parts[i] == "name" { - parsingName = true - parsingValue = false - continue - } - if parts[i] == "value" { - parsingName = false - parsingValue = true - continue - } - - if parsingName { - if namePart != "" { - namePart += " " - } - namePart += parts[i] - } else if parsingValue { - if valuePart != "" { - valuePart += " " - } - valuePart += parts[i] - } - } - - name := strings.ToLower(namePart) - value := valuePart - - if name == "hash" { - if size, err := strconv.Atoi(value); err == nil { - search.GlobalTT = search.NewTranspositionTable(size) - } - } else if name == "threads" { - if t, err := strconv.Atoi(value); err == nil { - p.threads = t - } - } else if name == "multipv" { - if m, err := strconv.Atoi(value); err == nil { - p.multiPV = m - } - } else if name == "move overhead" { - if v, err := strconv.Atoi(value); err == nil { - p.moveOverhead = v - } - } else if name == "slow mover" { - if v, err := strconv.Atoi(value); err == nil { - p.slowMover = v - } - } else if name == "clear hash" { - search.GlobalTT.Clear() - eval.GlobalPawnTable.Clear() - } else if name == "uci_analysemode" { - p.analyseMode = value == "true" - } else if name == "uci_opponent" { - // Standard UCI option - } else if name == "book file" { - if p.book != nil { - p.book.Close() - } - if value != "" && value != "" { - var err error - p.book, err = engine.OpenBook(value) - if err != nil { - p.send(fmt.Sprintf("info string Error opening book: %v", err)) - } else if p.book != nil { - p.book.Options.BestMove = p.bookBestMove - } - } else { - p.book = nil - } - } else if name == "book best move" { - p.bookBestMove = value == "true" - if p.book != nil { - p.book.Options.BestMove = p.bookBestMove - } - } else if name == "book depth" { - if v, err := strconv.Atoi(value); err == nil { - p.bookDepth = v - } - } else if name == "log file" { - if err := logger.SetFile(value); err != nil { - p.send(fmt.Sprintf("info string Error opening log file: %v", err)) - } else { - logger.SetEnabled(true) - logger.Info("Logging enabled to file: %s", value) - } - } else if name == "aspiration delta" { - if v, err := strconv.Atoi(value); err == nil { - search.AspirationDelta = v - } - } else if name == "rfp margin" { - if v, err := strconv.Atoi(value); err == nil { - search.RFPMargin = v - } - } else if name == "fp margin" { - if v, err := strconv.Atoi(value); err == nil { - search.FPMargin = v - } - } else if name == "nmp base" { - if v, err := strconv.Atoi(value); err == nil { - search.NMPBase = v - } - } else if name == "nmp divisor" { - if v, err := strconv.Atoi(value); err == nil { - search.NMPDivisor = v - } - } else if name == "lmr base" { - if v, err := strconv.Atoi(value); err == nil { - search.UpdateLMR(float64(v)/100.0, search.LMRDivisor) - } - } else if name == "lmr divisor" { - if v, err := strconv.Atoi(value); err == nil { - search.UpdateLMR(search.LMRBase, float64(v)/100.0) - } - } -} - -func (p *Protocol) handleDisplay() { - p.send(p.board.String()) -} - -func (p *Protocol) handleEval() { - score := eval.Evaluate(p.board) - p.send(fmt.Sprintf("Evaluation: %d cp", score)) - - typeNames := []string{"None", "Pawn", "Knight", "Bishop", "Rook", "Queen", "King"} - - p.send("Material breakdown:") - whiteMg, whiteEg := 0, 0 - blackMg, blackEg := 0, 0 - - for pt := types.Pawn; pt <= types.Queen; pt++ { - wCount := p.board.Pieces[types.White][pt].Count() - bCount := p.board.Pieces[types.Black][pt].Count() - - var mg, eg int - switch pt { - case types.Pawn: - mg, eg = eval.PawnMG, eval.PawnEG - case types.Knight: - mg, eg = eval.KnightMG, eval.KnightEG - case types.Bishop: - mg, eg = eval.BishopMG, eval.BishopEG - case types.Rook: - mg, eg = eval.RookMG, eval.RookEG - case types.Queen: - mg, eg = eval.QueenMG, eval.QueenEG - } - - whiteMg += wCount * mg - whiteEg += wCount * eg - blackMg += bCount * mg - blackEg += bCount * eg - - if wCount > 0 || bCount > 0 { - p.send(fmt.Sprintf(" %-8s | White: %2d (MG: %4d, EG: %4d) | Black: %2d (MG: %4d, EG: %4d)", - typeNames[pt], wCount, wCount*mg, wCount*eg, bCount, bCount*mg, bCount*eg)) - } - } - - p.send(fmt.Sprintf(" %-8s | White: (MG: %4d, EG: %4d) | Black: (MG: %4d, EG: %4d)", - "Total", whiteMg, whiteEg, blackMg, blackEg)) -} - -func (p *Protocol) handleBench() { - positions := []string{ - "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", - "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1", - "8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1", - "r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1", - "rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8", - "r4rk1/1pp1qppp/p1np1n2/2b1p1B1/2B1P1b1/P1NP1N2/1PP1QPPP/R4RK1 w - - 0 10", - } - - totalNodes := uint64(0) - startTime := time.Now() - - for _, fen := range positions { - p.board.SetFEN(fen) - p.search = search.NewEngine(p.board) - p.search.Threads = p.threads - p.search.NodesLimit = 0 - p.search.TimeLimit = 0 - - p.send(fmt.Sprintf("Benchmarking position: %s", fen)) - p.search.Search(10) // Search to depth 10 - totalNodes += atomic.LoadUint64(p.search.Nodes) - } - - duration := time.Since(startTime).Seconds() - nps := uint64(0) - if duration > 0 { - nps = uint64(float64(totalNodes) / duration) - } - - p.send(fmt.Sprintf("\nTotal nodes: %d", totalNodes)) - p.send(fmt.Sprintf("Time: %.3f s", duration)) - p.send(fmt.Sprintf("Nodes per second: %d", nps)) -} - -func (p *Protocol) send(msg string) { - logger.Debug(">> %s", msg) - fmt.Fprintln(p.writer, msg) -} diff --git a/internal/protocol/protocol_test.go b/internal/protocol/protocol_test.go deleted file mode 100644 index 1ddb884..0000000 --- a/internal/protocol/protocol_test.go +++ /dev/null @@ -1,187 +0,0 @@ -package protocol - -import ( - "bytes" - "strings" - "testing" - "time" - - "github.com/Skiddle-Labs/axon-engine/internal/search" -) - -// TestProtocol_Handshake tests the basic UCI initialization sequence. -func TestProtocol_Handshake(t *testing.T) { - input := "uci\nisready\nquit\n" - var output bytes.Buffer - p := NewProtocol(strings.NewReader(input), &output) - p.Start() - - got := output.String() - - expectedIDs := []string{ - "id name Axon Engine", - "id author Axon Team", - "option name Hash type spin default 64 min 1 max 65536", - "option name Threads type spin default 1 min 1 max 128", - "option name MultiPV type spin default 1 min 1 max 128", - "option name Ponder type check default false", - "option name Move Overhead type spin default 10 min 0 max 5000", - "option name Slow Mover type spin default 100 min 10 max 1000", - "option name Clear Hash type button", - "option name UCI_AnalyseMode type check default false", - "option name UCI_Opponent type string", - "option name Book File type string default ", - "option name Book Best Move type check default false", - "option name Book Depth type spin default 255 min 0 max 255", - "uciok", - "readyok", - } - - for _, expected := range expectedIDs { - if !strings.Contains(got, expected) { - t.Errorf("Protocol output missing expected string: %q\nFull output:\n%s", expected, got) - } - } -} - -// TestProtocol_DisplayCommand verifies that the 'd' command renders the engine. -func TestProtocol_DisplayCommand(t *testing.T) { - input := "position startpos\nd\nquit\n" - var output bytes.Buffer - p := NewProtocol(strings.NewReader(input), &output) - p.Start() - - got := output.String() - - // Check for board frame - if !strings.Contains(got, "+---+---+---+---+---+---+---+---+") { - t.Error("Display command 'd' did not output a board frame") - } - - // Check for initial pieces in rank 1 and 8 - if !strings.Contains(got, "R | N | B | Q | K | B | N | R") { - t.Error("Initial White pieces not found in board display") - } - if !strings.Contains(got, "r | n | b | q | k | b | n | r") { - t.Error("Initial Black pieces not found in board display") - } -} - -// TestProtocol_PositionParsing verifies that FEN loading and move application works. -func TestProtocol_PositionParsing(t *testing.T) { - // FEN for 1. e4 - fen := "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1" - input := "position fen " + fen + "\nd\nquit\n" - var output bytes.Buffer - p := NewProtocol(strings.NewReader(input), &output) - p.Start() - - got := output.String() - - // The pawn should be on rank 4 (labeled "4 |") at file e (index 4 in the 8x8 grid) - // In the engine.String() implementation: "4 | . | . | . | . | P | . | . | . |" - if !strings.Contains(got, "4 | . | . | . | . | P | . | . | . |") { - t.Errorf("Pawn not found at e4 in FEN position. Got:\n%s", got) - } -} - -// TestProtocol_SetOption tests the UCI option configuration. -func TestProtocol_SetOption(t *testing.T) { - // We test the 'setoption' command for Hash. - // This ensures the parser correctly identifies the command. - input := "setoption name Hash value 128\nquit\n" - var output bytes.Buffer - p := NewProtocol(strings.NewReader(input), &output) - - // We run it mainly to ensure no panics or errors occur during command parsing. - p.Start() -} - -func TestProtocol_SetOptionValues(t *testing.T) { - p := NewProtocol(strings.NewReader(""), &bytes.Buffer{}) - - p.handleSetOption([]string{"setoption", "name", "Threads", "value", "4"}) - if p.threads != 4 { - t.Fatalf("expected Threads to be 4, got %d", p.threads) - } - - p.handleSetOption([]string{"setoption", "name", "MultiPV", "value", "3"}) - if p.multiPV != 3 { - t.Fatalf("expected MultiPV to be 3, got %d", p.multiPV) - } - - oldTT := search.GlobalTT - p.handleSetOption([]string{"setoption", "name", "Hash", "value", "128"}) - if search.GlobalTT == oldTT { - t.Fatal("expected Hash setoption to replace the transposition table") - } - - p.handleSetOption([]string{"setoption", "name", "Move", "Overhead", "value", "50"}) - if p.moveOverhead != 50 { - t.Fatalf("expected Move Overhead to be 50, got %d", p.moveOverhead) - } - - p.handleSetOption([]string{"setoption", "name", "Book", "Best", "Move", "value", "true"}) - if !p.bookBestMove { - t.Fatal("expected Book Best Move to be true") - } - - p.handleSetOption([]string{"setoption", "name", "Book", "Depth", "value", "10"}) - if p.bookDepth != 10 { - t.Fatalf("expected Book Depth to be 10, got %d", p.bookDepth) - } -} - -func TestProtocol_SetOptionInvalidTokens(t *testing.T) { - p := NewProtocol(strings.NewReader(""), &bytes.Buffer{}) - p.handleSetOption([]string{"setoption", "name", "Threads"}) - if p.threads != 1 { - t.Fatalf("expected Threads to remain default 1, got %d", p.threads) - } -} - -// TestProtocol_UCINewGame tests the ucinewgame command. -func TestProtocol_UCINewGame(t *testing.T) { - input := "ucinewgame\nquit\n" - var output bytes.Buffer - p := NewProtocol(strings.NewReader(input), &output) - p.Start() -} - -// TestProtocol_ParseMove verifies that algebraic move strings are correctly mapped to internal moves. -func TestProtocol_ParseMove(t *testing.T) { - input := "position startpos moves e2e4 e7e5\nd\nquit\n" - var output bytes.Buffer - p := NewProtocol(strings.NewReader(input), &output) - p.Start() - - got := output.String() - - // Verify e4 pawn - if !strings.Contains(got, "4 | . | . | . | . | P | . | . | . |") { - t.Error("White pawn not found on e4 after 'moves e2e4'") - } - // Verify e5 pawn - if !strings.Contains(got, "5 | . | . | . | . | p | . | . | . |") { - t.Error("Black pawn not found on e5 after 'moves e7e5'") - } -} - -func TestProtocol_PonderLogic(t *testing.T) { - input := "uci\nisready\nposition startpos\ngo ponder wtime 100000 btime 100000\nponderhit\nstop\nquit\n" - var output bytes.Buffer - p := NewProtocol(strings.NewReader(input), &output) - - done := make(chan bool) - go func() { - p.Start() - done <- true - }() - - select { - case <-done: - // Success - case <-time.After(2 * time.Second): - t.Fatal("Protocol loop timed out during ponder test") - } -} diff --git a/internal/protocol/uci/misc.go b/internal/protocol/uci/misc.go new file mode 100644 index 0000000..7ec281b --- /dev/null +++ b/internal/protocol/uci/misc.go @@ -0,0 +1,56 @@ +package uci + +import ( + "fmt" + "strconv" + "sync/atomic" + "time" + + "github.com/Skiddle-Labs/axon-engine/internal/engine" + "github.com/Skiddle-Labs/axon-engine/internal/eval" + "github.com/Skiddle-Labs/axon-engine/internal/search" +) + +func (u *UCI) handleIsReady() { + u.send("readyok") +} + +func (u *UCI) handleUCINewGame() { + if u.engine != nil { + atomic.StoreInt32(u.engine.Stopped, 1) + } + search.GlobalTT.Clear() + u.board = engine.NewBoard() + u.historyTable = [2][7][64]int{} + u.counterMoves = [64][64]engine.Move{} +} + +func (u *UCI) handleEval() { + score := eval.Evaluate(u.board) + u.send(fmt.Sprintf("Evaluation: %d", score)) +} + +func (u *UCI) handleBench(fields []string) { + depth := 10 + if len(fields) > 1 { + if d, err := strconv.Atoi(fields[1]); err == nil { + depth = d + } + } + + u.board.SetFEN(engine.StartFEN) + eng := search.NewEngine(u.board) + eng.Silent = true + + start := time.Now() + eng.Search(depth) + elapsed := time.Since(start) + + nodes := atomic.LoadUint64(eng.Nodes) + nps := uint64(0) + if elapsed.Seconds() > 0.001 { + nps = uint64(float64(nodes) / elapsed.Seconds()) + } + + u.send(fmt.Sprintf("Bench: %d nodes, %d nps, %v time", nodes, nps, elapsed)) +} diff --git a/internal/protocol/uci/options.go b/internal/protocol/uci/options.go new file mode 100644 index 0000000..8e5302d --- /dev/null +++ b/internal/protocol/uci/options.go @@ -0,0 +1,86 @@ +package uci + +import ( + "strconv" + "strings" + + "github.com/Skiddle-Labs/axon-engine/internal/engine" + "github.com/Skiddle-Labs/axon-engine/internal/search" +) + +func (u *UCI) handleUCI() { + u.send("id name Axon Engine") + u.send("id author Skiddle Labs") + + // Options + u.send("option name Threads type spin default 1 min 1 max 512") + u.send("option name MultiPV type spin default 1 min 1 max 500") + u.send("option name Hash type spin default 64 min 1 max 1048576") + u.send("option name Move Overhead type spin default 10 min 0 max 5000") + u.send("option name Slow Mover type spin default 100 min 10 max 1000") + u.send("option name Clear Hash type button") + u.send("option name OwnBook type check default true") + u.send("option name BookPath type string default ") + + u.send("uciok") +} + +func (u *UCI) handleSetOption(fields []string) { + // Format: setoption name [value ] + name := "" + value := "" + for i := 1; i < len(fields); i++ { + if fields[i] == "name" && i+1 < len(fields) { + name = strings.ToLower(fields[i+1]) + // Multi-word names + curr := i + 2 + for curr < len(fields) && fields[curr] != "value" { + name += " " + strings.ToLower(fields[curr]) + curr++ + } + i = curr - 1 + } else if fields[i] == "value" { + if i+1 < len(fields) { + value = strings.Join(fields[i+1:], " ") + } + break + } + } + + switch name { + case "threads": + if v, err := strconv.Atoi(value); err == nil { + u.threads = v + } + case "multipv": + if v, err := strconv.Atoi(value); err == nil { + u.multiPV = v + } + case "hash": + if v, err := strconv.Atoi(value); err == nil { + search.GlobalTT = search.NewTranspositionTable(v) + } + case "move overhead": + if v, err := strconv.Atoi(value); err == nil { + u.moveOverhead = v + } + case "slow mover": + if v, err := strconv.Atoi(value); err == nil { + u.slowMover = v + } + case "clear hash": + search.GlobalTT.Clear() + case "ownbook": + u.bookBestMove = (value == "true") + case "bookpath": + if value != "" { + book, err := engine.OpenBook(value) + if err == nil { + if u.book != nil { + u.book.Close() + } + u.book = book + } + } + } +} diff --git a/internal/protocol/uci/position.go b/internal/protocol/uci/position.go new file mode 100644 index 0000000..4c84a85 --- /dev/null +++ b/internal/protocol/uci/position.go @@ -0,0 +1,49 @@ +package uci + +import ( + "strings" + + "github.com/Skiddle-Labs/axon-engine/internal/engine" +) + +func (u *UCI) handlePosition(fields []string) { + if len(fields) < 2 { + return + } + + index := 2 + if fields[1] == "startpos" { + u.board.SetFEN(engine.StartFEN) + } else if fields[1] == "fen" { + fenParts := []string{} + for index < len(fields) && fields[index] != "moves" { + fenParts = append(fenParts, fields[index]) + index++ + } + u.board.SetFEN(strings.Join(fenParts, " ")) + } + + // Process moves + for index < len(fields) { + if fields[index] == "moves" { + index++ + continue + } + moveStr := fields[index] + move := u.parseMove(moveStr) + if move != engine.NoMove { + u.board.MakeMove(move) + } + index++ + } +} + +func (u *UCI) parseMove(moveStr string) engine.Move { + ml := u.board.GenerateMoves() + for i := 0; i < ml.Count; i++ { + if ml.Moves[i].String() == moveStr { + return ml.Moves[i] + } + } + return engine.NoMove +} diff --git a/internal/protocol/uci/search.go b/internal/protocol/uci/search.go new file mode 100644 index 0000000..bed7cae --- /dev/null +++ b/internal/protocol/uci/search.go @@ -0,0 +1,239 @@ +package uci + +import ( + "fmt" + "strconv" + "sync/atomic" + "time" + + "github.com/Skiddle-Labs/axon-engine/internal/engine" + "github.com/Skiddle-Labs/axon-engine/internal/eval" + "github.com/Skiddle-Labs/axon-engine/internal/search" + "github.com/Skiddle-Labs/axon-engine/internal/types" +) + +func (u *UCI) handleGo(parts []string) { + // 1. Check book + if u.board.Ply <= u.bookDepth && u.book != nil { + if move, ok := u.book.GetMove(u.board); ok { + u.send(fmt.Sprintf("info depth 1 score cp 0 nodes 0 pv %s", move.String())) + u.send(fmt.Sprintf("bestmove %s", move.String())) + return + } + } + + // 2. Optimization: Instant move if only one legal move is available and not pondering + isPonder := false + for _, part := range parts { + if part == "ponder" { + isPonder = true + break + } + } + + ml := u.board.GenerateMoves() + legalCount := 0 + var lastLegal engine.Move + for i := 0; i < ml.Count; i++ { + if u.board.MakeMove(ml.Moves[i]) { + u.board.UnmakeMove(ml.Moves[i]) + legalCount++ + lastLegal = ml.Moves[i] + } + } + + if legalCount == 1 && !isPonder { + score := eval.Evaluate(u.board) + u.send(fmt.Sprintf("info depth 1 score cp %d nodes 0 pv %s", score, lastLegal.String())) + u.send(fmt.Sprintf("bestmove %s", lastLegal.String())) + return + } + + // 3. Stop previous search + if u.engine != nil { + atomic.StoreInt32(u.engine.Stopped, 1) + } + + // 4. Setup engine instance + u.engine = search.NewEngine(u.board) + u.engine.Threads = u.threads + u.engine.MultiPV = u.multiPV + u.engine.HistoryTable = &u.historyTable + u.engine.CounterMoves = &u.counterMoves + u.isPondering = false + u.pendingTimeLimit = 0 + + // 5. Parse 'go' arguments + depth := 128 + var timeLimit time.Duration + wtime, btime := -1, -1 + winc, binc := 0, 0 + movestogo := 0 + movetime := -1 + nodesLimit := uint64(0) + + for i := 1; i < len(parts); i++ { + switch parts[i] { + case "ponder": + u.isPondering = true + case "depth": + if i+1 < len(parts) { + depth, _ = strconv.Atoi(parts[i+1]) + i++ + } + case "wtime": + if i+1 < len(parts) { + wtime, _ = strconv.Atoi(parts[i+1]) + i++ + } + case "btime": + if i+1 < len(parts) { + btime, _ = strconv.Atoi(parts[i+1]) + i++ + } + case "winc": + if i+1 < len(parts) { + winc, _ = strconv.Atoi(parts[i+1]) + i++ + } + case "binc": + if i+1 < len(parts) { + binc, _ = strconv.Atoi(parts[i+1]) + i++ + } + case "movestogo": + if i+1 < len(parts) { + movestogo, _ = strconv.Atoi(parts[i+1]) + i++ + } + case "movetime": + if i+1 < len(parts) { + movetime, _ = strconv.Atoi(parts[i+1]) + i++ + } + case "nodes": + if i+1 < len(parts) { + n, _ := strconv.ParseUint(parts[i+1], 10, 64) + nodesLimit = n + i++ + } + case "infinite": + depth = 128 + } + } + + // 6. Time Management + if movetime > 0 { + timeLimit = time.Duration(movetime) * time.Millisecond + } else { + myTime := wtime + myInc := winc + if u.board.SideToMove == types.Black { + myTime = btime + myInc = binc + } + + if myTime >= 0 { + mtg := movestogo + if mtg <= 0 { + occCount := u.board.Occupancy().Count() + mtg = 50 - occCount + if mtg < 20 { + mtg = 20 + } + } + timeLimit = time.Duration(myTime/mtg)*time.Millisecond + time.Duration(myInc)*8/10*time.Millisecond + } + } + + if timeLimit > 0 { + timeLimit = (timeLimit * time.Duration(u.slowMover)) / 100 + timeLimit -= time.Duration(u.moveOverhead) * time.Millisecond + if timeLimit < 1*time.Millisecond { + timeLimit = 1 * time.Millisecond + } + + if !u.isPondering { + u.engine.TimeLimit = timeLimit + u.engine.SoftLimit = (timeLimit * 6) / 10 + } else { + u.pendingTimeLimit = timeLimit + } + } + + u.engine.NodesLimit = nodesLimit + + // 7. Launch Search in a background goroutine + go func(e *search.Engine, d int) { + bestMove := e.Search(d) + + // If we are in ponder mode, wait for ponderhit or stop + for u.isPondering { + time.Sleep(10 * time.Millisecond) + if atomic.LoadInt32(e.Stopped) != 0 { + break + } + } + + if bestMove == engine.NoMove { + ml := e.Board.GenerateMoves() + if ml.Count > 0 { + bestMove = ml.Moves[0] + // Send a final info string for the fallback move to satisfy engine controllers + score := eval.Evaluate(e.Board) + u.send(fmt.Sprintf("info depth 1 score cp %d nodes %d pv %s", score, atomic.LoadUint64(e.Nodes), bestMove.String())) + } else { + return // Terminal state (mate/stalemate) + } + } + + // Probing the TT for a ponder move + ponderMoveStr := "" + tempBoard := *e.Board + if tempBoard.MakeMove(bestMove) { + _, pMove, found := search.GlobalTT.Probe(tempBoard.Hash, 0, -search.Infinity, search.Infinity, 0) + if found && pMove != engine.NoMove { + // Verify legality of the ponder move + pml := tempBoard.GenerateMoves() + for i := 0; i < pml.Count; i++ { + if pml.Moves[i] == pMove { + if tempBoard.MakeMove(pMove) { + ponderMoveStr = pMove.String() + } + break + } + } + } + } + + if ponderMoveStr != "" { + u.send(fmt.Sprintf("bestmove %s ponder %s", bestMove.String(), ponderMoveStr)) + } else { + u.send(fmt.Sprintf("bestmove %s", bestMove.String())) + } + + // Age history tables for the next search + for c := 0; c < 2; c++ { + for pt := 0; pt < 7; pt++ { + for sq := 0; sq < 64; sq++ { + u.historyTable[c][pt][sq] /= 2 + } + } + } + }(u.engine, depth) +} + +func (u *UCI) handleStop() { + if u.engine != nil { + atomic.StoreInt32(u.engine.Stopped, 1) + } + u.isPondering = false +} + +func (u *UCI) handlePonderHit() { + u.isPondering = false + if u.engine != nil && u.pendingTimeLimit > 0 { + u.engine.TimeLimit = u.pendingTimeLimit + u.engine.SoftLimit = (u.pendingTimeLimit * 6) / 10 + } +} diff --git a/internal/protocol/uci/uci.go b/internal/protocol/uci/uci.go new file mode 100644 index 0000000..280223c --- /dev/null +++ b/internal/protocol/uci/uci.go @@ -0,0 +1,98 @@ +package uci + +import ( + "bufio" + "fmt" + "io" + "strings" + "time" + + "github.com/Skiddle-Labs/axon-engine/internal/engine" + "github.com/Skiddle-Labs/axon-engine/internal/search" +) + +// UCI represents the state of a UCI protocol session. +type UCI struct { + reader *bufio.Scanner + writer io.Writer + + board *engine.Board + engine *search.Engine + + // Configurable options + threads int + multiPV int + moveOverhead int + slowMover int + + // Book settings + book *engine.PolyglotBook + bookDepth int + bookBestMove bool + + // Search state + isPondering bool + pendingTimeLimit time.Duration + + // Persistent heuristic tables + historyTable [2][7][64]int + counterMoves [64][64]engine.Move +} + +// NewUCI creates a new UCI protocol handler. +func NewUCI(r io.Reader, w io.Writer) *UCI { + return &UCI{ + reader: bufio.NewScanner(r), + writer: w, + board: engine.NewBoard(), + threads: 1, + multiPV: 1, + moveOverhead: 10, + slowMover: 100, + bookDepth: 255, + } +} + +// Start runs the main UCI loop. +func (u *UCI) Start() { + for u.reader.Scan() { + line := strings.TrimSpace(u.reader.Text()) + if line == "" { + continue + } + + fields := strings.Fields(line) + command := fields[0] + + switch command { + case "uci": + u.handleUCI() + case "isready": + u.handleIsReady() + case "setoption": + u.handleSetOption(fields) + case "ucinewgame": + u.handleUCINewGame() + case "position": + u.handlePosition(fields) + case "go": + u.handleGo(fields) + case "stop": + u.handleStop() + case "ponderhit": + u.handlePonderHit() + case "quit": + return + case "display", "d": + fmt.Fprintln(u.writer, u.board.String()) + case "eval": + u.handleEval() + case "bench": + u.handleBench(fields) + } + } +} + +func (u *UCI) send(s string) { + fmt.Fprintln(u.writer, s) +} diff --git a/internal/protocol/uci/uci_test.go b/internal/protocol/uci/uci_test.go new file mode 100644 index 0000000..d35a3bf --- /dev/null +++ b/internal/protocol/uci/uci_test.go @@ -0,0 +1,146 @@ +package uci + +import ( + "bytes" + "strings" + "testing" + "time" + + "github.com/Skiddle-Labs/axon-engine/internal/search" +) + +// TestUCI_Handshake tests the basic UCI initialization sequence. +func TestUCI_Handshake(t *testing.T) { + input := "uci\nisready\nquit\n" + var output bytes.Buffer + u := NewUCI(strings.NewReader(input), &output) + u.Start() + + got := output.String() + + expectedStrings := []string{ + "id name Axon Engine", + "id author Skiddle Labs", + "option name Threads type spin default 1 min 1 max 512", + "option name MultiPV type spin default 1 min 1 max 500", + "option name Hash type spin default 64 min 1 max 1048576", + "option name Move Overhead type spin default 10 min 0 max 5000", + "option name Slow Mover type spin default 100 min 10 max 1000", + "option name Clear Hash type button", + "option name OwnBook type check default true", + "option name BookPath type string default ", + "uciok", + "readyok", + } + + for _, expected := range expectedStrings { + if !strings.Contains(got, expected) { + t.Errorf("UCI output missing expected string: %q\nFull output:\n%s", expected, got) + } + } +} + +// TestUCI_DisplayCommand verifies that the 'd' command renders the board. +func TestUCI_DisplayCommand(t *testing.T) { + input := "position startpos\nd\nquit\n" + var output bytes.Buffer + u := NewUCI(strings.NewReader(input), &output) + u.Start() + + got := output.String() + + // Check for board frame components (rank labels) + if !strings.Contains(got, "8 |") || !strings.Contains(got, "1 |") { + t.Error("Display command 'd' did not output a board frame") + } + + // Check for initial pieces + if !strings.Contains(got, "r | n | b | q | k | b | n | r") { + t.Error("Initial pieces not found in board display") + } +} + +// TestUCI_PositionParsing verifies that FEN loading works. +func TestUCI_PositionParsing(t *testing.T) { + // FEN for 1. e4 + fen := "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1" + input := "position fen " + fen + "\nd\nquit\n" + var output bytes.Buffer + u := NewUCI(strings.NewReader(input), &output) + u.Start() + + got := output.String() + + // The pawn should be on rank 4 + if !strings.Contains(got, "4 |") || !strings.Contains(got, "P") { + t.Errorf("Pawn not found in expected rank after FEN load. Got:\n%s", got) + } +} + +func TestUCI_SetOption(t *testing.T) { + u := NewUCI(strings.NewReader(""), &bytes.Buffer{}) + + u.handleSetOption([]string{"setoption", "name", "Threads", "value", "4"}) + if u.threads != 4 { + t.Fatalf("expected Threads to be 4, got %d", u.threads) + } + + u.handleSetOption([]string{"setoption", "name", "MultiPV", "value", "3"}) + if u.multiPV != 3 { + t.Fatalf("expected MultiPV to be 3, got %d", u.multiPV) + } + + oldTT := search.GlobalTT + u.handleSetOption([]string{"setoption", "name", "Hash", "value", "128"}) + if search.GlobalTT == oldTT { + t.Fatal("expected Hash setoption to replace the transposition table") + } + + u.handleSetOption([]string{"setoption", "name", "Move", "Overhead", "value", "50"}) + if u.moveOverhead != 50 { + t.Fatalf("expected Move Overhead to be 50, got %d", u.moveOverhead) + } +} + +func TestUCI_UCINewGame(t *testing.T) { + input := "ucinewgame\nquit\n" + var output bytes.Buffer + u := NewUCI(strings.NewReader(input), &output) + u.Start() +} + +func TestUCI_ParseMove(t *testing.T) { + input := "position startpos moves e2e4 e7e5\nd\nquit\n" + var output bytes.Buffer + u := NewUCI(strings.NewReader(input), &output) + u.Start() + + got := output.String() + + // Verify white and black pawns moved + if !strings.Contains(got, "4 |") || !strings.Contains(got, "P") { + t.Error("White pawn not found on rank 4 after 'moves e2e4'") + } + if !strings.Contains(got, "5 |") || !strings.Contains(got, "p") { + t.Error("Black pawn not found on rank 5 after 'moves e7e5'") + } +} + +func TestUCI_PonderLogic(t *testing.T) { + input := "uci\nisready\nposition startpos\ngo ponder wtime 1000 btime 1000\nponderhit\nstop\nquit\n" + var output bytes.Buffer + u := NewUCI(strings.NewReader(input), &output) + + done := make(chan bool) + go func() { + u.Start() + done <- true + }() + + select { + case <-done: + // Success + case <-time.After(5 * time.Second): + t.Fatal("UCI loop timed out during ponder test") + } +} diff --git a/main.go b/main.go index 0715d67..7c6788d 100644 --- a/main.go +++ b/main.go @@ -4,7 +4,7 @@ import ( "os" "strings" - "github.com/Skiddle-Labs/axon-engine/internal/protocol" + "github.com/Skiddle-Labs/axon-engine/internal/protocol/uci" ) func main() { @@ -13,12 +13,12 @@ func main() { if len(os.Args) > 1 { command := strings.Join(os.Args[1:], " ") input := strings.NewReader(command + "\nquit\n") - p := protocol.NewProtocol(input, os.Stdout) + p := uci.NewUCI(input, os.Stdout) p.Start() return } // Default mode: start the UCI protocol loop reading from standard input. - p := protocol.NewProtocol(os.Stdin, os.Stdout) + p := uci.NewUCI(os.Stdin, os.Stdout) p.Start() } -- knotmirror 0.0.1