# Handoff: build `hg51b-python`, the SNES Cx4 core > **Wave 2 (2026-11-19).** This brief is the Phase 0 record and keeps its decisions. Its > source rule is superseded: GPL and unlicensed sources are **closed boxes only** (run, > never read); byuu's model is cited in its ISC form, ares; the MiSTer Cx4 is not opened > (no licence). Where the text below says what bsnes, Mesen2 or MiSTer *do*, it records > what was read under the old rule; docs/provenance.md and undocumented-behavior.md hold > the current sources. ## Context you are inheriting The family's shape is **chips are cores, boards compose cores**; CPUs always get their own core (Aubrey's chip-extraction rule), and a coprocessor that runs its own program is a CPU. This core's first user is `snes-python` (a sibling repository), milestone 7 ("Super FX, Cx4, Super Game Boy, MSU-1. GSU and Cx4 as their own cores (each its own Phase 0) ... **Acceptance**: ... Cx4 self-test PASS"), and milestone 6's deferred "Mega Man X2/X3's Cx4 test". snes-python's handoff decision 3 named this repository: "Cx4 to `hg51b-python`". A board that finds a corner of this core raises it **on the core** (an issue or PR here; re-certification is fine), never as a workaround in the board. Models for the code and the tooling: - `upd7725-python` (a sibling repository): the closest Phase 0 and build of a SNES coprocessor core (the same docs set, a board-free harness running the program's own self-tests, a recorded-trace replay, class-attribute switches for every contested behaviour, the board wiring in its README). - `spc700-python`, `huc6280-python`: the readability contract (one instruction family per module, the hardware reason as a comment on the line that encodes it) and the tooling bar (`state`, `disasm`, `debug`, `trace`, `console`, `python -m`). - snes-python `src/snes_python/necdsp.py` (a timed cartridge, `advance` with an exact fraction, the chip caught up before each access) and `sa1.py` (a second CPU on the cartridge bus, vectors from the coprocessor, the IRQ line). This chip is more than the uPD7725 in three places: **it fetches its program from the cartridge ROM through a cache it loads itself**, **it has a DMA engine and a byte bus of its own**, and **it sits between the S-CPU and the ROM**, so the S-CPU loses the ROM while the chip uses it. It is less in one: **no manufacturer document exists**, so every behaviour is research or emulator tier, and the game's own built-in test is the only hardware-designed judge. The user's rules that bind this work: - **Oracle tiers**: hardware-captured > hardware-designed self-test > manufacturer > program > research > emulator; a low tier detects, never judges; state the tier of every claim. Conflicts: console > fullsnes/anomie > two emulators agreeing > MAME. **No hardware capture of this chip exists.** - **Python floor 3.11** (PyPy): `requires-python = ">=3.11"`, ruff `target-version = "py311"` (pinned ruff 0.16.8), CPython and PyPy both green. Watch the PyPy 80-attribute rule (keep the CPU's hot state under 80 instance attributes, or use lists). - **Reference cores are correct, not fast**; a `-fast` fork is later work. - **Modern over compat**: dataclasses, callables, no shims. - **BYOR**: no ROM, data ROM image, trace or screenshot committed or fetched; the cartridges are read in place (No-Intro zips); the data ROM is computed (decision 3) or read from a BYOR file. - **GPL and unlicensed sources: closed box only** (bsnes, Mesen2, snes9x, MAME's `snescx4.cpp`: built and run as detectors, never opened; MiSTer's Cx4 has no licence: not opened). byuu's model is read and cited in ares (ISC, notice kept in NOTICE). - **No dangerous-looking shell one-liners** (`rm -rf`, `sed -i`, `ln -sfn`); anything reading `reference/` or a ROM runs with `python -I`; heavy runs under `nice -n 19`, one at a time; **local git only** until Aubrey says otherwise; minimal CI (PyPy only) if a GitHub repository ever exists. ### Read, in this order, before writing code 1. `README.md`. 2. `docs/start-here.md`: registers, the encoding table, flags, cache and pages, the bus port, data RAM/ROM, the S-CPU's map, the boundary. 3. `docs/timing.md`: the clock, costs, the S-CPU's view while the chip runs, what the program uses, the oracle measurements. 4. `docs/undocumented-behavior.md`: U1-U21, C1-C15. 5. `docs/validation.md`: every oracle with tier; what does not exist; rungs. 6. `docs/mame-oracle.md`: the MAME and Mesen2 recipes, their traps, the replay. 7. fullsnes l.8468-8766, then ares `component/processor/hg51b/` (≈1,500 lines) and `sfc/coprocessor/hitachidsp/memory.cpp`; Mesen2's differences come from running it (`scripts/cx4_probe.py`), never from its source. Then `python -I scripts/fetch_references.py --verify`, `python -I scripts/check_data_rom.py`, `python -I scripts/survey_program.py`. ## Decided by the user - **The Cx4 core is its own repository, `hg51b-python`** (snes-python handoff-brief decision 3, 2026-10-21). - **ROMs are BYOR**, read from user paths (snes-python decision 5). ## The core boundary The HG51B169's pins are the SNES bus (A0-A23, D0-D7, /RD, /WR, /IRQ, /RST), the ROM/SRAM bus (RA0-RA20, RD0-RD7, /ROM1, /ROM2, /SRAM, /ROE, /RWE) and the crystal (fullsnes pinout). The core is the die between them. | Part | Where it lives | Why | | --- | --- | --- | | Registers, decode, ALU, multiplier, flags, stack, cache pages, data RAM, data ROM | **core** | the chip | | The SNES-side register file and decode of $6000-$7FFF (data RAM bytes, $7F40-$7F5F I/O, vectors, R0-R15 bytes) | **core** | the chip decodes A0-A23 itself (pins 1-24); every consumer needs the same map | | The cache loader, DMA engine, bus port, wait states, suspend, lock | **core** | inside the die; they drive the ROM bus | | "The chip owns the ROM bus now" (cache load, DMA, bus access) and the vector bytes for $00:FFE0-$FFFF | **core**, as a property and a method | the board needs them to block S-CPU ROM reads (U16, C12) | | /IRQ | **core**, as a boolean output | the pin; the board ORs it into `Cartridge.irq` | | The ROM bytes, LoROM decode of the chip's 24-bit bus addresses, the two-chip select, SRAM (none fitted) | **board**, behind two callables | the cartridge's chips and wiring (SHVC-1DC0N one ROM, SHVC-2DC0N two) | | The 20 MHz crystal, its ratio to the master clock, catching the chip up before each S-CPU access | **board** | the oscillator is on the cartridge | | S-CPU wait states for $6000-$7FFF and ROM | **board** | the S-CPU side of the connector | ## The contract (required shape; names are open decision 1) ```python from hg51b_python import HG51B, data_rom cx4 = HG51B( bus_read=lambda address: rom_byte(address), # the chip's ROM/SRAM bus: 24-bit address -> byte bus_write=lambda address, value: None, # SRAM writes (none fitted on Cx4 boards) data_rom=None, # None: computed (U21); or 1,024 words from a BYOR image ) cx4.reset() # power-on state (U20); C15 for the console's reset cx4.run(clocks) -> int # advance by chip clocks; cache loads and DMA advance per byte (decision 5) cx4.read(address) -> int # S-CPU read of $6000-$7FFF (bank bits ignored); no side effect except bus timing cx4.write(address, value) # S-CPU write; $7F47/$7F48/$7F4F start DMA/preload/program when halted cx4.irq -> bool # /IRQ asserted (U13) cx4.owns_rom_bus -> bool # cache load, DMA or bus access in flight (U16) cx4.vector(offset) -> int # the byte the S-CPU reads at $00:FFE0+offset while owns_rom_bus cx4.data_ram # 3,072-byte bytearray cx4.capture_state() / cx4.restore_state(state) ``` - The board's `Cx4Cartridge` (snes-python, milestone 7) is `timed = True`; `advance(master_clocks)` accumulates `master_clocks * 176` and runs `owed // 189` chip clocks (NTSC; PAL 2,000,000/2,128,137); its `read`/`write` route banks 00-3F/80-BF $6000-$7FFF to the core, and ROM reads to its own ROM unless `owns_rom_bus` (then open bus, except $00:FFE0-$FFFF -> `vector`); `irq` reads `cx4.irq`. The chip's `bus_read` is the board's ROM in LoROM order (banks 00-3F/80-BF $8000-$FFFF, C0-FF $0000-$FFFF, linear = (bank & 3F) << 15 | offset & 7FFF, ares `hitachidsp/memory.cpp` l.26-40), with data RAM at the chip's own $6000-$6BFF handled inside the core (DMA targets 006000h). - Contested behaviours (C1-C15) are class attributes (decision 4), so a comparison flips one without editing code. - Plain integers, lists and bytearrays, no generators, no per-instruction allocation, so `hg51b-rust` and a `-fast` fork can transcribe it. ## Proposed layout (the build session may refine) ``` src/hg51b_python/ __init__.py HG51B, data_rom cpu.py registers, reset, run/step, the cache, DMA, bus port, suspend, lock _decode.py the 64 opcode groups and their sub-fields (one table, shared with disasm) _alu.py ADD/SUB/CMP/logic/shifts/MUL and flags (C1, C2 decided here, commented) _flow.py jumps, calls, skips, the stack (C4, C5) host.py the S-CPU side: $6000-$7FFF read/write, status, vectors, IRQ data_rom.py the six tables, exactly (decimal, floor, saturate) and a BYOR loader with SHA-1 check disasm.py byuu's syntax, ares (decision 11) state.py, debug.py, trace.py, console.py, harness.py, replay.py, __main__.py, py.typed tests/ test_decode.py (rung 0), test_alu.py, test_flow.py, test_cache.py, test_bus.py, test_dma.py, test_host.py (rung 1), test_data_rom.py (rung 2), test_selftest.py (rung 3, BYOR), test_mesen_replay.py (rung 4, slow) ``` ## Your task: the rung ladder Build to the contract and pass the rungs of [validation.md](validation.md) "Rung plan", in order: 0. **Decode**: all 65,536 encodings classified like byuu's table (ares); `disasm` of both programs (retail and Rockman X2 beta); executed words checked against Mesen2's trace disassembly. 1. **Directed tests**, one file per family, each naming its U/C entry and tier. 2. **The data ROM**: the generator's SHA-1 = a002f4ef... (the test uses no image; with a BYOR `cx4.bin` it also compares bytes); byte sum 054336h. 3. **The game's test functions in the harness** (BYOR cartridge): 0E:00-3C, 0E:40 after DMA of every 2 KiB of the ROM, 0E:54 over an R0 sweep, 0E:5C, 0E:89; expected values read from the S-CPU's test code (find it from the "Cx4 TEST" string table at ROM 0x315C2 in X2 USA; the HLE `op40`-`op89` are detectors). 4. **Mesen2 replay** (mame-oracle.md "The replay"): boot window, the test loop, then gameplay windows that reach pages 2-0Ch (wireframes, scaling, trig). Extend `scripts/mesen_cx4_trace.py` with the Lua host stream first. Classify every divergence by C-entry; record the measurements undocumented-behavior.md "What the build session should measure first" asks for. 5. **(Follow-up)** HLE command comparison. 6. **Through snes-python milestone 7**: the test screen on the board, eight "OK."; Mega Man X2/X3 frames vs Mesen2. ### The minimal harness (`harness.py`) The core, a BYOR cartridge ROM on `bus_read` in LoROM order, and a scripted S-CPU: `write` the configuration the games use ($7F52 = 00, $7F50 = 44, $7F51 = 01, base 028000h, $7F4C = 00), DMAs, page/PC starts, polls of $7F5E bit 6 with `run` between, `read` of R0-R15 and data RAM. It also replays a Mesen2 host stream (rung 4). No 65816, no PPU, no master-clock ratio. ### Tooling at the family bar `state.py` (`CPUState`: pb, pc, p, a, mul, mdr, rom, ram, mar, dpr, r[16], flags n z c v, stack, cache pages and addresses, halt/lock/suspend, DMA and bus state), `disasm.py`, `debug.py` (`DebugSession`: breakpoints on PB:PC, watchpoints on data RAM, S-CPU accesses and bus reads), `trace.py` (JSONL, one record per instruction, one per S-CPU access, one per cache load and DMA), `console.py`, `py.typed`, and `python -m hg51b_python CART [--test-function 0E:89] [--trace out.jsonl]` running the harness. ## Decided by the user, 2026-11-07: every recommendation below taken Aubrey took all thirteen as recommended ("Take all, build it"). Going public still waits for Aubrey's word, as for the other cores. The items keep their reasoning for the build session: Each has a recommendation; the build session starts from the recommendations unless Aubrey says otherwise. 1. **Names.** Repository `hg51b-python` (decided). Recommend import package **`hg51b_python`** and class **`HG51B`** (byuu's name for the processor, ares; the "169" is this part's mask/data-ROM variant, which lives in `data_rom`). Alternative: `HG51B169` or `Cx4` (Capcom's name for the board chip), which reads worse beside a processor-named core family. 2. **Boundary: chip-level or CPU-level.** Recommend **chip-level** (the table above): the SNES-side registers, cache, DMA and bus port are in the die and every consumer needs them identically. Alternative: bsnes' split (CPU core + `HitachiDSP` glue in the board), which would leave 300 lines of chip behaviour in snes-python where it cannot be tested board-free. 3. **The data ROM: compute it.** Recommend **the core computes the 1,024 words from fullsnes' formulas exactly** (Python `decimal`, floor, saturate; ~1 s once per process on CPython, cached) and accepts an optional BYOR image (`cx4.bin` / `cx4.data.rom` / `hg51bs169.data.rom`), checked by SHA-1. Measured: every word equals a real chip's dump; no image is committed or fetched, and a generator is not an image. A Rust transcription can use f64 with the one exact case (tan 45 deg = 10000h) handled, the nearest other entry being 7.2e-4 from a rounding boundary. Alternatives: BYOR only (most users have no `cx4.bin`: MAME keeps it inside software-list sets, which are not on this machine), or reading the table out of a pinned emulator's source at run time (GPL text as data; ruled out in Wave 2). 4. **The contested defaults, as a group** (each a class attribute): C1 bsnes shift limit, C2 truncate A<