# Handoff: polish `m6800-python` into a publishable reference core Written 2026-09-18 after a full review of the core against z80-python (the reference this family of cores follows). The core and its tooling are already at z80-python's level; this brief lists what is *not* yet there, in the order to do it, each item with an acceptance test. Do the items in order. Items 1-6 are the job; 7 and 8 are stretch goals, only after 1-6 are green. ## Context you are inheriting - Repository: `/data/emu/m6800-python`, local git only, no remote, 31 commits all dated 2026-09-18, HEAD `aa2ae4d`. Clean tree. - Venvs: `.venv` (CPython 3.14.4), `.venv-pypy` (PyPy 3.11); ruff at `~/.local/bin/ruff`. The package is **not** pip-installed in `.venv`; tests run through `pythonpath = ["src", "tests"]` in `pyproject.toml`. - Baseline, verified 2026-09-18: `python -m pytest -q` → 917 passed, 12 deselected, 8 s; `ruff check .` and `ruff format --check .` clean; `python -m pytest -m slow` replays the MAME traces and the Williams board (about a minute; needs the gitignored `mame-work/` traces and the ROM path named in README). - Reference project to copy shapes from: `/data/emu/z80-python` (public, `alewman/z80-python`). Read its `.github/workflows/ci.yml`, `.github/workflows/oracles.yml`, `CONTRIBUTING.md`, `docs/api-stability.md`, `CHANGELOG.md`, `src/z80_python/conformance.py`, `docs/conformance.md`, `examples/conformance/`, `tests/test_conformance.py`, `benchmarks/z80_core_benchmark.py`. - Read first, in this repository: `README.md`, `docs/start-here.md` ("The embedding contract"), `docs/validation.md` ("The record so far"), `docs/handoff-brief.md` (the build brief; its constraints still apply), `src/m6800_python/cpu.py`, `_core.py`, `_interrupts.py`, `_undocumented.py`. Measured for the record (this machine, 2026-09-18): the core runs a mixed ALU/indexed/branch loop at 3.1 M instructions/s on CPython 3.14 and 41 M on PyPy 3.11; z80-python's benchmark runs 0.6-1.1 M instructions/s on CPython. ## Constraints (unchanged from the build brief, plus these) - **No semantic change to the core without rerunning rung 2 and rung 3** (`scripts/compare_mame_corpus.py`, `python -m pytest -m slow`) and saying so in the commit message. Items 1a and 1b touch `reset()` and the trap path only; rerun anyway. - Keep the readability test green: one handler per Motorola mnemonic, in its owning module, docstring citing the manual page. - Every new documentary claim cites a page; where you cannot find the page, write `[unverified]`, never a guess. - No runtime dependencies. Everything must pass on PyPy too. - `tests/datasheet.py` is generated; never edit it by hand. - One commit per item, authored as alewman, with the Co-Authored-By line the session gives you. **Do not push or create a GitHub repository unless the session prompt says to.** Item 3 ends with the repository *ready* to push. - Do not commit anything from `reference/`, `third_party/`, `mame-work/`, `tests/vectors/`, `*.trace`. ## Item 1 — the nits found by probing (about an hour) **1a. `reset()` must clear the opcode history.** `_core.py:53-56` says that after reset nothing is known and an odd opcode is assumed so that a `CLI` first thing keeps its one-instruction delay; but `reset()` in `_interrupts.py:42` leaves `_opcode`/`_previous_opcode` as they were, so a `CLI` right after a reset that followed an *even* opcode takes a pending IRQ at once. Fix: `reset()` sets both to `0x01`. Acceptance: a test in `tests/test_interrupts.py` that runs `LDAA #0` (opcode `$86`, even), calls `reset()`, points PC at `CLI; NOP` with `irq` held, and sees the IRQ taken *after* the NOP (a `step()` returning 2, then 12). Update `docs/cpu-state.md` if it describes reset. **1b. The strict trap must leave the state unchanged.** `_undocumented.py:8` promises "the CPU state unchanged, PC still pointing at the opcode", but `step()` has already shifted `_previous_opcode`/`_opcode` when `_trap` (`_undocumented.py:99`) raises, so `capture_state()` differs in `opcode`. Fix inside `_trap` (restore both fields; they are on `self`). Acceptance: a test that `capture_state()` before the step equals `capture_state()` after the `UndocumentedOpcode`, on both parts. **1c. Doc drift on `irq2`.** `docs/start-here.md:398` still says the core "will expose an interrupt-request input per vector". The built contract is one `irq2` attribute holding the highest-priority pending vector or `None` (`cpu.py`, class `M6803`). Rewrite that sentence to describe what exists and point at the embedding-contract section. **1d. Say why omitting the dummy reads is safe.** `docs/start-here.md:548` and `docs/validation.md:364` say the MC6800's dummy reads ("Irrelevant Data", MCSDD Table 8) are not modelled, and nothing in `docs/` mentions **VMA**. The reason a host with a 6821 PIA (whose reads have side effects) can trust the model is that the MC6800 drives VMA low during those cycles so peripherals must ignore them. Find the statement in the MC6800 data sheet inside `reference/` MCSDD (`pdftotext -layout`; the VMA pin description and Table 8's VMA column) and add a short paragraph to `docs/timing.md` under "The cycle model", citing the printed page. If a 6801/6803 host needs the equivalent statement, M6801RM's bus-timing section has it; cite or mark `[unverified]`. **1e. The example host is exercised by nothing.** `examples/minimal_host.py` fails with `ModuleNotFoundError` in `.venv` because the package is not installed. Add `tests/test_example_host.py` that imports the module and runs `main()` with stdout captured, asserting the four lines it prints (see the current output: `LDAA #$2A A=2A +2 cycles` … `$2000 = $2B`). CI (item 3) also runs it after an editable install. ## Item 2 — package hygiene (half a day) - `src/m6800_python/py.typed` (empty), and make sure hatch ships it (`[tool.hatch.build.targets.wheel]` already packages the directory; verify with `python -m build --wheel` and `unzip -l`). - `pyproject.toml`: add `[project.urls]` (Homepage, Changelog, Issues, pointing at `https://github.com/alewman/m6800-python`), classifiers (Python 3.12-3.14, PyPy, MIT, Emulators), keywords. Keep `requires-python = ">=3.12"` and version `0.1.0`. - `CHANGELOG.md` in Keep-a-Changelog form: one `0.1.0` entry summarising the seven rungs and the tooling, dated 2026-09-18, then `[Unreleased]` for this polish. Copy z80-python's preamble wording about semantic versioning. - `CONTRIBUTING.md`: z80-python's five rules, adapted: semantic-core changes rerun `scripts/compare_mame_corpus.py` and `pytest -m slow`; never commit vectors, traces, ROMs, `reference/`, `third_party/`. - `SECURITY.md`: copy z80-python's. - `docs/api-stability.md`: the supported surface is exactly `__all__` in `src/m6800_python/__init__.py` (list it by group: CPU classes and flag constants; `CPUState`; disassembly; `DebugSession` and its values; `CommandDebugger`; traces; and, after item 4, `m6800_python.conformance`). Same compatibility policy as z80-python's page. Say plainly that `undocumented="measured"` cycle counts marked `[unverified]` may change. - `docs/README.md`: add the new pages and `benchmarks/`. - Acceptance: `python -m build --wheel --sdist` in a fresh venv, `pip install dist/*.whl`, then from `/tmp` run the smoke test in item 3; `unzip -l` shows `py.typed`. ## Item 3 — CI, and a repository ready to publish (half a day) Copy z80-python's two workflows and adapt: - `.github/workflows/ci.yml`: matrix `3.12`, `3.13`, `3.14`, `pypy-3.11`; steps: `pip install -e ".[dev]"`, `python -m pytest -q`, `ruff check .`, `ruff format --check .`, `python examples/minimal_host.py`. A `package` job builds the wheel and sdist, installs the wheel, and smoke-tests the installed API from `runner.temp` with this program: ```python from m6800_python import M6800, CPUState, DebugSession, disassemble_bytes memory = bytearray(0x10000) memory[0xFFFE:0x10000] = b"\x10\x00" memory[0x1000:0x1002] = bytes((0x86, 0x2A)) cpu = M6800(memory.__getitem__, memory.__setitem__) cpu.reset() assert cpu.capture_state() == CPUState(pc=0x1000) assert disassemble_bytes(memory[0x1000:0x1002]).text == "LDAA #$2A" record = DebugSession(cpu, peek_byte=memory.__getitem__).step() assert (record.after.a, record.cycles) == (0x2A, 2) ``` (Check `CPUState(pc=0x1000)` really is the post-reset state: `cc` defaults to `0xD0`, everything else zero. Adjust if not.) - `.github/workflows/oracles.yml`: weekly and on dispatch. Steps: `scripts/fetch_mame_source.py`, then `scripts/mame_corpus.py generate` (read that script for the compiler it needs; `g++` is on `ubuntu-latest`), then `python -m pytest tests/test_mame_corpus.py -q`. Cache `tests/vectors/` keyed on the MAME source hashes in `docs/validation.md`. Leave out, with a comment saying why, the same way z80-python's file does: the trace replays and the Williams board (need ROMs; certified locally and recorded in `docs/validation.md`), and the n6800/sim68xx cross-checks (need Python 3.9 + amaranth via `uv`, and a C build). - README: add the two badges and a "CI coverage" table in z80-python's style saying which rungs each badge covers and which are local-only. - You cannot run GitHub Actions locally; the acceptance is that every command in both workflow files runs green in a **fresh** venv on CPython 3.12 (the oldest supported) and on `.venv-pypy`, and that `python -c "import yaml, sys; yaml.safe_load(open(sys.argv[1]))" FILE` accepts both files (install PyYAML into a scratch venv for that, not into the project). - End state: `git status` clean, everything committed, `git remote` still empty. If the session prompt says to publish: `gh repo create alewman/m6800-python --public --source . --push`, then confirm both badges go green, then tag `v0.1.0`. ## Item 4 — the conformance kit (two days; the point of a "reference core") Port `z80_python.conformance` to `src/m6800_python/conformance.py`, with `docs/conformance.md`, `examples/conformance/`, and `tests/test_conformance.py`. This is what lets a Rust or C port prove it is the same CPU; z80-rust was certified this way. Keep z80-python's names and shapes where they fit (`MemorySegment`, `Event`, `StopRule`, `Manifest`, `ConformanceHost`, `TraceRun`, `trace_manifest`, `write_checkpoints`, `diff_manifest`, `manifest_to_dict`/`manifest_from_dict`/`load_manifest`, and a `main` with `trace`, `diff`, `checkpoints` subcommands run as `python -m m6800_python.conformance`). What changes for this family: - Manifest gains `part` (`"6800"` or `"6803"`) and `undocumented` (`"strict"`, `"measured"`, `"mame"`), both mandatory. - One host profile, `flat`: 64 KiB RAM, no ports. No `cpm-minimal`; there is no CP/M here. `stop` keeps `max_steps` (mandatory), `at_pc`, and replaces `on_halt` with `on_wait` (stop before a `WAIT_IDLE` boundary when nothing is pending and no event remains) and `on_hcf` (stop before an `HCF_IDLE` boundary). - Events, applied immediately before the boundary numbered `at_step`: `irq`, `irq_clear`, `nmi` (sets the level; the core edge-detects), `nmi_clear`, `pulse_nmi`, `irq2` with `vector` (6803 only; reject on a 6800 manifest), `irq2_clear`, `reset` (calls `reset()`; there is no reset line to hold). - What must match at every boundary: the `BoundaryKind`, the cycle count, the instruction's address and bytes when it is one, and **all fifteen `CPUState` fields** before and after, `opcode`/`previous_opcode`, `irq_inhibit`, `nmi_previous`, `waiting`, `halted` included. Say in `docs/conformance.md` that a port matching registers but not `irq_inhibit` is not equivalent, as z80-python says of `wz`. - An `UndocumentedOpcode` under `strict` ends the run with a distinct stop reason recorded in the trace; it is not an error in the kit. - Trace format: `docs/trace-schema.md` as it stands (schema version 1); a port omits `mnemonic`/`operands` and the reader fills them in from `disasm.py`. Fixtures to ship in `examples/conformance/` (manifest + reference `.jsonl` each, all small, all regenerated by the test), one per decision the core made where a port is likeliest to differ: 1. `flags-and-branches` — every branch both ways, `CBA`/`SBA`, `NEG` of `$80` and `$00`, `COM`, shifts through C. 2. `daa` — the nine table rows, including `$99+$99` (C sticky). 3. `cpx-6800` and `cpx-6803` — the same operands; N/V from the high byte with C untouched on the 6800, a true 16-bit compare on the 6803. 4. `interrupts/cli-after-odd-opcode` and `cli-after-even-opcode` (MC6800: the delay depends on the previous opcode's bit 0, APPS Q15), and `cli-on-6803-always-delays`. 5. `interrupts/tap-delays-even-when-repeated`, `sei-is-not-delayed`. 6. `interrupts/wai-then-irq` (9 cycles, idle boundaries, then a 4-cycle exit without a second push), `wai-with-i-set-takes-nmi-only`. 7. `interrupts/nmi-outranks-irq`, `nmi-is-edge-triggered`, `rti-takes-pending-irq-at-once`, `irq-entry-costs-12-and-pushes-seven`. 8. `interrupts/irq2-priority` on the 6803: `irq` outranks `irq2`; the vector given is the one taken. 9. `undocumented-measured` — `$14`, `$15`, `$87`, `$CF` under `measured`; `hcf-halts` — `$9D` then `HCF_IDLE` boundaries until a `reset` event. 10. `stack-frames` — `SWI`, `JSR` all three modes, `BSR`, `PSHX`/`PULX`, `TSX`/`TXS` off-by-one. Tests: each fixture's reference trace regenerates byte-identical from its manifest; a perturbed copy of one trace (flip one `cc` bit at record N) makes `diff_manifest` report position N and the field; the CLI round-trips `trace` → `diff` clean; a 6800 manifest with an `irq2` event is rejected with a message naming the event. Add `conformance` to `docs/api-stability.md` and `docs/README.md`, and a paragraph to README under "Reading and stepping through code". ## Item 5 — turn the n6800 bus-order agreement into a certified claim (a day) z80-python now certifies every instruction's memory transactions against pin traces (its commit `a463f51`). The nearest thing this family has is `scripts/crosscheck/n6800.py`, which showed 173 of 197 MC6800 opcodes agreeing with the n6800 RTL model on registers, cycles **and bus order**, but only as a script run once. Make it durable and cheap: - Extend `scripts/crosscheck/n6800.py` with `--export FILE` that writes, for each of the 173 agreeing opcodes, a handful (say 4) of the corpus cases as `{opcode, before: CPUState fields, memory patches, expected accesses: [["r"|"w", address, value], ...], cycles}` — the core's own access log format from `tests/conftest.py`'s `Bus`. Keep it under ~200 KB. Commit it as `tests/fixtures/n6800_bus_order.json`. It is generated data about the core's own random states, not n6800 code; still, record the n6800 commit (`f117162`, GPL-3.0) and the generation command in the file's header and in `docs/validation.md`. - `tests/test_bus_order.py`: replay every fixture case through `M6800` with the logging `Bus` and assert the access sequence and cycle count. Fast, no third-party install. Note in the test docstring that the 24 opcodes not in the fixture are the ones where the manual sides with the core against n6800 (`docs/validation.md`, rung 5), and list them. - `docs/validation.md`: promote rung 5's n6800 line to a certified claim with the fixture name and the count of opcodes and cases; add a sentence that the dummy (VMA-low) cycles are excluded and why (item 1d). - If `third_party/n6800` is not present, the environment notes in `docs/validation.md` say how it was installed (`uv` inside `.venv` gives a Python 3.9 with amaranth 0.3). Do not add it to CI. ## Item 6 — a benchmark harness (half a day) `benchmarks/m6800_core_benchmark.py` modelled on z80-python's: a flat-memory host, four deterministic workloads (`alu_loop`: the loop in this brief's opening paragraph; `indexed_memory`: `LDAA/STAA ,X` with `INX`/`CPX`; `stack_calls`: `JSR`/`RTS`/`PSHA`/`PULA`; `interrupts`: a `WAI` loop with `irq` toggled by the host every step), `--instructions`, `--repeats`, `--warmup-instructions`, `--json`, median and per-sample times, instructions/s and cycles/s, platform line. `tests/test_benchmark.py` runs each workload for a few thousand instructions and checks the JSON shape. Record the numbers from this machine for CPython 3.14 and PyPy 3.11 in a short "Speed" table in README (replacing the sentence there now) and in `docs/validation.md`. ## Stretch 7 — a 6803 host with the on-chip timer Only after 1-6. The Williams board (`scripts/williams_board.py`) is the only real host, and it is a 6808: nothing exercises `irq2` outside unit tests. Knuckle Joe's sound CPU is an MC6803 whose ROM uses the timer; its trace is in `mame-work/kncljoe/` and `scripts/replay_trace.py kncljoe` already replays it with the interrupts *taken from the trace*. Build `scripts/m6803_board.py` with the free-running counter, output-compare and overflow flags and TCSR (M6801RM §4, cite the register map page), driven from the core's returned cycles, raising `irq2` itself; acceptance is that the replay agrees with MAME's trace with the interrupt entries generated by the board, not read from the trace. Then a `williams_debug.py`-style debugger over it. ## Stretch 8 — a self-checking 6800 functional test program The one move that can raise this family's evidence ceiling without a chip: write `validation/functional_test.asm` (MIT), in the spirit of Klaus Dormann's 6502 test, covering every documented opcode of the MC6800 with expected flags, each failure landing at its own address, success at a known PC with a known value in A. First check what assembler is installed (`asl`, `vasm6800_std`, `a68`; if none, write the test with the project's own small assembler in `scripts/`, since the instruction table is already in `tests/datasheet.py`). Acceptance: it passes under the core (both parts), under sim68xx and under n6800 (`scripts/crosscheck/`), and a `README` section invites owners of MEK6800D2 / SWTPC / Altair 680 boards to run the binary and report, which would give this family its first hardware-corrected oracle. ## Known gotchas, from the build session - MAME: the installed binary is 0.285; the source tree at `~/mame-master` is 0.261 and its `CLI`/`TAP` code differs. Cite only the pinned `reference/mame0285/` files. MAME has *two* 6800-family handler tables; check both before saying MAME is wrong. - Lua taps in `scripts/*.lua` must be held in globals or they are garbage collected. `error.log` lands in the cwd. - ROMs are read in place from the path in README; never copy them. - The `-m slow` replays need `mame-work/*/*.trace`, which are gitignored; `scripts/replay_trace.py GAME` with no trace prints the MAME command that records one. - `test_readability.py` parses the source with `ast`: a new `_op_` method with a docstring that does not read `MNEMONIC -- ... (M68PRM p. A-nn)` fails it. ## What done looks like - Items 1-6 each landed as one commit; fast suite, `-m slow`, ruff check and format, on CPython 3.14 and PyPy, all green; rung 2 and rung 3 rerun after item 1 with the same counts as `docs/validation.md` records. - A fresh clone in a fresh venv can `pip install -e ".[dev]"`, run the suite, run the example, build a wheel, and run the conformance CLI on every fixture. - `docs/validation.md` "The record so far" and README's rung table updated; `CHANGELOG.md` `[Unreleased]` lists every item. - `git remote` empty unless told otherwise; if published, both badges green and `v0.1.0` tagged.