# Handoff: build `sms-python`, the SG-1000 / Master System / Game Gear board > This is the brief the board was built from, written on 2026-09-18 before any > code existed, and kept as the record of what was asked. All nine milestones > are done. For the current state read > [handoff-2026-11-12.md](handoff-2026-11-12.md). ## Context you are inheriting `z80-python` (github alewman/z80-python) is the family's flagship core: a readable pure-Python Z80 verified against hardware-tier oracles, embedded through a callables contract. `m6800-python` raised the tooling bar (state capture, disassembler, debugger, console, JSONL traces, `python -m`) and showed how a *board* is validated: its Williams sound board matched MAME write for write over 199,423 PIA writes. This repository is the first full console on the family's cores, and the stepping stone to a Mega Drive (68000 + Z80 + a VDP that keeps Mode 4), which comes after it. Read, in order, before writing code: 1. `README.md`: scope, the machine table, what is fetched. 2. `docs/start-here.md`: the three machines, memory and I/O maps, the VDP programming model, the PSG. 3. `docs/timing.md`: the scanline, the counters, when events fire, and the sub-instruction timing requirement. 4. `docs/undocumented-behavior.md`: revision differences (SMS1/SMS2/GG, discrete versus integrated PSG), known-wrong sources, open items. 5. `docs/validation.md`: every oracle with its tier and pin. 6. `docs/mame-oracle.md`: the verified trace recipe and its traps. 7. z80-python's `README.md`, `docs/start-here.md` and `src/z80_python/cpu.py`: the contract you embed. Then run `python scripts/fetch_references.py --verify` (or without `--verify` on a fresh clone). ## Prerequisites and decisions already made - **Wait for z80-python 0.4.0** (the polish round in progress on 2026-09-18). Depend on it through the callables contract: `Z80CPU(read_byte, write_byte, *, read_port=None, write_port=None)`. Until 0.4.0 is on PyPI, pin a git revision of `alewman/z80-python` in `pyproject.toml`, not a local path. - **Python floor 3.11**, CPython and PyPy both, in CI: the floor is the newest Python PyPy supports. `requires-python = ">=3.11"`, ruff `target-version = "py311"`, no 3.12-only syntax. - **The core stays dependency-free.** A frontend (window, audio) is a separate optional extra; the board must run headless and produce frames and audio as data. - **Do not modify z80-python from here.** Two z80-python changes are needed, both as PRs *there* after 0.4.0: (a) a CMOS variant (`OUT (C),0` drives $FF) for the Game Gear; (b) optionally, the T-state offset of each bus access inside an instruction (see `docs/timing.md`, "Sub-instruction timing"). Both can be worked around in the board for the early milestones. ## Your task Build the board as `src/sms_python/`. The module shape in `docs/start-here.md` is a suggestion; the requirements are: - **Machines as data.** `SG1000`, `SC3000` (keyboard optional), `MarkIII`, `SMS1`, `SMS2`, `GameGear`, and PAL variants are configurations: a VDP variant, a PSG variant, a RAM size, a port decode, a BIOS option. The quirks in `docs/undocumented-behavior.md` are fields on those variants, each with a comment naming its source and tier. - **One scheduler.** The board steps the Z80 (`cycles = cpu.step()`), advances the VDP and PSG by those cycles, and raises INT and NMI. A catch-up design (devices run up to the current cycle when the CPU touches them, and at line boundaries) is the usual answer; choose, and document why. - **Cartridge boards from MAME's software lists.** Identify the board type by CRC from `/usr/share/games/mame/hash/{sg1000,sms,gamegear}.xml` (read the file at runtime or generate a small table with a script; do not commit MAME's XML). - **Tooling at the family bar**: `state.py` (save and restore the whole machine), a debugger that reuses z80-python's `DebugSession` with board-level watchpoints (VDP registers, VRAM, I/O ports), a JSONL trace in z80-python's schema plus I/O events, `py.typed`, and `python -m sms_python CART --frames N --png out.png --wav out.wav`. ### Milestones, each with its acceptance test, in oracle-tier order 1. **Board skeleton and ZEXALL-SMS.** The Master System memory map with the Sega mapper (the ZEXALL-SMS images are 64 KB, more than the SG-1000's 48 KB window), the I/O decode, and the SDSC debug-console ports ($FC/$FD) as an output sink. The VDP can be a stub at first. ZEXALL-SMS probes for a VDP (Mode 4, else TMS9918 text), so if it waits on VDP status, bring milestone 3's register file forward rather than faking values. Run `zexdoc.sms` and `zexall.sms` from ZEXALL-SMS v0.21 (`tests/test_roms/github/ZEXALL-SMS-0.21.zip`, the GitHub release; source in `reference/src/zexall-sms` at the same tag). **Acceptance:** every test prints OK on the SDSC console under PyPy, with the instruction and cycle totals and wall time recorded. The CPU was certified in z80-python, so this checks the plumbing (paging, RAM mirror, port decode) under a hardware-captured CRC set. Record the `SCF`/`CCF` pre-test counts it prints (`undocumented-behavior.md`, CPU item 2). 2. **The PSG, both variants.** Tone, noise (16-bit/$0009 and 15-bit/$0003), attenuation, the latch/data protocol, the GG stereo register, and a sample output at a chosen rate. **Acceptance:** the 15-bit variant's white noise equals `SN76489 white noise.dat` over all 32,767 samples (the wiki's bit pattern; it is the $0003 m-sequence, inverted, starting at phase 32,752). The 16-bit $0009 variant follows the wiki text, MAME and Genesis Plus GX, because the wiki's "Sega" pattern file contradicts them (`undocumented-behavior.md`, open item 6): say so in the test. Unit tests for the tone-0/1 rule and the power-up state. The SMS2 clipping table is optional and off by default. The SG-1000 M2 Check Program's sound test and JoppyFurr's SN76489 TestRoms are the functional checks. 3. **TMS9918A modes 0–3, and the SG-1000 working.** The renderer, sprites (four per line, fifth-sprite flag and number, collision), the frame interrupt, the TI manual's register semantics, the undocumented mixed modes from Sean Young's document. **Acceptance:** Sega's SG-1000 M2 Check Program shows "SCRATCH RAM OK" and every check OK except the expansion port, which should report BAD without a loopback plug, as it does on MAME (hardware- corrected, functional). Then MAME `sg1000` lockstep (`scripts/mame_trace.py`) on at least five games for at least 60 seconds each, CPU state and I/O events identical, N stated. The first divergence is diagnosed to a source before the run is extended. Frame images are compared with MAME snapshots as a detector only. 4. **Mode 4, the Sega mapper, and the Master System working.** Mode 4 rendering, CRAM, scrolling and locks, the line interrupt, the H and V counters with TH latching, ports $3E/$3F/$DC/$DD, the pause NMI, region detection, the export BIOS (boot-through and skip-BIOS modes), and the SMS1 and SMS2 VDP variants. **Acceptance:** SMS VDP Test v1.31 passes every test on the SMS2 variant, and on the SMS1 variant every test whose hardware result is recorded (the readme and forum thread 10695), with each exception listed in `docs/validation.md` against its hardware report. Charles MacDonald's VCounter Test, FluBBa's PauseTest, and ZEXALL-SMS in Mode 4 all behave as their documents say. MAME `sms` and `sms1` lockstep on the VDP test and five games, N stated. 5. **Sub-instruction timing.** Decide between the board access-time table and a z80-python hook (`docs/timing.md`). **Acceptance:** FluBBa's timing tests ("HC change on TH 0->1", "HCounter correct", "VCounter chg time", both IRQ HCount tests, "VINT flag HCount", "Spr col correct HC", "Spr ovr correct HC", and the two latch columns) show the hardware values. This milestone may move before 4's final acceptance: they are the same test program. 6. **Game Gear.** The 160×144 window, 12-bit CRAM with the odd-byte latch, ports $00–$06, stereo, the CMOS `OUT (C),0` (needs the z80-python option, or a documented board-side shim until it lands). **Acceptance:** GG Button Test and SN76489 TestRom-GG behave as documented; the VDP test's GG mode passes what the forum thread records for a GG; MAME `gamegear` lockstep on five games. 7. **Compatibility sweep (detector).** Boot every cartridge in the local SG-1000, Master System and Game Gear sets for N seconds against MAME's frame at the same time (and, where cheap, the trace), and publish the table of divergences with their causes. Use the cartridge-board table from MAME's hash files. Nothing is "fixed" to match MAME without a higher-tier source. 8. **Sound-driver stream (detector), optional.** For games with a vgmrips pack, compare the PSG register-write stream the game's own sound driver produces against the pack's VGM log, using `vgm_parser.py` from `github.com/alewman/vgmllm` (MIT). vgmrips logs are mostly emulator-made: detector tier. 9. **YM2413 FM unit, optional.** Japanese SMS and Mark III with FM. Judge: Nuked-OPLL (die-derived) and the openMSX YM2413 measurements (`reference/src/ym2413/results`). Do not skip a rung. The early ones make the later ones cheap to diagnose. ## Constraints - **Oracle tiers are not negotiable.** MAME, Genesis Plus GX and Gearsystem are detectors. A disagreement with them is a question for a higher tier, not a bug report against the board. - **Never commit ROMs, BIOS images, traces, fetched documents or test programs.** `reference/`, `tests/test_roms/` and `tests/mame_traces/` are ignored. Commercial cartridges are read in place from a local copy (`NO_INTRO_DIR`). - **Do not read Genesis Plus GX** (non-commercial licence). As first written this brief said to read and cite it; it was changed in November 2026 to the family's rule that GPL, LGPL and non-commercial emulators are only run, as closed boxes, never read while writing code. - **Pins in every claim**: z80-python revision, MAME version, test ROM SHA-256, Python versions, wall time, instruction and frame counts. - **Do not modify sibling repositories.** Propose z80-python changes as PRs there. - Commit in reviewable units. ## Size and speed, honestly - **Code**: the VDP is the bulk (both renderers, sprites, counters, interrupts, variants): expect 2,500–4,000 lines. The PSG is a few hundred; the board, mappers and ports about 1,500; tooling about as much again. Tests and documents on top. - **Speed**: an SMS runs 3.58 M CPU cycles/s, about 450–500 k Z80 instructions/s. z80-python measured 586 k instr/s on CPython 3.14 before its polish round (target 2.5 M) and about 55 M/s on PyPy. The CPU alone is borderline on CPython and comfortable on PyPy. **The VDP is the real cost**: 256×192 pixels × 60 frames is 2.9 M pixel decisions a second, with sprites and priority. Full speed on CPython is not expected and is not a milestone. Record frames per second on CPython and PyPy at every milestone, render per line (not per pixel call), and keep rendering out of the CPU's hot path. ## What done looks like `README.md` states which milestones pass, with counts and pins; `docs/validation.md` turns from "the oracles found" into "the certification record"; CI runs milestones 1–3 on every push, fetching the pinned test ROMs (the open-licensed ones) the way z80-python fetches its vectors; the MAME lockstep runs are recorded locally with their command lines and counts. Then the Mega Drive: `m68000-python` must be done first (see its brief).