# Handoff: build `65c02-python`, the CMOS 65C02 core > **Built 2026-11-12.** Rungs 0 to 8 are passed; `docs/build-progress.md` has > their numbers, the traps and what is left (rung 9, with `lynx-python`). This > brief is kept as the specification the build worked from. Two things in it > were overtaken by the build and are marked where they stand: the dummy-read > addresses are the captures', not SingleStepTests' ("The contract as built", > and docs/timing.md), and the capture replay is a test harness, not part of > `w65c02_python.harness`. ## Context you are inheriting The family's shape is **chips are cores, boards compose cores**. Each core is certified alone against its oracles and pinned by commit by the boards that use it. This core's first user is `lynx-python` (`../lynx-python` beside this repository, Phase 0 done in parallel; do not edit it). Later users could be Apple IIe/IIc-class boards, a BBC Master, arcade boards. A board that finds a corner of this core raises it **here** (an issue or a PR; re-certification is fine), never as a workaround in the board. Rules that bind the work: oracle tiers (validation.md; an emulator is a detector, never a judge; state the tier of every claim); Python floor 3.11, CPython and PyPy both green; reference cores are correct, not fast; modern over compat; no dangerous-looking shell one-liners; local git only until the user says otherwise; no GPL logic in the repository (GPL programs are run, their sources read for facts); never copy a chip file between repositories; no hardware will be bought; run any Python that reads `reference/` with `-I`. ### Read, in this order, before writing code 1. `README.md`, then `docs/start-here.md` (the rows and their evidence). 2. `docs/timing.md` (every bus cycle; the measured tables). 3. `docs/undocumented-behavior.md` (U1-U13, C1-C12). 4. `docs/validation.md` (oracles, what ran, the rungs). 5. `docs/mame-oracle.md`. 6. `6502-python` at **`origin/main` = `741419a`**: `src/sixfiveohtwo/frame.py` (all of it), `docs/api-stability.md`, `tests/test_frame.py`, `tests/test_tooling_hooks.py`. The local `main` branch of `../6502-python` is stale (`b5387f6`); use `git show origin/main:`. 7. `../65816-python/src/w65c816/` (`cpu.py`, `_core.py`, `_control.py` for `WAI`/`STP` in `_halted`, `harness.py`) and `../huc6280-python/src/huc6280/` as worked examples of frame subclasses with reused tooling. 8. `../lynx-python/docs/handoff-brief.md` and `start-here.md`, "What the board needs from `65c02-python`". Then `python -I scripts/fetch_references.py` (about 2 GB, mostly the corpus and captures), `python -I scripts/build_tools.py`, and run `survey_sst.py`, `decode_capture.py master reset --show 12` and `mame_trace.py bbcm` to see the data. ## Where the 65C02 lives (open decision 1; laid out, not decided) Facts measured in the siblings: - `CPUFrame` (347 lines) gives the bus callables, the request API, the poll, `note_stall` and `step()`'s skeleton. Two cores already subclass it from their own repositories: `65816-python` and `huc6280-python`. - PR #9 ("tooling-hooks") **is merged** (GitHub `main` = `741419a`, 2026-10-23): `StepRecord`, `DebugSession`, `read_trace`, `CommandDebugger` are subclassing surfaces. **The plan does not depend on an open PR.** There is no release containing the frame yet (`0.2.0.dev0`), so dependants pin a commit. - `MOS6502`'s handler mixins (`_alu`, `_loads`, `_shifts`, `_control`, `_core`'s `_ea_*`) are declared implementation details (`docs/api-stability.md`): another repository may not import them. - `huc6280-python` is a 65C02 superset in *semantics* only. Its handlers are written against its own cycle helpers (`_io()`, `ZERO_PAGE | zp`, a 21-bit mapper): `LDA zp` is 4 cycles there, read-modify-write is read, internal, write; `TSB`/`TRB` take Z from the stored result, decimal leaves V alone, `BIT #` sets N and V. Its rung 1b passes 2,089,891 Rockwell cases on **results only**, with cycles and bus not compared and five masks. What it holds of a 65C02 that is not welded to its bus: the opcode-to-mnemonic map of the 209 shared opcodes (`tests/rockwell.py`, `R65C02`), the bit-number decoding (`_bits.py`, three lines), and two decimal digit-adjust formulas whose *accumulator* results its issue 0004 found equal to the 65C02's. ### Option (a): this repository on `CPUFrame`, its own handlers, rows as data As `65816-python` and `huc6280-python`. `W65C02S(CPUFrame)` etc.; handlers written here against timing.md; tooling by subclassing 6502-python's. - Cost: about the size of `huc6280-python`'s `src/` (3,000 lines with tooling). The documented NMOS instructions are written a third time in the family (their bus cycles differ from both siblings: the page-cross re-read, read-modify-write, the decimal cycle). - Requires of siblings: nothing to start. Requests R1-R3 below are small. - Risk: none to the NMOS boards (NES, 2600, 5200, 7800), whose pins of `6502-python` do not move. ### Option (b): a CMOS class inside `6502-python` `class W65C02(...)` beside `MOS6502` and `RP2A03`, reusing the private mixins legitimately and overriding `_indexed`, the read-modify-write handlers, the ALU's decimal branch, `BRK`, `JMP`, and the table. - Saves: perhaps 600 lines of unchanged handlers (loads, stores, transfers, compares, flags, stack, `JSR`/`RTS`/`RTI`, branches). - Cost: the NMOS hot path gains hook points it does not need (a dummy write that is sometimes a read, a decimal cycle, a poll rule for one-cycle NOPs); `6502-python`'s claims (die-backed poll timing, AccuracyCoin through the NES board) would sit beside a part whose poll timing is U5; every board pinning `6502-python` re-pins for changes that are not theirs; `6502-rust` and its `-fast` fork transcribe `741419a` and would have to follow or diverge; three rows of variant data, three corpora and 250 MB of captures join that repository's test suite. - Requires of `6502-python`: all of the above as PRs there. The `huc6280-python` brief already left "the Lynx's 65C02 mode to its own plan", and this batch was set up with a separate repository. ### Option (c): this repository becomes the CMOS base; `huc6280-python` is rebased onto it The family rule is extract on the second consumer, never copy a chip file. The Lynx makes the 65C02 a second consumer of "CMOS 6502 semantics". - What could really be shared: pure functions and data only: the decimal accumulator results (not the flags), `TSB`/`TRB`/`RMB`/`SMB` result arithmetic (one line each), the mnemonic table of the 209 shared opcodes for the disassemblers. No handler: every HuC6280 handler makes different cycles at different addresses. - Cost: `HuC6280(W65C02S)` would override every addressing helper and nearly every handler, inheriting names and little else; or the base's handlers would be written through hooks (`_zp()`, `_internal()`) until neither chip reads plainly, against the readability contract. `huc6280-python` is certified (rungs 0-5) and pinned by the PC Engine boards; a rebase re-certifies all of it for no behavioural gain. - Requires of `huc6280-python`: a rebase PR, re-run of its seven rungs, a re-pin in each board that uses it. - The same question was put for the ALU in that brief ("a third flavour is a third function, not a shared one") and decided that way by the user on 2026-10-23. ### Recommendation **(a)**, with a narrow form of (c) held open: this core keeps its pure pieces pure and public-shaped (`w65c02_python._alu.decimal_add`/`decimal_subtract` returning the accumulator and carry; the opcode table as data), so that if `huc6280-python` or a later 65CE02/R65C19 core wants them they are imported, never copied. Nothing is extracted now. Is the rule broken? Judged no: nothing in `huc6280-python` would be copied here; the 65C02's `_bits.py` has different cycles and a different Z rule, so it is another chip's file. ### Requests to sibling repositories (not made; this repository changes nothing there) - **R1, `6502-python` (documentation and one test):** say in `note_stall`'s docstring and `docs/start-here.md` that a CMOS part's host may call it from a **write** callback (RDY stops the 65C02 on write cycles, DS Table 7-1), and add that case to `tests/test_frame.py`. The method already works there: it does not look at the access kind. - **R2, `6502-python` (optional):** tag a release that contains the frame and the tooling hooks, so three dependants can pin a version instead of `741419a`. - **R3, `6502-python` (optional):** list `NO_POLL` assignment by a subclass handler (`self._polled = NO_POLL`) as a supported use in `docs/api-stability.md`; the one-cycle NOPs need it (the names are already public there; the use is not written down). - **R4, `huc6280-python` (optional, after this core's rung 3):** compare its two decimal formulas with this core's over all 131,072 inputs each. Its issue 0004 would gain a tier-1-backed 65C02 reference (CAP ran Clark's test on two real 65C02s); the HuC6280 itself stays unjudged. - **R5, `lynx-python`:** use the contract below; pick rows as in open decision 3. ## The bus contract ```python cpu = G65SC02(read_byte, write_byte) # or R65C02, W65C02S, Lynx2Cell # read_byte(address) -> int every read cycle, dummy reads included # write_byte(address, value) every write cycle cycles = cpu.step() # == number of callbacks made ``` - Every cycle is exactly one callback, in the chip's order. There is no `idle` callback: a 65C02 reads or writes in every cycle, and on the Lynx every one of them costs ticks. - **The core keeps no time.** A board advances its devices inside the callbacks; `step()`'s return is a count, for traces and tests. - Inside a callback the host may read: - `cpu.sync`: True during the opcode fetch (the chip's SYNC pin), else False; - `cpu.fetch`: True for every read of the instruction stream at PC (opcode **and operand bytes**), False for data, stack, vector and dummy accesses that are not at PC; - `cpu.opcode`: the opcode of the instruction in progress. These are plain attributes set by the fetch helpers (two stores per fetch). - `step()` runs one instruction, one interrupt entry, one reset, or one cycle of `WAI`/`STP` waiting (a read of the next opcode's address). - Interrupts: `CPUFrame`'s API unchanged. `request_maskable_interrupt()` / `clear_maskable_interrupt()` are a level; NMI an edge; `request_reset()`. - A callback may take as long as the host likes, and may change interrupt requests. If it holds the CPU (RDY, a bus grant to another chip) it calls `cpu.note_stall()` as the hold begins and after each held cycle, in a read **or a write** callback (R1). - Row settings are class attributes, so a board can make its own row: `bit_instructions`, `wai_stp`, `reset_writes_stack`, and the defaults of the U entries (`one_cycle_nops_poll = False`, `nop_5c_reads`, ...). - Plain integers in the hot path, no generators: a `-rust` fork transcribes it. - PyPy: keep each instance under 80 attributes (the family's PyPy rule). ### The contract as built (2026-11-12) The build kept the contract above. What it pinned down, for a board that pins this core: - **Classes** (`from w65c02_python import ...`): `W65C02S`, `R65C02`, `G65SC02` (the Lynx I's cell) and `Lynx2Cell` (the Lynx II's cell: the `G65SC02` row with `bit_instructions` on), all subclasses of `CMOS65C02`. Constructor: `Row(read_byte, write_byte)`. `CPUState` is the snapshot type (`capture_state()` / `restore_state()`). - **Row attributes**, set on a subclass (the opcode table is built once per class, so assigning them on an instance has no effect): `bit_instructions`, `wai_stp`, `reset_writes_stack`, `one_cycle_nops_poll` (False), `nop_5c_reads` (`"ff_page"` or `"pc"`), `nop_dc_fc_reads` (`"absolute"` or `"operand"`). - **`cpu.sync`**: True in the callback of an opcode fetch, and of the first cycle of an interrupt entry and of reset (the chip fetches an opcode there with SYNC high and drops it: captured). False in every other callback. - **`cpu.fetch`**: True in the callback of every read whose address is the program counter: the opcode fetch; each operand byte; the read a one-byte instruction makes of the byte after it and drops; a taken branch's read of the next opcode's address (twice across a page); the decimal cycle of `ADC` and `SBC` (it reads the next opcode's address); `RTS`'s last cycle; both reads at PC of an interrupt entry and of reset; each waiting cycle of `WAI` and `STP`. False for data, stack and vector accesses, for every write, and for the cycles that read an instruction byte a second time (`zp,X`, `(zp,X)`, a page crossing, the indirect jumps): there the program counter has already moved on. Which of these Mikey shortens in page mode is the board's rule; `cpu.sync` and `cpu.opcode` are there to refine it. - **`cpu.opcode`**: the opcode of the instruction in progress, from its second cycle on. In the opcode fetch's own callback it still holds the previous instruction's; an interrupt entry and reset leave it unchanged. - **`step()`** returns the number of callbacks it made: 1 to 8 for an instruction, 7 for an interrupt entry or reset, 1 for a waiting cycle of `WAI` or `STP`. `cpu.halted` is True while waiting or stopped (`cpu.waiting`, `cpu.stopped`). - **Dummy reads are not where SingleStepTests has them.** The captures of two real parts decide (timing.md): a board that maps hardware in page zero, or whose devices react to reads, sees the operand byte re-read in `zp,X` and `(zp,X)`, the pointer's high byte re-read in `(zp),Y`, and an indexed store that does not cross a page reading its target address before writing it. On the Lynx the last matters: `STA $FD00,X` reads the hardware register it is about to write. - **Reset on both Lynx rows writes three bytes to the stack** (PCH, PCL, P) at whatever S holds (U2). - **Tooling**: `w65c02_python.debug.W65C02Session` (its tracked accesses are `"rs"` an opcode fetch, `"rf"` another read at PC, `"r"`, `"w"`), `w65c02_python.trace`, `w65c02_python.console.W65C02Debugger`, `w65c02_python.disasm.disassemble(reader, address, row)`. A session accepts a board object with `step()`, `capture_state()` and `cpu`. ### The Lynx's requests, one by one From `lynx-python/docs/handoff-brief.md` ("From `65c02-python`") and its `start-here.md`: | Lynx request | Given by `CPUFrame` today? | What this core adds | | --- | --- | --- | | 1. A callback for every cycle in chip order, dummy cycles included | the frame gives the two callables and their replacement; the per-cycle order is each core's handlers | the handlers (timing.md) | | 1b. Tell an instruction-byte fetch (opcode and operands) from a data access, for 4-tick page mode against 5 | **no**: the frame's callbacks are `read_byte(address)` and `write_byte(address, value)` with no kind | `cpu.fetch` and `cpu.sync`, readable in the callback. Not a third callable and not a `kind` argument: the signature stays the family's, the debugger's bus wrapping keeps working, and hosts that do not care pay nothing. Which fetches Mikey really shortens (its "decode the current op-code" rule, MAPCTL bit 7, the measured pattern in `lynx-python`'s page-mode capture) is the board's; `cpu.opcode` is there for it | | 2. No time in the core; the board charges ticks in the callback | **yes** | nothing | | 3. The callback may take arbitrarily long (Suzy draws inside the `CPUSLEEP` write) | **yes**: nothing in the frame times a callback. For interrupts raised during the hold to be polled as the chip would, the board calls `note_stall()` in that write callback | R1 (documentation); a directed test in rung 6 | | 4. Rows for Lynx I and Lynx II; `WAI`/`STP` switchable, default off | not the frame's business | rows as class attributes; open decision 3 | | 5. Level-sensitive IRQ; `CLI`/`SEI` delay; D cleared on entry; `BRK` two bytes; `JMP (abs)` fix; the NOPs; one-cycle NOPs and IRQs | **yes** for the level, the `CLI`/`SEI`/`PLP` delay (`_polled_i`) and the no-poll mechanism (`NO_POLL`) | the rest is this core's handlers; one-cycle NOPs set `NO_POLL` | | 6. Reset as 7 cycles reading the vector through the callback | the frame calls `_accept_reset()` | 7 cycles (CAP). Note the three stack cycles are **writes** on the `G65SC02` row: the Lynx board will see three writes to page one at reset (U2) | | 7. `lynx-tests` `cpu.lnx` as this core's board-level rung | | rung 9 | `CPUSLEEP` itself needs nothing from the core: it is Mikey's bus request, not `WAI`. The board either holds inside the write callback (its plan) or stops calling `step()`; both work. ## Proposed layout (the build session may refine) `src/w65c02_python/`: `cpu.py` (the classes and their row attributes, `step` hooks, state capture), `_core.py` (registers, fetch helpers that set `sync`/`fetch`, addressing modes cycle by cycle, stack), `_dispatch.py` (one 256-entry base table plus per-row overrides, built once per class; handler, mode, mnemonic, base cycles), `_alu.py` (binary and decimal; BC Appendix A cited line by line), `_loads.py`, `_shifts.py` (read, read, write), `_bits.py` (`TSB TRB RMB SMB BBR BBS`), `_control.py` (branches, jumps, stack, `BRK`, interrupt entry, reset, `WAI`, `STP`), `_nops.py` (each NOP class with its evidence), `state.py`, `disasm.py`, `debug.py`, `trace.py`, `console.py`, `harness.py` (flat-memory host for the test programs, the capture replay), `__main__.py`, `py.typed`. `pyproject.toml` as `huc6280-python`'s, depending on `6502-python @ git+https://github.com/alewman/6502-python@741419a33d1de400a63f7c24c7916bb600694ca2`. One instruction family per module, one mnemonic per handler docstring, the source and tier as a comment on the line that encodes each fact (`# C1: 8 cycles, CAP + DS Table 7-1; SST says 4`). ## Your task Build the core to the rungs in `docs/validation.md`, one rung per commit, in this order: 0, 1, 2, 3, 4, 6, 5, 7, 8. Rung 4 (the capture lockstep) is the one to protect: it is the only tier-1 judge and it decides U4's addresses where the data allows. Keep `docs/` current; every deviation from a source gets a U or C entry with its tier. Rung 9 is run with `lynx-python`. ### Tooling at the family bar `state.py` (`CPUState`: `a x y s pc p`, `waiting`, `stopped`, the frame's poll fields), `disasm.py` (per row: the same byte disassembles differently on `G65SC02` and `R65C02`), `debug.py`, `trace.py` (JSONL, the family schema), `console.py`, `python -m w65c02_python IMAGE --row g65sc02 [--max-cycles N] [--trace out.jsonl]`. All by subclassing `6502-python`'s `StepRecord`, `DebugSession` and `CommandDebugger` through the merged hooks, as `65816-python` and `huc6280-python` do; no parallel modules. `halted_kinds` gains `wai` and `stp`. ### Smoke list (the quick loop; the full rungs only at commit points) 1. SST, the first 100 cases of each of 768 files (about 77,000 cases). 2. Dormann's `sc` image to `$2434`, and the decimal test. 3. The Master's `reset` capture replayed (5 MB, a boot's worth of instructions, includes interrupts and the reset writes). 4. The directed tests of rung 6. 5. The tooling tests. ## Decided by the user Nothing yet: this Phase 0 is new. ## Open decisions for Aubrey > **Decided 2026-11-12.** Aubrey answered "yes to all the recommendations". > For every item below, the option marked as recommended is now the decision. > The options are kept as written, as the record of what was asked. 1. **Where the 65C02 lives.** (a) this repository on `CPUFrame` with its own handlers; (b) a class inside `6502-python`; (c) this repository as the CMOS base with `huc6280-python` rebased onto it. **Recommend (a)**, with pure helpers kept importable so (c) can happen piecemeal if a consumer asks. 2. **Names.** Distribution `65c02-python`; an import name cannot start with a digit. Options: `w65c02` (matches `w65c816`; the design is WDC's, licensed to every maker here), `sixfivecohtwo` (matches `sixfiveohtwo`; hard to read), `cmos6502`. Classes named by part: `W65C02S`, `R65C02`, `G65SC02`. **Recommend `w65c02` and those three classes.** (Renamed on 2026-11-12: the repository and distribution are `w65c02-python` and the package is `w65c02_python`, the family rule that `x-python` imports as `x_python`. The class names did not change.) 3. **The Lynx rows.** Lynx I = `G65SC02`. Lynx II executes the bit instructions (C12) and nothing else about its cell is known. Options: (i) the board uses `R65C02` for the Lynx II (reset reads the stack); (ii) this core ships a fourth class for the later Lynx cell = `G65SC02` with `bit_instructions = True` (reset writes), named for what it is, e.g. `VL65NC02B`; (iii) the board defines that subclass itself. **Recommend (ii)** under a plain descriptive name (`Lynx2Cell` is honest; no part number is known), so the core's rungs cover the combination; `WAI`/`STP` off on both. 4. **How rung 1 treats the corpus where a higher tier contradicts it** (C1, C2, C3, C10: 30,000 + 320,000 + 40,000 + 60,000 cases). Options: count them as named known disagreements (recommended); or add a `corpus` compatibility row that reproduces the generator so that every case passes. **Recommend counting**: a row that exists to agree with an emulator is the detector judging. 5. **Defaults where no judge decides** (validation.md, "What no judge decides"): W65C02S reset reads the stack (U1); `$CB`/`$DB` are one-byte, one-cycle NOPs outside the W65C02S (U3); the frame's poll rule with no branch exception (U5); `WAI` wakes at the next step (U6); one-cycle NOPs do not poll (U7); `$5C` reads `$FFxx` then `$FFFF` (U9); `$DC`/`$FC` read the absolute address (C10); dummy addresses as SST until rung 4 says otherwise (U4). **Recommend: adopt, each a named class attribute.** 6. **The capture lockstep as a rung** (rung 4): it needs 250 MB of captures in `reference/` and a replay harness of perhaps 200 lines. **Recommend yes**; it is the only hardware-captured judge any 65xx core in the family has. 7. **More rows now or later**: an "old WDC/NCR/Synertek" row for Apple IIc/IIe boards (U8), `R65C102`/`G65SC102` (same instruction sets, different pins). **Recommend later**, when a board needs one and brings evidence. 8. **Ask upstream for missing evidence?** A W65C02S reset capture (U1) and a run of Dormann's `wdc_op = 0` build on real non-WDC parts (U3) would close two unknowns; David Banks and George Foot have the rigs. That means posting outside this machine, under the family's rule that a post names the model. **Recommend: decide after rung 4**, when the list of what the captures could not settle is known. 9. **Public or local.** `65816-python` and `huc6280-python` went public after rung 1. **Recommend the same**: local until rung 1 passes; MIT, no third-party file committed. 10. **Rust and `-fast` forks.** Not now; the Lynx board only needs correct.