The web client now plays borealis (data/models.json), trained on the three-round match and taking the 501-dim match view rather than a bare round. Only the actor trunk is exported -- the critic exists to grade moves in training and never plays, so the graph physically cannot leak the opponent's hand or the deck, which beats promising not to call it. The TypeScript match layer and observation mirror match.py and match_obs.py. They have to agree to the bit: a mismatch throws nowhere, the ONNX policy just consumes a wrong vector and plays worse for reasons nobody can see. So the port is not trusted -- generate_match_parity_fixture.py emits 282 positions from real JAX play (mid-round, both seats, past a roll-over, with a live carry) and the TS output is checked against them to float32 round-off. Match mode is a menu toggle. A seed fixes all three deals and the coin flips, so a match stays a pure function of it. One-deal mode is unchanged from the player's side; borealis simply sees it as round one at a carry of zero, a position it has seen a great many times. Two bugs found by driving the built app in a browser, both silent: - The result card totalled the round, not the match. It read "-11 : 3" while the match stood at -96 : 66 -- it would have named the wrong winner. It now headlines the match total and breaks the round out beneath it. - Game records were being rejected. The client's schema went to v2 (it now records which model played; the old records stored the on-screen label, which stops identifying anything once there are two models) while serve_web_with_logs.py still only accepted v1, so every record would have 400'd into a console warning. v1 stays accepted -- the 111 existing games are altair. npm test and tsc were green through both. Hence web/.claude/skills/verify, which records the recipe and the selectors so the next session drives the app instead of re-deriving how. .gitignore excluded the new model, which would have shipped a 404: the deploy builds straight from the repo. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XBQKgvBbxbheiTF1AVy1Sh
87 lines
3.4 KiB
Python
87 lines
3.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Serve the production web client and append completed games to JSONL."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
from http import HTTPStatus
|
|
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
MAX_RECORD_BYTES = 6_000_000
|
|
|
|
# v2 adds the opponent's identity (codename + hash) and the match layer -- three
|
|
# deals, the coin flips, and which round each move belongs to. v1 is still
|
|
# accepted because 111 games were recorded under it; they are all altair, which
|
|
# data/models.json records since v1 has nowhere to say so.
|
|
SUPPORTED_FORMATS = frozenset({"lost-cities-web-game-v1", "lost-cities-web-game-v2"})
|
|
|
|
|
|
def parse_record(body: bytes) -> dict[str, Any]:
|
|
if len(body) > MAX_RECORD_BYTES:
|
|
raise ValueError("record is too large")
|
|
value = json.loads(body)
|
|
if not isinstance(value, dict) or value.get("format") not in SUPPORTED_FORMATS:
|
|
raise ValueError("unsupported game record")
|
|
if not isinstance(value.get("gameId"), str) or not isinstance(value.get("moves"), list):
|
|
raise ValueError("invalid game record")
|
|
return value
|
|
|
|
|
|
def make_handler(dist: Path, output: Path):
|
|
seen_ids: set[str] = set()
|
|
if output.exists():
|
|
for line in output.read_text(encoding="utf-8").splitlines():
|
|
try:
|
|
game_id = json.loads(line).get("gameId")
|
|
if isinstance(game_id, str):
|
|
seen_ids.add(game_id)
|
|
except (json.JSONDecodeError, AttributeError):
|
|
continue
|
|
|
|
class Handler(SimpleHTTPRequestHandler):
|
|
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
super().__init__(*args, directory=str(dist), **kwargs)
|
|
|
|
def do_POST(self) -> None: # noqa: N802
|
|
if self.path != "/api/game-records":
|
|
self.send_error(HTTPStatus.NOT_FOUND)
|
|
return
|
|
try:
|
|
length = int(self.headers.get("content-length", "0"))
|
|
record = parse_record(self.rfile.read(length))
|
|
except (ValueError, json.JSONDecodeError) as error:
|
|
self.send_error(HTTPStatus.BAD_REQUEST, str(error))
|
|
return
|
|
game_id = record["gameId"]
|
|
if game_id not in seen_ids:
|
|
output.parent.mkdir(parents=True, exist_ok=True)
|
|
with output.open("a", encoding="utf-8") as stream:
|
|
stream.write(
|
|
json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n"
|
|
)
|
|
seen_ids.add(game_id)
|
|
self.send_response(HTTPStatus.NO_CONTENT)
|
|
self.end_headers()
|
|
|
|
return Handler
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--host", default="0.0.0.0")
|
|
parser.add_argument("--port", type=int, default=5173)
|
|
parser.add_argument("--dist", type=Path, default=Path("web/dist"))
|
|
parser.add_argument("--output", type=Path, default=Path("data/human-play/game-records.jsonl"))
|
|
args = parser.parse_args()
|
|
server = ThreadingHTTPServer((args.host, args.port), make_handler(args.dist, args.output))
|
|
print(f"Serving {args.dist} on http://{args.host}:{args.port}", flush=True)
|
|
print(f"Writing game records to {args.output}", flush=True)
|
|
server.serve_forever()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|