GLOBALGRID2050 / EXPLORE CODE

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

CI Chess Gate and 1 more file

A Python command-line tool in the explore folder of Cosmic that reads build graph, using SHA-256. It checks perft (`check_perft`), checks board (`check_board`) and checks tournament (`check_tournament`).

539 lines of Python from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1090 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. Tournament storage · cosmic / tools/explore/chess/tournament.py lines 1–146
  2. CI Chess Gate automation · cosmic / tools/explore/ci/chess_gate.py lines 1–393

Tournament

A Python command-line tool in the chess folder of Cosmic that reads board and games.

storagecosmic / tools/explore/chess/tournament.py · lines 1–146 of 146 · Entry point · pattern table (shared by 65 files)

What it does
It loads board and games. Defines 6 functions or classes, including find_board, adjudicate, play, table, run. Uses libraries argparse, json, os, random, sys. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file board.json; JSON file games.json; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 3 files: Test No Tmp (cosmic); CI Chess Gate (cosmic); Extras (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
What it achieves
It finds board (`find_board`) and is built from the adjudicate step (`adjudicate`) and the play step (`play`). Code chess tournament: every white player against every black player, fixed seeds -> `games.json`. It accepts `--board`, `--out` and `--both-colours`.
Why it matters
Imported by CI Chess Gate. Run by Extras. Checked by Test No Tmp.
Application
cosmic · tools/explore/chess · Python CLI
Uses
Players (import), Rules (import), argparse, json, os, random, sys, time
Used by
run by Test No Tmp (script call), imported by CI Chess Gate (sys.path import), run by Extras (script call)
Produces
find_board, adjudicate, play, table, run, main
Defines here
find_board, adjudicate, play, table, run, main
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/tournament.py:1-146 · blob a2b7443dcd7ddebbf82a864e81687d7c0d34c3ce · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""Code chess tournament: every white player against every black player, fixed seeds -> games.json.

  python tournament.py --board board.json --out games.json [--both-colours] [--ply-cap 160]

Game k (white i, black j, 0-based) uses seed 1 + 5*i + j (with --both-colours the reversed games use
seed 101 + 5*i + j, the black-roster player taking white). A game ends by rules.outcome() (checkmate,
stalemate, insufficient material, threefold repetition, fifty-move rule) or at the ply cap, where it
is adjudicated on plain material (pawn 1, knight 3, bishop 3, rook 5, queen 9): a lead of
ADJUDICATE_MARGIN or more wins, anything less is a draw. Writes games.json per CONTRACT.md
(explore-chess-games-v1) plus a `meta` block (settings, runtime, furnace calls).
"""
import argparse
import json
import os
import random
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import players as pl  # noqa: E402
import rules  # noqa: E402

PLY_CAP = 160
ADJUDICATE_MARGIN = 3
PLAIN = (0, 1, 3, 3, 5, 9, 0)
BOARD_CANDIDATES = (os.environ.get('CHESS_BOARD', ''),
                    os.path.join(os.environ.get('EXTRA_OUT') or '.', 'board.json'), 'board.json')


def find_board():
    for p in BOARD_CANDIDATES:
        if p and os.path.exists(p):
            return p
    raise SystemExit('tournament.py: no board.json found (tried %s); run board.py first or pass --board'
                     % ', '.join(p for p in BOARD_CANDIDATES if p))


def adjudicate(bd):
    bal = sum((1 if p > 0 else -1) * PLAIN[abs(p)] for p in (bd.b[s] for s in rules.SQUARES) if p)
    if bal >= ADJUDICATE_MARGIN:
        return '1-0', 'ply cap: white ahead by %d on material' % bal
    if bal <= -ADJUDICATE_MARGIN:
        return '0-1', 'ply cap: black ahead by %d on material' % -bal
    return '1/2-1/2', 'ply cap: material within %d' % (ADJUDICATE_MARGIN - 1)


def play(white, black, seed, by_id, ply_cap=PLY_CAP):
    bd = rules.Board(track_ids=True)
    rng = random.Random(seed)
    moves, own = [], {1: 0, -1: 0}
    result = None
    while result is None:
        if len(moves) >= ply_cap:
            result = adjudicate(bd)
            break
        side = bd.side
        p = white if side == 1 else black
        m = p.choose(bd, rng, own[side])
        legal = bd.legal_moves()
        assert m in legal
        rec = bd.move_record(m, legal)
        own[side] += 1
        bd.push(m)
        result = bd.outcome()
        mate = bool(result and result[1] == 'checkmate')
        moves.append({'ply': len(moves) + 1, 'piece': rec['piece'], 'from': rec['from'], 'to': rec['to'],
                      'capture': rec['capture'], 'check': rec['check'], 'san': rec['san'],
                      'promotion': rec['promotion'], 'note': pl.note(rec, by_id, mate)})
    return {'white': white.id, 'black': black.id, 'seed': seed, 'result': result[0], 'reason': result[1],
            'plies': len(moves), 'moves': moves}


def table(games, roster):
    rows = {p.id: {'player': p.id, 'played': 0, 'won': 0, 'drawn': 0, 'lost': 0} for p in roster}
    for g in games:
        for pid, colour in ((g['white'], '1-0'), (g['black'], '0-1')):
            r = rows[pid]
            r['played'] += 1
            if g['result'] == '1/2-1/2':
                r['drawn'] += 1
            elif g['result'] == colour:
                r['won'] += 1
            else:
                r['lost'] += 1
    for r in rows.values():
        r['points'] = r['won'] + 0.5 * r['drawn']
    return [rows[p.id] for p in roster]


def run(board_path, both=False, ply_cap=PLY_CAP, only=None, log=None):
    board = json.load(open(board_path))
    pieces = board['pieces']
    by_id = {p['id']: p for p in pieces}
    roster = pl.roster(pieces)
    whites = [p for p in roster if p.side == 'white']
    blacks = [p for p in roster if p.side == 'black']
    pairs = [(wp, bp, 1 + 5 * i + j) for i, wp in enumerate(whites) for j, bp in enumerate(blacks)]
    if both:
        pairs += [(bp, wp, 101 + 5 * i + j) for i, wp in enumerate(whites) for j, bp in enumerate(blacks)]
    if only is not None:
        pairs = pairs[:only]
    t0 = time.perf_counter()
    games = []
    for wp, bp, seed in pairs:
        g0 = time.perf_counter()
        games.append(play(wp, bp, seed, by_id, ply_cap))
        if log:
            g = games[-1]
            print('%s v %s seed %d: %s (%s, %d plies) %.1fs' % (g['white'], g['black'], seed, g['result'],
                  g['reason'], g['plies'], time.perf_counter() - g0), file=log, flush=True)
    f = roster[0].fz
    return {'schema': 'explore-chess-games-v1',
            'players': [p.info() for p in roster],
            'games': games,
            'table': table(games, roster),
            'meta': {'board': os.path.abspath(board_path), 'board_cut': board.get('cut'),
                     'board_stub': bool(board.get('stub')), 'rules_version': rules.RULES_VERSION,
                     'ply_cap': ply_cap, 'adjudicate_margin': ADJUDICATE_MARGIN, 'both_colours': both,
                     'runtime_s': round(time.perf_counter() - t0, 1),
                     'furnace': {'backend': f.xp.__name__, 'calls': f.calls, 'positions': f.positions}}}


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('--board', default=None)
    ap.add_argument('--out', default=os.path.join(os.environ.get('EXTRA_OUT') or '.', 'games.json'))
    ap.add_argument('--both-colours', action='store_true')
    ap.add_argument('--ply-cap', type=int, default=PLY_CAP)
    ap.add_argument('--games', type=int, default=None, help='only the first N games (smoke runs)')
    a = ap.parse_args(argv)
    if a.board and not os.path.isfile(a.board):
        sys.exit('tournament.py: --board %r does not exist; run board.py first' % a.board)
    doc = run(a.board or find_board(), a.both_colours, a.ply_cap, a.games, log=sys.stderr)
    os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
    with open(a.out, 'w') as fh:
        json.dump(doc, fh, indent=1)
    names = {p['id']: p['name'] for p in doc['players']}
    for r in doc['table']:
        print('%-3s %-15s P%-3d W%-3d D%-3d L%-3d %.1f' % (r['player'], names[r['player']], r['played'], r['won'],
                                                           r['drawn'], r['lost'], r['points']))
    print('runtime %.1fs, furnace %s' % (doc['meta']['runtime_s'], doc['meta']['furnace']))


if __name__ == '__main__':
    main()

CI Chess Gate

A Python command-line tool in the explore folder of Cosmic that reads build graph, using SHA-256. It checks perft (`check_perft`), checks board (`check_board`) and checks tournament (`check_tournament`).

automationcosmic / tools/explore/ci/chess_gate.py · lines 1–393 of 393 · Entry point · pattern check_board (shared by 2 files)

What it does
It loads build graph. Defines 14 functions or classes, including load, timed, wrap, check_perft, canon. Uses libraries argparse, hashlib, html, json, os. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage field_execution (path word 'gate'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Inputs & outputs
In: JSON file build_graph.json; JSON file release.json; JSON file ci-chess.json; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 1 file: Test CI (cosmic).
What it achieves
Chess regression gate for CI: four quick checks on `tools/explore/chess`, plus a "new code enters the board" view. It accepts `--graph`, `--newcode` and `--out-dir`.
Why it matters
Checked by Test CI.
Application
cosmic · tools/explore/ci · Python CLI
Uses
Board (sys.path import), Page (sys.path import), Players (sys.path import), Rules (sys.path import), Tournament (sys.path import), argparse, hashlib, html, json, os, random, sys, time
Used by
imported by Test CI (import)
Produces
load, timed, check_perft, canon, check_board, replay, check_tournament, check_page, release_view, release_html, report, main
Defines here
load, timed, wrap, check_perft, canon, check_board, replay, check_tournament, run, check_page, release_view, release_html, report, main
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/ci/chess_gate.py:1-393 · blob d569dc824eef849ebd6205e24578122b813e7bcd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
#!/usr/bin/env python3
"""Chess regression gate for CI: four quick checks on tools/explore/chess, plus a "new code enters the board" view.

    python tools/explore/ci/chess_gate.py [--graph build_graph.json] [--newcode ci-newcode.json]
        [--out-dir DIR] [--games 5] [--ply-cap 60]

Checks (each PASS / FAIL / SKIP, written to DIR/ci-chess.md and DIR/ci-chess.json):
  perft        rules.Board().perft(1..3) == 20, 400, 8902 (move generator unchanged).
  board        board.build_board(graph, '') twice gives byte-identical JSON, 32 pieces, 16 a side, the ids and
               squares of rules.start_piece_ids(). SKIP without a build_graph.json.
  tournament   a seeded mini-tournament (white i v black i, seed 1 + 6*i as tournament.py numbers it, ply cap)
               is played twice and must be identical; every move is replayed on a fresh rules.Board and must be
               legal with the recorded piece id, capture, check and SAN; the result must match outcome() or the
               ply-cap adjudication. Uses the fixture board (page.fixture_board) when there is no graph.
  page         page.build_data + page.render produce a full page (doctype, page schema, every piece label, no
               {{...}} placeholder left); written to DIR/chess/index.html for the UI tests.

Release view (with --newcode, the JSON of newcode.py): each push is shown as one "move" on the board.
  - A changed file that is in the deployed graph reinforces the community it belongs to (computed communities,
    board.py rule 2): that piece, or reserve, is marked with the number of new/changed functions.
  - New files are grouped by folder; each folder is a new code community. board.py rule 4 scores a community
    size / largest size + centrality. A new community has no edges in the deployed graph, so its centrality is
    taken as 0 (a lower bound). If that score beats the weakest piece still on the board, the folder is shown as
    PROMOTED onto that piece's square (it would displace it at the next build); otherwise it joins the reserve.
  This is an illustration computed from the board's own rule, not a legal chess move, and the page says so.
Exit 1 if any check FAILs (the workflow runs it advisory with continue-on-error); 0 otherwise.
"""
import argparse
import hashlib
import html
import json
import os
import random
import sys
import time

HERE = os.path.dirname(os.path.abspath(__file__))
CHESS = os.path.join(HERE, '..', 'chess')
sys.path.insert(0, os.path.abspath(CHESS))
import board as board_mod  # noqa: E402
import page as page_mod  # noqa: E402
import players as pl  # noqa: E402
import rules  # noqa: E402
import tournament as tour  # noqa: E402

PERFT = {1: 20, 2: 400, 3: 8902}
GRAPH_CANDIDATES = [os.environ.get('EXPLORE_GRAPH', ''),
                    os.path.join(HERE, '..', '..', '..', '..', '_site', 'explore-code', 'build_graph.json'),
                    '/tmp/site8/explore-code/build_graph.json']


def load(path):
    with open(path, encoding='utf-8') as fh:
        return json.load(fh)


def timed(fn):
    def wrap(*a, **k):
        t0 = time.perf_counter()
        try:
            r = fn(*a, **k)
        except Exception as e:  # a crash is a FAIL with its message, never a traceback-only CI log
            r = {'status': 'FAIL', 'detail': '%s: %s' % (type(e).__name__, e)}
        r['name'] = fn.__name__.replace('check_', '')
        r['seconds'] = round(time.perf_counter() - t0, 2)
        return r
    return wrap


@timed
def check_perft():
    got = {d: rules.Board().perft(d) for d in PERFT}
    ok = got == PERFT
    return {'status': 'PASS' if ok else 'FAIL',
            'detail': 'perft 1..3 = %s (expected %s)' % (', '.join(str(got[d]) for d in PERFT),
                                                         ', '.join(str(PERFT[d]) for d in PERFT))}


def canon(obj):
    return json.dumps(obj, sort_keys=True, separators=(',', ':'), ensure_ascii=False)


@timed
def check_board(graph, keep):
    if graph is None:
        return {'status': 'SKIP', 'detail': 'no build_graph.json (pass --graph or set EXPLORE_GRAPH)'}
    b1 = board_mod.build_board(graph, '')
    b2 = board_mod.build_board(json.loads(json.dumps(graph)), '')
    h1, h2 = hashlib.sha256(canon(b1).encode()).hexdigest(), hashlib.sha256(canon(b2).encode()).hexdigest()
    problems = []
    if h1 != h2:
        problems.append('two builds differ (%s vs %s)' % (h1[:12], h2[:12]))
    pieces = b1['pieces']
    if len(pieces) != 32:
        problems.append('%d pieces' % len(pieces))
    sides = {s: sum(1 for p in pieces if p['side'] == s) for s in ('white', 'black')}
    if sides != {'white': 16, 'black': 16}:
        problems.append('sides %s' % sides)
    ids = rules.start_piece_ids()
    bad = [p['id'] for p in pieces if ids.get(p['square']) != p['id']]
    if bad:
        problems.append('ids not on their start squares: %s' % bad[:5])
    keep['board'] = b1
    return {'status': 'FAIL' if problems else 'PASS', 'sha256': h1,
            'detail': '; '.join(problems) or 'deterministic (sha256 %s), 32 pieces 16/16, %d reserve, cut %s'
            % (h1[:12], len(b1['reserve']), b1.get('cut'))}


def replay(game, by_id, ply_cap):
    """Replay one games.json game on a fresh board. Returns a list of problems (empty = legal)."""
    bd = rules.Board(track_ids=True)
    for mv in game['moves']:
        legal = bd.legal_moves()
        found = None
        for m in legal:
            rec = bd.move_record(m, legal)
            if rec['from'] == mv['from'] and rec['to'] == mv['to'] and rec['promotion'] == mv.get('promotion'):
                found = (m, rec)
                break
        if not found:
            return ['ply %d %s-%s is not legal' % (mv['ply'], mv['from'], mv['to'])]
        m, rec = found
        for k in ('piece', 'capture', 'check', 'san'):
            if rec[k] != mv[k]:
                return ['ply %d %s: recorded %r, replay gives %r' % (mv['ply'], k, mv[k], rec[k])]
        bd.push(m)
    out = bd.outcome()
    if out is None:
        if len(game['moves']) < ply_cap:
            return ['game stops at ply %d without an outcome' % len(game['moves'])]
        out = tour.adjudicate(bd)
    if out[0] != game['result']:
        return ['result %s, replay gives %s (%s)' % (game['result'], out[0], out[1])]
    return []


@timed
def check_tournament(keep, n_games, ply_cap):
    board = keep.get('board') or page_mod.fixture_board(None)
    keep.setdefault('board', board)
    pieces = board['pieces']
    by_id = {p['id']: p for p in pieces}

    def run():
        roster = pl.roster(pieces)
        whites = [p for p in roster if p.side == 'white']
        blacks = [p for p in roster if p.side == 'black']
        games = []
        for i in range(min(n_games, len(whites), len(blacks))):
            games.append(tour.play(whites[i], blacks[i], 1 + 5 * i + i, by_id, ply_cap))
        return roster, games

    roster, g1 = run()
    _, g2 = run()
    problems = []
    if canon(g1) != canon(g2):
        problems.append('same seeds gave different games')
    for g in g1:
        for p in replay(g, by_id, ply_cap):
            problems.append('%s v %s seed %d: %s' % (g['white'], g['black'], g['seed'], p))
    keep['games'] = {'schema': 'explore-chess-games-v1', 'players': [p.info() for p in roster], 'games': g1,
                     'table': tour.table(g1, roster)}
    res = ', '.join('%s-%s %s/%d' % (g['white'], g['black'], g['result'], g['plies']) for g in g1)
    return {'status': 'FAIL' if problems else 'PASS', 'games': len(g1),
            'detail': '; '.join(problems[:5]) or '%d games replayed legally and identically (%s)' % (len(g1), res)}


@timed
def check_page(graph, keep, out_dir):
    board, games = keep.get('board'), keep.get('games')
    if not board or not games:
        return {'status': 'SKIP', 'detail': 'needs the board and games of the previous checks'}
    data = page_mod.build_data(board, games, graph)
    text = page_mod.render(data)
    problems = []
    if not text.lstrip().lower().startswith('<!doctype html'):
        problems.append('no doctype')
    if '{{' in text and any(t in text for t in ('{{CSS}}', '{{JS}}', '{{DATA}}', '{{NOSCRIPT}}', '{{CUT}}')):
        problems.append('template placeholder left')
    if page_mod.PAGE_SCHEMA not in text:
        problems.append('page schema missing')
    missing = [p['label'] for p in board['pieces'] if html.escape(p['label']) not in text and p['label'] not in text]
    if missing:
        problems.append('%d piece labels missing' % len(missing))
    d = os.path.join(out_dir, 'chess')
    os.makedirs(d, exist_ok=True)
    with open(os.path.join(d, 'index.html'), 'w', encoding='utf-8') as fh:
        fh.write(text)
    return {'status': 'FAIL' if problems else 'PASS',
            'detail': '; '.join(problems) or 'rendered %d KB to %s' % (len(text) // 1024, os.path.join(d, 'index.html'))}


# ------------------------------------------------------------------------------------------- release view
def release_view(newcode, graph, board):
    """Map newcode.py results onto the board: reinforced pieces, promoted new communities, new reserves."""
    files = graph['files']
    col = board_mod.label_propagation(len(files), board_mod.edge_lists(graph))
    sizes = {}
    for c in col:
        if c >= 0:
            sizes[c] = sizes.get(c, 0) + 1
    max_size = max(sizes.values())
    by_comm = {p['community']: p for p in board['pieces']}
    reserve = {r['community']: r for r in board.get('reserve', [])}
    where = {(f['repo'], f['path']): f['id'] for f in files}
    core = {r['repo'] for r in graph.get('repos', []) if r.get('core')}
    reinforced, groups = {}, {}
    moves = []
    for res in newcode.get('results', []):
        cls_by_path = {}
        for u in res['units']:
            cls_by_path.setdefault(u['path'], []).append(u['cls'])
        for f in res['code_files']:
            fid = where.get((res['repo'], f.get('old_path') or f['path']), where.get((res['repo'], f['path'])))
            if fid is not None and col[fid] >= 0:
                r = reinforced.setdefault(col[fid], {'community': col[fid], 'files': 0, 'functions': 0})
                r['files'] += 1
                r['functions'] += f['new_or_changed_units']
                continue
            key = (res['repo'], os.path.dirname(f['path']) or '.')
            g = groups.setdefault(key, {'repo': res['repo'], 'folder': key[1], 'files': 0, 'lines': 0,
                                        'functions': 0, 'unique': 0, 'duplicates': 0, 'engine_maths': 0})
            g['files'] += 1
            g['lines'] += f.get('lines', 0)
            cl = cls_by_path.get(f['path'], [])
            g['functions'] += len(cl)
            g['unique'] += cl.count('unique')
            g['duplicates'] += sum(1 for c in cl if c.startswith('duplicate'))
            g['engine_maths'] += cl.count('engine-maths')
    on_board = sorted(board['pieces'], key=lambda p: (p['size'] / max_size + p['centrality'], p['id']))
    weakest = list(on_board)
    promoted, reserves = [], []
    for g in sorted(groups.values(), key=lambda g: (-g['files'], g['repo'], g['folder'])):
        g['score'] = round(g['files'] / max_size, 4)
        g['side'] = 'white' if g['repo'] in core else 'black'
        w = weakest[0] if weakest else None
        wscore = w['size'] / max_size + w['centrality'] if w else None
        if w and g['score'] > wscore:
            weakest.pop(0)
            g.update(displaces=w['id'], square=w['square'], displaced_label=w['label'], displaced_score=round(wscore, 4))
            promoted.append(g)
            moves.append('*%s@%s(x%s)' % (os.path.basename(g['folder']) or g['folder'], w['square'], w['id']))
        else:
            reserves.append(g)
    rein = []
    for c, r in sorted(reinforced.items()):
        p = by_comm.get(c)
        r.update(piece=p['id'] if p else None, square=p['square'] if p else None,
                 label=(p or reserve.get(c) or {}).get('label', 'community %d' % c), on_board=bool(p))
        rein.append(r)
    heads = ['%s %s..%s' % (r['repo'], r['base'][:7], r['head'][:7]) for r in newcode.get('results', [])]
    notation = '%s: %s%s+%d reserve%s, %d reinforced' % (
        ', '.join(heads) or 'no change', ' '.join(moves) + ('; ' if moves else ''), '', len(reserves),
        '' if len(reserves) == 1 else 's', len(rein))
    return {'schema': 'ci-chess-release-v1', 'cut': graph.get('cut'), 'largest_community': max_size,
            'weakest_on_board': {'id': on_board[0]['id'], 'square': on_board[0]['square'],
                                 'score': round(on_board[0]['size'] / max_size + on_board[0]['centrality'], 4)},
            'notation': notation, 'promoted': promoted, 'reserve': reserves, 'reinforced': rein,
            'rule': 'board.py rule 4: score = files / largest community + centrality; new folders have no edges in '
                    'the deployed graph, so centrality 0 (lower bound). Illustration, not a legal chess move.'}


GLYPH = {'king': 'K', 'queen': 'Q', 'rook': 'R', 'bishop': 'B', 'knight': 'N', 'pawn': 'P'}
UNI = {('white', 'king'): '♔', ('white', 'queen'): '♕', ('white', 'rook'): '♖',
       ('white', 'bishop'): '♗', ('white', 'knight'): '♘', ('white', 'pawn'): '♙',
       ('black', 'king'): '♚', ('black', 'queen'): '♛', ('black', 'rook'): '♜',
       ('black', 'bishop'): '♝', ('black', 'knight'): '♞', ('black', 'pawn'): '♟'}


def release_html(rel, board):
    E = lambda s: html.escape(str(s), quote=True)  # noqa: E731
    by_sq = {p['square']: p for p in board['pieces']}
    prom = {g['square']: g for g in rel['promoted']}
    rein = {r['square']: r for r in rel['reinforced'] if r['square']}
    cells = []
    for rank in range(8, 0, -1):
        for f in 'abcdefgh':
            sq = '%s%d' % (f, rank)
            dark = (ord(f) - 97 + rank) % 2 == 0
            p = by_sq.get(sq)
            cls = ['sq', 'd' if dark else 'l']
            body, tip = '', sq
            if sq in prom:
                g = prom[sq]
                cls.append('prom')
                body = '<span class="pc">★</span><span class="tag">NEW</span>'
                tip = '%s: %s (%d new files) would displace %s "%s"' % (sq, g['folder'], g['files'], g['displaces'],
                                                                         g['displaced_label'])
            elif p:
                body = '<span class="pc">%s</span>' % UNI[(p['side'], p['type'])]
                tip = '%s %s: %s' % (sq, p['id'], p['label'])
                if sq in rein:
                    cls.append('rein')
                    body += '<span class="tag">+%d</span>' % rein[sq]['functions']
                    tip += ' (+%d new/changed functions)' % rein[sq]['functions']
            cells.append('<div class="%s" title="%s" aria-label="%s">%s</div>' % (' '.join(cls), E(tip), E(tip), body))
    rows = ''.join('<tr><td>%s</td><td>%s</td><td>%d</td><td>%d</td><td>%d/%d/%d</td><td>%s %s</td></tr>' % (
        E(g['repo']), E(g['folder']), g['files'], g['lines'], g['unique'], g['duplicates'], g['engine_maths'],
        E(g['square']), E(g['displaces'])) for g in rel['promoted'])
    res = ''.join('<li><b>%s</b> %s: %d files, %d functions (%d unique)</li>' % (
        E(g['repo']), E(g['folder']), g['files'], g['functions'], g['unique']) for g in rel['reserve'][:60])
    return '''<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1"><title>Release as a chess move</title>
<style>
body{margin:0;font:15px/1.45 system-ui,sans-serif;background:#0d1117;color:#e6edf3;padding:16px;max-width:900px}
h1{font-size:20px;margin:0 0 6px}.note{color:#9aa7b4;font-size:13px}
.move{font:600 16px ui-monospace,monospace;background:#161b22;border:1px solid #30363d;border-radius:8px;padding:10px;margin:12px 0;overflow-wrap:anywhere}
.board{display:grid;grid-template-columns:repeat(8,1fr);width:min(100%%,480px);aspect-ratio:1;border:2px solid #30363d}
.sq{position:relative;display:flex;align-items:center;justify-content:center;font-size:clamp(20px,6vw,34px)}
.l{background:#e9dcc0;color:#111}.d{background:#9c7b55;color:#111}
.rein{box-shadow:inset 0 0 0 3px #2f81f7}.prom{box-shadow:inset 0 0 0 3px #f2cc60;background:#3b2f00;color:#f2cc60}
.tag{position:absolute;right:2px;bottom:1px;font:700 10px system-ui;background:#0d1117;color:#fff;border-radius:3px;padding:0 3px}
table{border-collapse:collapse;margin:10px 0;font-size:13px;width:100%%}td,th{border:1px solid #30363d;padding:4px 6px;text-align:left}
.key span{display:inline-block;width:14px;height:14px;vertical-align:middle;margin:0 4px 0 10px}
ul{padding-left:18px}.scroll{overflow-x:auto;max-width:100%%}td{overflow-wrap:anywhere}
</style></head><body>
<h1>This release as a chess move</h1>
<p class="note">%s</p>
<div class="move" aria-label="release notation">%s</div>
<p class="key"><span style="box-shadow:inset 0 0 0 3px #f2cc60"></span>promoted new community
<span style="box-shadow:inset 0 0 0 3px #2f81f7"></span>existing piece reinforced</p>
<div class="board" role="img" aria-label="chess board with promoted squares">%s</div>
<h2>Promoted (%d)</h2>
<div class="scroll"><table><tr><th>repo</th><th>folder</th><th>files</th><th>lines</th><th>unique/dup/engine</th><th>displaces</th></tr>%s</table></div>
<h2>New reserves (%d)</h2><ul>%s</ul>
<p class="note">Board cut %s. Largest community %d files; weakest piece on the board %s (%s, score %.4f).</p>
</body></html>
''' % (E(rel['rule']), E(rel['notation']), ''.join(cells), len(rel['promoted']), rows, len(rel['reserve']), res,
       E(rel['cut']), rel['largest_community'], E(rel['weakest_on_board']['id']),
       E(rel['weakest_on_board']['square']), rel['weakest_on_board']['score'])


def report(checks, rel):
    L = ['# Chess regression gate (ci-chess)', '', 'Generated by tools/explore/ci/chess_gate.py.', '',
         '| check | status | seconds | detail |', '|---|---|---|---|']
    L += ['| %s | %s | %.2f | %s |' % (c['name'], c['status'], c['seconds'], c['detail'].replace('|', '/'))
          for c in checks]
    L.append('')
    if rel:
        L += ['## This release as a chess move', '', '`%s`' % rel['notation'], '', rel['rule'], '']
        for g in rel['promoted']:
            L.append('- PROMOTED %s `%s` (%d files, %d lines; %d unique, %d duplicate, %d engine-maths functions) '
                     'onto %s, displacing %s "%s"' % (g['repo'], g['folder'], g['files'], g['lines'], g['unique'],
                                                       g['duplicates'], g['engine_maths'], g['square'],
                                                       g['displaces'], g['displaced_label']))
        if rel['reserve']:
            L.append('- RESERVE: ' + ', '.join('`%s` (%d)' % (g['folder'], g['files']) for g in rel['reserve'][:20])
                     + (' and %d more' % (len(rel['reserve']) - 20) if len(rel['reserve']) > 20 else ''))
        for r in rel['reinforced']:
            L.append('- REINFORCED %s "%s": %d files, %d functions' % (r['piece'] or 'reserve', r['label'],
                                                                     r['files'], r['functions']))
        L.append('')
    fails = [c for c in checks if c['status'] == 'FAIL']
    L.append('Result: %s' % ('FAIL (%s)' % ', '.join(c['name'] for c in fails) if fails else 'PASS'))
    return '\n'.join(L) + '\n'


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('--graph', default=None)
    ap.add_argument('--newcode', default=None, help='JSON written by newcode.py --json')
    ap.add_argument('--out-dir', default='.')
    ap.add_argument('--games', type=int, default=5)
    ap.add_argument('--ply-cap', type=int, default=60)
    a = ap.parse_args(argv)
    gpath = a.graph if a.graph is not None else next((p for p in GRAPH_CANDIDATES if p and os.path.isfile(p)), None)
    graph = load(gpath) if gpath and os.path.isfile(gpath) else None
    os.makedirs(a.out_dir, exist_ok=True)
    keep = {}
    checks = [check_perft(), check_board(graph, keep), check_tournament(keep, a.games, a.ply_cap),
              check_page(graph, keep, a.out_dir)]
    rel = None
    if a.newcode and os.path.isfile(a.newcode) and graph is not None and keep.get('board', {}).get('cut') == graph.get('cut'):
        rel = release_view(load(a.newcode), graph, keep['board'])
        with open(os.path.join(a.out_dir, 'release.json'), 'w', encoding='utf-8') as fh:
            json.dump(rel, fh, indent=1)
        with open(os.path.join(a.out_dir, 'release-board.html'), 'w', encoding='utf-8') as fh:
            fh.write(release_html(rel, keep['board']))
    md = report(checks, rel)
    with open(os.path.join(a.out_dir, 'ci-chess.md'), 'w', encoding='utf-8') as fh:
        fh.write(md)
    with open(os.path.join(a.out_dir, 'ci-chess.json'), 'w', encoding='utf-8') as fh:
        json.dump({'schema': 'ci-chess-v1', 'graph': gpath, 'checks': checks,
                   'release': rel and rel['notation']}, fh, indent=1)
    for c in checks:
        print('%-10s %-4s %5.2fs %s' % (c['name'], c['status'], c['seconds'], c['detail']))
    if rel:
        print('release: %s' % rel['notation'])
    return 1 if any(c['status'] == 'FAIL' for c in checks) else 0


if __name__ == '__main__':
    sys.exit(main())