# Handoff: build `65816-python`, the SNES's CPU core ## Context you are inheriting The family's shape is **chips are cores, boards compose cores**. Each core is certified on its own against its oracles and pinned by the boards that use it. This core's first user is `snes-python` (`/data/emu/snes-python`, being prepared in parallel with `spc700-python` and `s-dsp-python`); an Apple IIGS or a 65C816 single-board computer could follow. A board that finds a corner of this core raises it **on the core** (an issue or a PR here, re-certification is fine), never as a workaround in the board. Models for the code and the tooling: - `6502-python` (`/data/emu/6502-python`, 0.2.0.dev0, public): **its frame is this core's base class** (decided, below). Every CPU cycle is one bus callback, in chip order; interrupts polled at the end of the second-to-last cycle; `RP2A03` shows how a chip variant is a subclass with class-level switches (`_decimal_mode`) and a per-class dispatch table (`build_table(cls)`). - `z80-python` (`/data/emu/z80-python`, v0.4.0 on PyPI): the readability contract (one instruction family per module, one mnemonic per handler docstring, the hardware reason as a comment on the line that encodes it), the tooling bar (`state.py`, `disasm.py`, `debug.py`, `trace.py`, `console.py`, `python -m`), `docs/` layout, oracle tiers. - `sm83-python` (`/data/emu/sm83-python`): the Phase 0 this repository copies in shape; its bus contract carries internal cycles with their address, as this one must. - `m6800-python`: the rung ladder, scripts that drive MAME. The user's rules that bind this work: - **Oracle tiers**: hardware-captured > hardware-verified > manufacturer > research > emulator-derived (validation.md); a low-tier oracle is a detector, never a judge; state the tier of every claim. - **Python floor 3.11** (the newest PyPy supports): `requires-python = ">=3.11"`, ruff `target-version = "py311"`, CPython and PyPy both green. - **Reference cores are correct, not fast.** A `-fast` fork is later work. - **Modern over compat**: callables, dataclasses, no shims; no external users. - **No dangerous-looking shell one-liners** in scripts or docs (no `rm -rf`, `sed -i`); keep CI minimal (PyPy only, main + PRs, cancel in progress) if and when a GitHub repository exists. This repository is **local git only** until the user says otherwise. - **Never copy a chip file between repositories**; extract on the second consumer. Here: depend on 6502-python's frame, never vendor it. - Run any Python that reads `reference/` with `-I`. ### Read, in this order, before writing code 1. `README.md`. 2. `docs/start-here.md`: registers, emulation vs native, addressing, the bus as the 5A22 sees it, interrupts, WAI/STP, MVN/MVP, decimal, what the core does not own. 3. `docs/timing.md`: the measured agreement, every Table 5-7 row, the notes. 4. `docs/undocumented-behavior.md`: U1-U14, C1-C8. 5. `docs/validation.md`: every oracle with tier and pin, results, rungs, the harness. 6. `docs/mame-oracle.md`. 7. `/data/emu/6502-python/docs/start-here.md`, `docs/api-stability.md` and all of `src/sixfiveohtwo/` (about 3,400 lines); `/data/emu/z80-python/docs/ start-here.md` ("The embedding contract"). Then `python -I scripts/fetch_references.py` (10 repositories incl. the 2.8 GB SingleStepTests corpus, 15 files incl. a 750 MB GHDL bundle; `--skip 65816` and `--no-tools` leave them out), `python -I scripts/build_referees.py`, and `python -I scripts/datasheet_timing.py --cases 100` to see the bus model run. ## Decided by the user - **Build on 6502-python's frame** (Aubrey, 2026-10-21; narrowed 2026-10-22 after reading its core): `65816-python` stays its own repository and **depends on 6502-python, pinned** (a git commit until a release contains the frame, then a version). `W65C816` subclasses the frame (below) and has its own addressing modes and handlers; it reuses no NMOS handler and never copies files. The 2026-10-21 plan to route NMOS handlers through bank and width hooks (old PRs 3-4) was dropped: a call per cycle on the NMOS path for handlers the 65816 overrides anyway. ## Proposed (the build session may refine; open items are listed at the end) - **Names**: distribution `65816-python`, import package `w65c816`, class `W65C816` (WDC's part name; a Python identifier cannot start with a digit, and 6502-python's `sixfiveohtwo` spelling would give `sixfiveeightsixteen`). The 5A22 is the SNES's SoC, not a core variant: there is no `Ricoh5A22` class here. One class for every 65C816; the 65802 (16-bit bus) is out of scope. - **Subclass the frame, do not wrap**: `W65C816` subclasses 6502-python's frame and has its handlers in its own modules (`_native.py`, `_block.py`, `_long.py`, ...), one family per module. - **Fetch-first `step()`**: a step starts with the opcode fetch (or an interrupt entry) and ends after the last cycle, as SST records it. MVN/MVP: one step per byte (the chip refetches the opcode; interrupts fit between bytes), so a SST case is N steps. ## The bus contract (required) One callback per CPU cycle, in chip order, **including IO cycles**, each with the 24-bit address the chip drives, and the cycle's kind readable inside the callback: ```python cpu = W65C816(read_byte, write_byte, idle) # read_byte(address) -> int a cycle with RWB high and VDA or VPA (or VPB) # write_byte(address, value) a cycle with RWB low # idle(address) an IO cycle: VDA = VPA = 0, RWB high # address is 24-bit (bank << 16 | offset). # Inside any callback: cpu.vda, cpu.vpa, cpu.vpb, cpu.mlb (bools) describe # the current cycle; cpu.e, cpu.m, cpu.x_flag are the mode as the pins show it. cycles = cpu.step() # cycles consumed == number of callbacks made ``` - `idle` defaults to a no-op; a host that ignores IO cycles still gets correct cycle counts from the return value. The SNES board needs it: IO cycles are 6 master clocks, accesses 6, 8 or 12 by address (start-here.md). - The board advances its devices **inside** the callbacks, by the length it decides for that cycle, never by adding `step()`'s return value on top. A DMA or HDMA that halts the CPU runs inside the callback before the access is performed (HYPOTHESIS: as read from bsnes's GPL source before the 2026-11-14 rule; for review, 2026-11-24). - The emulation-mode RMW modify cycle (C3) is a `write_byte` call with `cpu.vda` false and `cpu.mlb` true; the board decides whether it reaches the bus. - Interrupt inputs follow 6502-python's API (`request_maskable_interrupt`, `clear_maskable_interrupt`, `request_non_maskable_interrupt`, `request_reset`), plus `request_abort()`; the poll point is 6502-python's (end of the second-to-last cycle; timing.md "Interrupt sampling"). - `cpu.waiting` (WAI) and `cpu.stopped` (STP) are readable; a waiting or stopped CPU's `step()` makes one `idle(PBR,PC)` call and returns 1 (the 5A22 keeps clocking, DMA keeps running); WAI ends on NMI/IRQ/ABORT/reset, with I = 1 an IRQ ends it without a vector (U11). - Plain integers in the hot path, no generators or coroutines, so a `65816-rust` and `-fast` forks can copy it. ## What 6502-python provides: the frame (decided 2026-10-22) One PR on `alewman/6502-python` splits `MOS6502` into a documented, semver-covered base class, the **frame**, and the NMOS handlers on top of it, with no change in NMOS behaviour (re-certified there against SST `6502` and `nes6502` and Dormann). The frame holds what is subtle, certified and chip-independent: - the bus callables, their setters, and the `_request`/`_confirm` wrappers that tell whether a request change came before the last cycle; - the interrupt request API (`request_maskable_interrupt`, `request_non_maskable_interrupt`, `request_reset` and their clears and `*_pending` properties) and the poll (`_requests`, `_polled`, `_deferred`, `_polled_i`, `NO_POLL`); - `step()`'s skeleton: reset, a halted CPU, the boundary's interrupt decision, one instruction, the deferred poll; with overridable hooks for each (`_accept_reset`, `_halted`, `_boundary_interrupt`, `_enter_interrupt(kind)`, `_execute`); - the poll fields of a state snapshot, captured and restored. `W65C816` subclasses the frame, not `MOS6502`, and writes everything else itself: the `idle` callable and its confirming wrapper, cycle kinds (VDA/VPA/VPB/MLB), 24-bit addressing, widths, its own vectors and entry sequence, ABORT (an extra request bit through `_boundary_interrupt`), WAI and STP through `_halted`, and its cycle count. The earlier PR list (0-8) is superseded: PRs 3-4 would have put a call per cycle on the NMOS path for handlers the 65816 overrides anyway, and PRs 1, 2, 6 and 7 are needs the subclass meets itself. Tooling generalisation (the old PR 8) is a later PR, after rung 1. ### NMOS behaviours the 65816 must not carry over The frame (below) carries none of these: they live in 6502-python's NMOS handlers, which `W65C816` does not inherit. They are listed so that patterns borrowed from those handlers are not borrowed with them: - **Dummy reads.** NMOS dummy cycles read real addresses; the 65816's are IO cycles (VDA = VPA = 0, start-here.md). On the SNES a read is 8 clocks in slow regions and can acknowledge an I/O register; an IO cycle is 6 clocks and touches nothing. Inherited reads would shift timing on every implied instruction and every page crossing. - **Decimal flags** (U7): NMOS N/V/Z from the binary sum; 65816 N/Z valid. - **`JMP ($xxFF)`**: NMOS page bug (`_op_jmp_ind`); the 65816 has none. - **JSR's bus order**: 6502-python's `_op_jsr` does low byte, stack read, push, push, high byte; the 65816's `JSR a` does low, high, IO, push, push (DS row 1c, "different order from N6502"). Only `JSR (a,x)` resembles the 6502 order. RTS's last cycle: NMOS reads the pulled address; 65816 is IO at S. - **Page-zero and page-one wrapping**: correct only in emulation mode, only with D.l = 0, only for the 6502's instructions and modes (U1, U2); `(d,x)` has its own quirk (U3). - **Interrupt entry and BRK**: NMOS reads PC twice and leaves D; the 65816 fetches, idles, pushes PBR in native mode, clears D. 6502-python models **interrupt hijacking** (an NMI during BRK/IRQ steals the vector, NESdev from visual6502); nothing shows the 65816 does this (bsnes fixes the vector before pushing: HYPOTHESIS, read from its GPL source before the 2026-11-14 rule; for review, 2026-11-24), so the 65816 must not inherit it. - **Branch polling**: 6502-python's branch-specific poll points come from visual6502 for the NMOS part; unverified on the 65816 (rung 6 question); native branches never pay for a page crossing. - **RMW**: NMOS writes the old value (`_shifts._modify`); 65816 native mode has an IO cycle there and emulation mode writes with VDA = 0 (C3). - **The P invariant**: 6502-python keeps bit 5 set and B clear and validates it in `CPUState`; in native mode those bits are M and X. - **JAM, the 105 undocumented opcodes, `ane_constant`/`lxa_constant`, `dma_stalled`**: NMOS-only, absent on the 65816. ## Your task Land the frame PR on 6502-python (re-certified there), pin it here, then build `src/w65c816/` to the contract above and pass the rungs in [validation.md](validation.md) "The plan", in order: 0. **Tables and schedule.** Opcode map == `scripts/datasheet_timing.py` `ROWS`; for every opcode, (E, M, X) and path, the core's per-cycle (address, VDA, VPA, VPB, RWB, MLB) == the datasheet schedule (move `schedule()` into a test fixture rather than importing the script), with U1-U3 and the C1/C2 decisions applied. Readability test. 1. **SingleStepTests 65816**, all 512 files: registers (A, X, Y, S, D, DBR, PBR, PC, P, E), RAM, and every cycle's address, value and VDA/VPA/VPB/RWB/E/M/X/MLB; force SH = $01 in emulation-mode initial states and XH = YH = 0 when X = 1 (timing.md); WAI/STP's trailing null row means "now waiting/stopped"; masks for C1 (`7C`, `FC` pointer reads) and C2 (`42`); C4's cases excluded and counted. A sample (100 per file) in the quick loop, everything under `-m slow`. 2. **gilyon cputest-full and -basic** in `w65c816.harness` (validation.md "The minimal harness"). 3. **krom's 23 CPU tests** in the harness, PASS decoded from VRAM writes. 4. **MAME replay** of real games, I/O reads fed from MAME's log (mame-oracle.md "Use"): detector. 5. **P65C816 testbench** (optional in the first session): SST initial states into srg320's VHDL under GHDL, per-cycle kinds compared, a third opinion on C1-C3. 6. **Through snes-python**: its interrupt-timing, DMA/HDMA, WAI and game milestones certify what only a board can; its core failures come back here as issues/PRs. ### Tooling at the family bar `state.py` (`CPUState` with `a x y s d dbr pbr pc p e`, `waiting`, `stopped`, the poll fields from 6502-python), `disasm.py` (M/X-aware operand lengths, checked against MAME's disassembly of the same trace), `debug.py` (breakpoints on 24-bit PC, bus watchpoints that see IO cycles), `trace.py` (JSONL, the family schema with `kind` = read, write, idle and the VDA/VPA/VPB/MLB bits), `console.py`, `py.typed`, and `python -m w65c816 ROM.sfc [--max-cycles N] [--trace out.jsonl]` running a ROM in the harness. Generalise 6502-python's tooling modules in a later PR rather than writing parallel ones. ## Decided by the user: the open decisions (2026-10-21) Aubrey took every recommendation this Phase 0 made: 1. **Names**: distribution `65816-python`, import `w65c816`, class `W65C816`. 2. **Local until rung 1 passes**, then public (after the frame PR it pins is merged and pushed). 3. **6502-python PR order**: superseded 2026-10-22 by the frame (above): one bit-identical PR now, tooling after rung 1. A CMOS (65C02) mode stays wanted for the Lynx and HuC6280, off this core's path. 4. **C1**: the datasheet (VPA) for the JMP/JSR (a,x) pointer reads; the corpus is masked there. 5. **C2**: bsnes (a program read) for WDM's operand cycle; the corpus is masked there. 6. **C3**: the core reports the emulation-mode RMW modify cycle as a write with VDA = 0, and the board decides whether the 5A22 strobes it. **Aubrey owns a Super Famicom and an EverDrive X5**, so snes-python settles this with a console probe (no logic analyser needed if the probe can observe the write's side effect on an I/O register). 7. **C4**: implement the `(d,x)` emulation-mode quirk; exclude the corpus's contrary cases, counted. Optionally report upstream. 8. **U9**: not in the core until a board rung or hardware probe needs it; keep an issue. 9. **ABORT**: implement the input and entry sequence; no rung depends on it. 10. **No interrupt hijacking** inherited from 6502-python's NMOS behaviour.