GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore/chess

Rules and 1 more file

A Python command-line tool in the chess folder of Cosmic that starts piece (`start_piece_ids`), sets fen (`set_fen`) and parses uci (`parse_uci`).

700 lines of Python from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1087 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Players transform · cosmic / tools/explore/chess/players.py lines 1–245
  2. Rules ingest · cosmic / tools/explore/chess/rules.py lines 1–455

Players

A Python module in the chess folder of Cosmic. It is built from the player class (`Player`), the info step (`info`) and the enc step (`enc`).

transformcosmic / tools/explore/chess/players.py · lines 1–245 of 245 · Entry point · pattern terminal (shared by 2 files)

What it does
It calculates its inputs. Defines 16 functions or classes, including w, Player, __init__, info, enc. Uses libraries random, numpy.
Downstream impact
Used directly by 2 files: Tournament (cosmic); CI Chess Gate (cosmic). Reached from 5 other entry points, including Extras (cosmic); Ship (cosmic); Test Extras (cosmic).
What it achieves
Ten deterministic computer players for code chess (5 white, 5 black), scored by the furnace.
Why it matters
Imported by Tournament and CI Chess Gate.
Application
cosmic · tools/explore/chess · Python module
Uses
Furnace (import), Rules (import), random, numpy
Used by
imported by Tournament (import), imported by CI Chess Gate (sys.path import)
Produces
w, Player, roster, note
Defines here
w, Player, __init__, info, enc, scores, terminal, choose, _d1, _d2, _d3, _min_node, _max_leaf, roster, _pct, note
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/chess/players.py:1-245 · blob 6e4b7336f810a05c22d03eea17fc0031c6ae1d39 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Ten deterministic computer players for code chess (5 white, 5 black), scored by the furnace.

Rules interface the players rely on (documented so any rules engine can stand in; rules.py's
`Board(track_ids=True)` is the one used):
  bd.side                      +1 white / -1 black to move
  bd.b, rules.SQUARES          piece codes (pawn 1 .. king 6, white +), read through SQUARES a1..h8
  bd.ids                       board.json piece id per square (None if empty)
  bd.legal_moves()             legal moves (opaque tuples), bd.pseudo_moves() pseudo-legal ones
  bd.push(m) / bd.pop()        play / take back a legal move (records repetition keys)
  bd._make(m) / bd._unmake()   fast play / take back without repetition bookkeeping (search only)
  bd.in_check(), bd.outcome()  check; None or (result, reason) for mate/stalemate/draw rules
A move a player returns is always one of bd.legal_moves(); only search-internal plies use
pseudo-legal moves, where a king left en prise is caught by the furnace's 'king' feature (a captured
king scores -1000), so illegal internal lines are never preferred.

Every player is a weight vector over furnace.FEATURES plus a search shape:
  depth 1  every legal move's resulting position is scored in ONE furnace call
  depth 2  every (move, reply) position for all moves is scored in ONE furnace call; minimax
  depth 3  alpha-beta: replies ordered by a furnace call, each reply's leaves scored in one call
Terminal positions (mate, stalemate, repetition, fifty moves) come from rules.outcome(), not the furnace.
Determinism: the only randomness is random.Random(seed) for exact ties and, in a player's first two
moves, a choice among moves within OPENING_SPREAD of the best, so a seed fixes the whole game.
"""
import random

import numpy as np

import furnace as fz
import rules

MATE = 10000.0
KING_W = 1000.0
OPENING_SPREAD = 0.15


def w(**kw):
    v = np.zeros(fz.K)
    v[fz.F_IDX['king']] = KING_W
    for k, x in kw.items():
        v[fz.F_IDX[k]] = x
    return v


# id, side, name, strategy, weights, depth, extra
ROSTER = [
    ('w1', 'white', 'Line Counter', 'Counts material only and grabs the biggest capture one move ahead.',
     w(material=1), 1, {}),
    ('w2', 'white', 'Hub Finder', 'Positional: develops minor pieces and occupies the centre, one move ahead.',
     w(material=1, centre=0.3, develop=0.3), 1, {}),
    ('w3', 'white', 'Furnace', 'Alpha-beta to depth 3 on the batched furnace evaluator (material, centre, safety).',
     w(material=1, centre=0.1, advance=0.05, tropism=0.03, shelter=0.1, develop=0.15), 3, {}),
    ('w4', 'white', 'Reach Map', 'Values each piece by its community\'s reach, uniqueness and centrality; 2-ply minimax.',
     w(reach=1, centre=0.05), 2, {}),
    ('w5', 'white', 'Test Guard', 'Cautious defender: keeps a pawn shield round its king and never trades down; 2-ply.',
     w(material=1.2, shelter=0.5, develop=0.1), 2, {}),
    ('b1', 'black', 'Merge Conflict', 'Aggressive attacker: swarms officers towards the enemy king; 2-ply.',
     w(material=1, tropism=0.2, advance=0.05), 2, {}),
    ('b2', 'black', 'Deep Diff', 'Alpha-beta to depth 3 on the furnace, preferring space and pawn advances.',
     w(material=1, advance=0.15, centre=0.15, shelter=0.05), 3, {}),
    ('b3', 'black', 'Orphan Reach', 'Values pieces whose communities are least reached and least central most; 2-ply.',
     w(orphan=1, centre=0.05), 2, {}),
    ('b4', 'black', 'Linter', 'Restricts: picks the move that leaves the opponent fewest legal replies, material first.',
     w(material=1, centre=0.05), 1, {'mobility': 0.05}),
    ('b5', 'black', 'Pawn Pipeline', 'Pushes pawns down the pipeline towards promotion, material aware; 2-ply.',
     w(material=1, advance=0.4), 2, {}),
]


class Player:
    def __init__(self, pid, side, name, strategy, weights, depth, extra, furnace):
        self.id, self.side, self.name, self.strategy = pid, side, name, strategy
        self.w, self.depth, self.extra, self.fz = weights, depth, extra, furnace
        self.idx = dict(furnace.index)
        self.idx[None] = fz.EMPTY_ID
        self.nodes = 0

    def info(self):
        return {'id': self.id, 'side': self.side, 'name': self.name, 'strategy': self.strategy}

    # ---------------------------------------------------------------- encoding + scoring
    def enc(self, bd):
        b, ids, idx = bd.b, bd.ids, self.idx
        return [b[s] for s in rules.SQUARES], [idx[ids[s]] for s in rules.SQUARES]

    def scores(self, rows, persp):
        """Furnace scores of encoded positions, from side `persp`'s point of view."""
        if not rows:
            return np.zeros(0)
        self.nodes += len(rows)
        c, d = self.fz.encode([r[0] for r in rows], [r[1] for r in rows])
        # rounded so exact ties (and so seeded tie-breaks) do not depend on float summation order
        return np.round(self.fz.to_host(self.fz.score(c, d, self.w)) * persp, 9)

    @staticmethod
    def terminal(bd, persp):
        out = bd.outcome()
        if out is None:
            return None
        res = out[0]
        if res == '1/2-1/2':
            return 0.0
        return MATE if (res == '1-0') == (persp == 1) else -MATE

    # ---------------------------------------------------------------- move choice
    def choose(self, bd, rng, own_moves_played):
        me = bd.side
        legal = bd.legal_moves()
        vals = getattr(self, '_d%d' % self.depth)(bd, legal, me)
        best = max(vals)
        spread = OPENING_SPREAD if own_moves_played < 2 else 1e-9
        cands = [m for m, v in zip(legal, vals) if v >= best - spread]
        return rng.choice(cands) if len(cands) > 1 else cands[0]

    def _d1(self, bd, legal, me):
        rows, fixed, mob = [], {}, {}
        for i, m in enumerate(legal):
            bd.push(m)
            t = self.terminal(bd, me)
            if t is not None:
                fixed[i] = t
            elif 'mobility' in self.extra:
                mob[i] = len(bd.legal_moves())
            rows.append(self.enc(bd))
            bd.pop()
        s = self.scores(rows, me)
        out = []
        for i in range(len(legal)):
            v = fixed[i] if i in fixed else float(s[i]) - self.extra.get('mobility', 0) * mob.get(i, 0)
            out.append(v)
        return out

    def _d2(self, bd, legal, me):
        rows, owner, fixed = [], [], {}
        for i, m in enumerate(legal):
            bd.push(m)
            t = self.terminal(bd, me)
            if t is not None:
                fixed[i] = t
            else:
                for r in bd.pseudo_moves():
                    bd._make(r)
                    rows.append(self.enc(bd))
                    owner.append(i)
                    bd._unmake()
            bd.pop()
        s = self.scores(rows, me)
        best = [np.inf] * len(legal)
        for o, v in zip(owner, s):
            if v < best[o]:
                best[o] = float(v)
        return [fixed.get(i, best[i]) for i in range(len(legal))]

    def _d3(self, bd, legal, me):
        # order root moves by a one-call depth-1 furnace pass
        rows, fixed = [], {}
        for i, m in enumerate(legal):
            bd.push(m)
            t = self.terminal(bd, me)
            if t is not None:
                fixed[i] = t
            rows.append(self.enc(bd))
            bd.pop()
        s1 = self.scores(rows, me)
        order = sorted(range(len(legal)), key=lambda i: -(fixed.get(i, s1[i])))
        vals = [None] * len(legal)
        alpha = -np.inf
        for i in order:
            if i in fixed:
                vals[i] = fixed[i]
            else:
                bd.push(legal[i])
                vals[i] = self._min_node(bd, me, alpha - OPENING_SPREAD)
                bd.pop()
            alpha = max(alpha, vals[i])
        return vals

    def _min_node(self, bd, me, alpha):
        """Opponent to move (pseudo-legal replies); returns a fail-soft upper bound <= true value."""
        replies = bd.pseudo_moves()
        rows = []
        for r in replies:
            bd._make(r)
            rows.append(self.enc(bd))
            bd._unmake()
        s = self.scores(rows, me)
        v = np.inf
        for j in np.argsort(s, kind='stable'):
            bd._make(replies[j])
            leaf = self._max_leaf(bd, me)
            bd._unmake()
            v = min(v, leaf)
            if v <= alpha:
                break
        return float(v)

    def _max_leaf(self, bd, me):
        rows = []
        for m in bd.pseudo_moves():
            bd._make(m)
            rows.append(self.enc(bd))
            bd._unmake()
        if not rows:
            return float(self.scores([self.enc(bd)], me)[0])
        return float(self.scores(rows, me).max())


def roster(pieces, xp=np):
    furnace = fz.Furnace(pieces, xp=xp)
    return [Player(*r, furnace=furnace) for r in ROSTER]


# ---------------------------------------------------------------- notes from board.json facts
CENTRE = {'d4', 'e4', 'd5', 'e5'}


def _pct(x):
    return '%d%%' % round(100 * float(x))


def note(rec, by_id, mate=False):
    """One line tying a move to the communities involved, using only board.json fields."""
    p = by_id.get(rec['piece'], {})
    lab = '"%s" (%s, %d files)' % (p.get('label', rec['piece']), p.get('role', '?'), p.get('size', 0))
    kind = p.get('type', 'piece')
    if rec.get('castle'):
        rook_sq = {'g1': 'f1', 'c1': 'd1', 'g8': 'f8', 'c8': 'd8'}[rec['to']]
        s = 'king %s castles, bringing its rook to %s' % (lab, rook_sq)
    elif rec['capture']:
        c = by_id.get(rec['capture'], {})
        s = '%s %s takes the %s "%s" (%s, %d files, %s duplicate candidates, reach %s)' % (
            kind, lab, c.get('type', 'piece'), c.get('label', rec['capture']), c.get('role', '?'),
            c.get('size', 0), _pct(1 - float(c.get('unique', 1))), _pct(c.get('reach', 0)))
    else:
        s = '%s %s moves %s-%s' % (kind, lab, rec['from'], rec['to'])
        if rec['to'] in CENTRE:
            s += ' into the centre'
    if rec.get('promotion'):
        s += '; promotes to a %s, so a %d-line community now carries %s weight' % (
            rec['promotion'], p.get('lines', 0), rec['promotion'])
    if rec['check']:
        k = by_id.get(('b' if rec['piece'].startswith('w') else 'w') + '-k', {})
        s += '; %s the king "%s" (centrality %.2f)' % ('checkmates' if mate else 'checks',
                                                       k.get('label', 'king'), float(k.get('centrality', 0)))
    return s

Rules

A Python command-line tool in the chess folder of Cosmic that starts piece (`start_piece_ids`), sets fen (`set_fen`) and parses uci (`parse_uci`).

ingestcosmic / tools/explore/chess/rules.py · lines 1–455 of 557 · Entry point · pattern outcome (shared by 2 files)

What it does
Defines 36 functions or classes, including sq_name, sq_parse, square_colour, start_piece_ids, Board. Uses libraries sys, time.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 7 files: Board (cosmic); Furnace (cosmic); Players (cosmic); Test Board (cosmic); and 3 more. Reached from 7 other entry points, including Extras (cosmic); Page (cosmic); Ship (cosmic).
What it achieves
It is built from the sq name helper (`sq_name`), the sq parse helper (`sq_parse`) and the square colour helper (`square_colour`). Chess rules engine in pure Python (no dependencies): chess-rules-v1.
Why it matters
Imported by 5 files, including Board, Furnace and Players. Checked by 2 tests, including Test Board.
Application
cosmic · tools/explore/chess · Python CLI
Uses
sys, time
Used by
imported by Board (import), imported by Furnace (import), imported by Players (import), imported by Test Board (import), imported by Test Rules (import), imported by Tournament (import), imported by CI Chess Gate (sys.path import)
Produces
sq_name, sq_parse, square_colour, start_piece_ids, Board
Defines here
sq_name, sq_parse, square_colour, start_piece_ids, Board, __init__, set_fen, fen, copy, attacked, in_check, pseudo_moves, pinned, legal_moves, _make, _unmake, _ep_legal, _record_key, push, pop, push_uci, parse_uci, uci, is_capture, piece_at, id_at, san
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/chess/rules.py:1-455 · blob ac7f35044a66bdd39de3a575ea440c404d8d9f60 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Chess rules engine in pure Python (no dependencies): chess-rules-v1.

Board: 0x88 mailbox (128 cells, square = rank * 16 + file, a1 = 0, h8 = 119); off-board test is
`sq & 0x88`. Pieces are small ints: pawn 1, knight 2, bishop 3, rook 4, queen 5, king 6; white
positive, black negative, empty 0.

Rules implemented (FIDE Laws of Chess): all piece moves, castling (rights, empty path, king not in,
through or into check), en passant (only on the ply right after the double push), promotion to
Q/R/B/N, check, checkmate, stalemate, threefold repetition (same placement, side to move, castling
rights and en passant possibility, which counts only if an en passant capture is actually legal),
fifty-move rule (100 plies without a pawn move or capture), and dead positions by insufficient
material (K v K, K+minor v K, K+B v K+B with bishops on one colour). FEN in and out, SAN and UCI out.

Move = tuple (from_sq, to_sq, promo, flag); promo is a positive piece code or 0; flag is NORMAL,
DOUBLE (pawn two-step), EP (en passant) or CASTLE. Legal generation: pseudo-legal moves; a move that
could expose the king (side in check, king move, en passant, pinned piece) is made and unmade and kept
only if the king is then safe; all others are legal outright. legal_moves() is cached per position
between push/pop. Speed (CPython 3.13): perft(4) from the start in about 0.5 s; random playouts with
outcome() checks at about 5,000 plies per second (roughly 0.05 s per game).

Optional piece identity tracking (`Board(track_ids=True)` from the standard start) follows every
piece from its starting square, with ids shared with board.json: side letter + piece letter
(+ starting file for rooks, bishops, knights and pawns), e.g. "w-k", "b-q", "w-r-a", "w-p-e".
A promoted pawn keeps its id. `move_record(m)` returns the games.json move fields for a move.

Validated by perft (see test_rules.py): start position 20 / 400 / 8902 / 197281 (depth 1-4),
Kiwipete 48 / 2039 / 97862 (depth 1-3), plus the standard positions 3-5 of the perft suite.
"""
RULES_VERSION = 'chess-rules-v1'

PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING = 1, 2, 3, 4, 5, 6
WHITE, BLACK = 1, -1
NORMAL, DOUBLE, EP, CASTLE = 0, 1, 2, 3
PIECE_NAMES = {1: 'pawn', 2: 'knight', 3: 'bishop', 4: 'rook', 5: 'queen', 6: 'king'}
PIECE_LETTERS = {1: 'p', 2: 'n', 3: 'b', 4: 'r', 5: 'q', 6: 'k'}
LETTER_PIECE = {v: k for k, v in PIECE_LETTERS.items()}
START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'

SQUARES = tuple(r * 16 + f for r in range(8) for f in range(8))
KNIGHT_D = (33, 31, 18, 14, -33, -31, -18, -14)
KING_D = (1, -1, 16, -16, 15, 17, -15, -17)
BISHOP_D = (15, 17, -15, -17)
ROOK_D = (1, -1, 16, -16)
SLIDES = {BISHOP: BISHOP_D, ROOK: ROOK_D, QUEEN: KING_D}
# castling rights bits and the mask applied when a move touches a square
WK, WQ, BK, BQ = 1, 2, 4, 8
CR_MASK = [15] * 128
CR_MASK[4], CR_MASK[7], CR_MASK[0] = 15 & ~(WK | WQ), 15 & ~WK, 15 & ~WQ
CR_MASK[116], CR_MASK[119], CR_MASK[112] = 15 & ~(BK | BQ), 15 & ~BK, 15 & ~BQ


def sq_name(sq):
    return 'abcdefgh'[sq & 7] + str((sq >> 4) + 1)


def sq_parse(name):
    f, r = 'abcdefgh'.index(name[0]), int(name[1]) - 1
    if not 0 <= r < 8:
        raise ValueError('bad square %r' % name)
    return r * 16 + f


def square_colour(sq):
    """0 dark, 1 light (a1 is dark)."""
    return ((sq >> 4) + (sq & 7)) & 1


def start_piece_ids():
    """{square name: piece id} for the standard start; shared with board.json."""
    ids = {}
    back = 'rnbqkbnr'
    for side, rank, prank in (('w', 1, 2), ('b', 8, 7)):
        for i, f in enumerate('abcdefgh'):
            letter = back[i]
            ids[f + str(rank)] = '%s-%s' % (side, letter) if letter in 'kq' else '%s-%s-%s' % (side, letter, f)
            ids[f + str(prank)] = '%s-p-%s' % (side, f)
    return ids


class Board:
    __slots__ = ('b', 'side', 'castling', 'ep', 'halfmove', 'fullmove', 'kings', 'stack', 'keys', 'rep', 'ids', '_cache')

    def __init__(self, fen=START_FEN, track_ids=False):
        self.set_fen(fen)
        if track_ids:
            if fen.split()[0] != START_FEN.split()[0]:
                raise ValueError('piece ids are defined only from the standard start position')
            self.ids = [None] * 128
            for name, pid in start_piece_ids().items():
                self.ids[sq_parse(name)] = pid

    # ---------------------------------------------------------------- FEN
    def set_fen(self, fen):
        parts = fen.split()
        if len(parts) == 4:
            parts += ['0', '1']
        if len(parts) != 6:
            raise ValueError('FEN needs 6 fields: %r' % fen)
        place, side, cas, ep, half, full = parts
        rows = place.split('/')
        if len(rows) != 8:
            raise ValueError('FEN placement needs 8 ranks')
        b = [0] * 128
        kings = [None, None, None]
        for i, row in enumerate(rows):
            r, f = 7 - i, 0
            for ch in row:
                if ch.isdigit():
                    f += int(ch)
                else:
                    if ch.lower() not in LETTER_PIECE or f > 7:
                        raise ValueError('bad FEN rank %r' % row)
                    p = LETTER_PIECE[ch.lower()] * (WHITE if ch.isupper() else BLACK)
                    b[r * 16 + f] = p
                    if abs(p) == KING:
                        kings[(p > 0) * 2] = r * 16 + f
                    f += 1
            if f != 8:
                raise ValueError('bad FEN rank %r' % row)
        if kings[0] is None or kings[2] is None:
            raise ValueError('FEN needs one king per side')
        if side not in ('w', 'b'):
            raise ValueError('bad side to move %r' % side)
        self.b, self.kings = b, kings
        self.side = WHITE if side == 'w' else BLACK
        self.castling = 0 if cas == '-' else sum({'K': WK, 'Q': WQ, 'k': BK, 'q': BQ}[c] for c in cas)
        self.ep = -1 if ep == '-' else sq_parse(ep)
        self.halfmove, self.fullmove = int(half), int(full)
        self.ids = None  # identities are defined only from the standard start (see __init__)
        self.stack = []
        self.keys = []
        self.rep = {}
        self._cache = None
        self._record_key()

    def fen(self):
        rows = []
        for r in range(7, -1, -1):
            row, empty = '', 0
            for f in range(8):
                p = self.b[r * 16 + f]
                if not p:
                    empty += 1
                    continue
                if empty:
                    row, empty = row + str(empty), 0
                ch = PIECE_LETTERS[abs(p)]
                row += ch.upper() if p > 0 else ch
            rows.append(row + (str(empty) if empty else ''))
        cas = ''.join(c for c, bit in (('K', WK), ('Q', WQ), ('k', BK), ('q', BQ)) if self.castling & bit) or '-'
        ep = sq_name(self.ep) if self.ep >= 0 else '-'
        return '%s %s %s %s %d %d' % ('/'.join(rows), 'w' if self.side == WHITE else 'b', cas, ep,
                                      self.halfmove, self.fullmove)

    def copy(self):
        c = Board.__new__(Board)
        c.b, c.side, c.castling, c.ep = self.b[:], self.side, self.castling, self.ep
        c.halfmove, c.fullmove, c.kings = self.halfmove, self.fullmove, self.kings[:]
        c.stack, c.keys, c.rep = self.stack[:], self.keys[:], dict(self.rep)
        c.ids = self.ids[:] if self.ids is not None else None
        c._cache = self._cache
        return c

    # ---------------------------------------------------------------- attacks
    def attacked(self, sq, by):
        """True if side `by` attacks square sq."""
        b = self.b
        if by == WHITE:
            for s in (sq - 15, sq - 17):
                if not s & 0x88 and b[s] == PAWN:
                    return True
        else:
            for s in (sq + 15, sq + 17):
                if not s & 0x88 and b[s] == -PAWN:
                    return True
        kn, kg = KNIGHT * by, KING * by
        for d in KNIGHT_D:
            s = sq + d
            if not s & 0x88 and b[s] == kn:
                return True
        for d in KING_D:
            s = sq + d
            if not s & 0x88 and b[s] == kg:
                return True
        bi, ro, qu = BISHOP * by, ROOK * by, QUEEN * by
        for d in BISHOP_D:
            s = sq + d
            while not s & 0x88:
                p = b[s]
                if p:
                    if p == bi or p == qu:
                        return True
                    break
                s += d
        for d in ROOK_D:
            s = sq + d
            while not s & 0x88:
                p = b[s]
                if p:
                    if p == ro or p == qu:
                        return True
                    break
                s += d
        return False

    def in_check(self, side=None):
        side = self.side if side is None else side
        return self.attacked(self.kings[side + 1], -side)

    # ---------------------------------------------------------------- generation
    def pseudo_moves(self):
        b, side = self.b, self.side
        out = []
        add = out.append
        fwd = 16 * side
        start_rank, promo_rank = (1, 7) if side == WHITE else (6, 0)
        for frm in SQUARES:
            p = b[frm]
            if not p or (p > 0) != (side > 0):
                continue
            t = p * side
            if t == PAWN:
                to = frm + fwd
                if not to & 0x88 and not b[to]:
                    if to >> 4 == promo_rank:
                        for pr in (QUEEN, ROOK, BISHOP, KNIGHT):
                            add((frm, to, pr, NORMAL))
                    else:
                        add((frm, to, 0, NORMAL))
                        if frm >> 4 == start_rank and not b[to + fwd]:
                            add((frm, to + fwd, 0, DOUBLE))
                for to in (frm + fwd - 1, frm + fwd + 1):
                    if to & 0x88:
                        continue
                    q = b[to]
                    if q and (q > 0) != (side > 0):
                        if to >> 4 == promo_rank:
                            for pr in (QUEEN, ROOK, BISHOP, KNIGHT):
                                add((frm, to, pr, NORMAL))
                        else:
                            add((frm, to, 0, NORMAL))
                    elif to == self.ep:
                        add((frm, to, 0, EP))
            elif t == KNIGHT or t == KING:
                for d in (KNIGHT_D if t == KNIGHT else KING_D):
                    to = frm + d
                    if to & 0x88:
                        continue
                    q = b[to]
                    if not q or (q > 0) != (side > 0):
                        add((frm, to, 0, NORMAL))
            else:
                for d in SLIDES[t]:
                    to = frm + d
                    while not to & 0x88:
                        q = b[to]
                        if not q:
                            add((frm, to, 0, NORMAL))
                        else:
                            if (q > 0) != (side > 0):
                                add((frm, to, 0, NORMAL))
                            break
                        to += d
        # castling
        cr = self.castling
        if side == WHITE and cr & (WK | WQ):
            if cr & WK and b[4] == KING and b[7] == ROOK and not b[5] and not b[6] and \
                    not self.attacked(4, BLACK) and not self.attacked(5, BLACK) and not self.attacked(6, BLACK):
                add((4, 6, 0, CASTLE))
            if cr & WQ and b[4] == KING and b[0] == ROOK and not b[1] and not b[2] and not b[3] and \
                    not self.attacked(4, BLACK) and not self.attacked(3, BLACK) and not self.attacked(2, BLACK):
                add((4, 2, 0, CASTLE))
        elif side == BLACK and cr & (BK | BQ):
            if cr & BK and b[116] == -KING and b[119] == -ROOK and not b[117] and not b[118] and \
                    not self.attacked(116, WHITE) and not self.attacked(117, WHITE) and not self.attacked(118, WHITE):
                add((116, 118, 0, CASTLE))
            if cr & BQ and b[116] == -KING and b[112] == -ROOK and not b[113] and not b[114] and not b[115] and \
                    not self.attacked(116, WHITE) and not self.attacked(115, WHITE) and not self.attacked(114, WHITE):
                add((116, 114, 0, CASTLE))
        return out

    def pinned(self, side=None):
        """Squares of `side`'s pieces that stand alone between their king and an enemy slider."""
        side = self.side if side is None else side
        b, ksq = self.b, self.kings[side + 1]
        out = set()
        for d in KING_D:
            diag = d in BISHOP_D
            s, own = ksq + d, -1
            while not s & 0x88:
                p = b[s]
                if p:
                    if (p > 0) == (side > 0):
                        if own >= 0:
                            break
                        own = s
                    else:
                        t = -p * side
                        if own >= 0 and (t == QUEEN or t == (BISHOP if diag else ROOK)):
                            out.add(own)
                        break
                s += d
        return out

    def legal_moves(self):
        """Legal moves (a fresh list). Cached per position between push/pop calls. A move is tested by
        make/unmake only when it could expose the king: in check, king moves, en passant, pinned pieces."""
        stable = len(self.stack) == len(self.keys) - 1
        if stable and self._cache is not None:
            return list(self._cache)
        side = self.side
        ksq = self.kings[side + 1]
        check = self.attacked(ksq, -side)
        pins = () if check else self.pinned(side)
        out = []
        for m in self.pseudo_moves():
            if check or m[0] == ksq or m[3] == EP or m[0] in pins:
                self._make(m)
                if not self.attacked(self.kings[side + 1], -side):
                    out.append(m)
                self._unmake()
            else:
                out.append(m)
        if stable:
            self._cache = out
            return list(out)
        return out

    # ---------------------------------------------------------------- make / unmake
    def _make(self, m):
        frm, to, promo, flag = m
        b, side = self.b, self.side
        p = b[frm]
        cap_sq = to - 16 * side if flag == EP else to
        cap = b[cap_sq]
        ids = self.ids
        cap_id = None
        if ids is not None:
            cap_id = ids[cap_sq]
        self.stack.append((m, cap, self.castling, self.ep, self.halfmove, cap_id))
        if flag == EP:
            b[cap_sq] = 0
        b[to] = promo * side if promo else p
        b[frm] = 0
        if ids is not None:
            if flag == EP:
                ids[cap_sq] = None
            ids[to], ids[frm] = ids[frm], None
        if flag == CASTLE:
            rf, rt = (frm + 3, frm + 1) if to > frm else (frm - 4, frm - 1)
            b[rt], b[rf] = b[rf], 0
            if ids is not None:
                ids[rt], ids[rf] = ids[rf], None
        if p == KING * side:
            self.kings[side + 1] = to
        self.castling &= CR_MASK[frm] & CR_MASK[to]
        self.ep = (frm + to) >> 1 if flag == DOUBLE else -1
        self.halfmove = 0 if (p == PAWN * side or cap) else self.halfmove + 1
        if side == BLACK:
            self.fullmove += 1
        self.side = -side

    def _unmake(self):
        m, cap, self.castling, self.ep, self.halfmove, cap_id = self.stack.pop()
        frm, to, promo, flag = m
        side = self.side = -self.side
        b, ids = self.b, self.ids
        p = PAWN * side if promo else b[to]
        b[frm] = p
        if ids is not None:
            ids[frm] = ids[to]
        if flag == EP:
            b[to] = 0
            b[to - 16 * side] = cap
            if ids is not None:
                ids[to], ids[to - 16 * side] = None, cap_id
        else:
            b[to] = cap
            if ids is not None:
                ids[to] = cap_id
        if flag == CASTLE:
            rf, rt = (frm + 3, frm + 1) if to > frm else (frm - 4, frm - 1)
            b[rf], b[rt] = b[rt], 0
            if ids is not None:
                ids[rf], ids[rt] = ids[rt], None
        if p == KING * side:
            self.kings[side + 1] = frm
        if side == BLACK:
            self.fullmove -= 1

    # ---------------------------------------------------------------- public play
    def _ep_legal(self):
        if self.ep < 0:
            return False
        return any(m[3] == EP for m in self.legal_moves())

    def _record_key(self):
        self._cache = None
        self.keys.append(None)  # placeholder: the position is now stable, so legal_moves() caches
        k = (tuple(self.b), self.side, self.castling, self.ep if self._ep_legal() else -1)
        self.keys[-1] = k
        self.rep[k] = self.rep.get(k, 0) + 1

    def push(self, m):
        """Play a move (assumed legal: pass one from legal_moves())."""
        self._make(m)
        self._record_key()

    def pop(self):
        k = self.keys.pop()
        self.rep[k] -= 1
        self._cache = None
        self._unmake()

    def push_uci(self, uci):
        m = self.parse_uci(uci)
        self.push(m)
        return m

    def parse_uci(self, uci):
        frm, to = sq_parse(uci[:2]), sq_parse(uci[2:4])
        promo = LETTER_PIECE[uci[4]] if len(uci) > 4 else 0
        for m in self.legal_moves():
            if m[0] == frm and m[1] == to and m[2] == promo:
                return m
        raise ValueError('illegal move %s in %s' % (uci, self.fen()))

    @staticmethod
    def uci(m):
        return sq_name(m[0]) + sq_name(m[1]) + (PIECE_LETTERS[m[2]] if m[2] else '')

    def is_capture(self, m):
        return m[3] == EP or bool(self.b[m[1]])

    def piece_at(self, square):
        """(side, type name) or None, square as name ('e4') or 0x88 index."""
        sq = sq_parse(square) if isinstance(square, str) else square
        p = self.b[sq]
        return None if not p else ('white' if p > 0 else 'black', PIECE_NAMES[abs(p)])

    def id_at(self, square):
        sq = sq_parse(square) if isinstance(square, str) else square
        return self.ids[sq] if self.ids is not None else None

    def san(self, m, legal=None):
        frm, to, promo, flag = m
        b = self.b
        if flag == CASTLE:
            s = 'O-O' if to > frm else 'O-O-O'
        else:
            t = abs(b[frm])
            cap = self.is_capture(m)
            if t == PAWN:
                s = ('abcdefgh'[frm & 7] + 'x' if cap else '') + sq_name(to)