# Handoff: build `mb88xx-python`, and hand emu-galaga a real 54xx ## Context you are inheriting `/data/emu/mb88xx-python` holds no core code. It holds the groundwork: the complete programming model of a Fujitsu MB88xx written from the 1987 datasheet and MAME's BSD-3-Clause core, its timing, the five Namco custom chips that are the reason to want it, a validation plan that is honest about there being no hardware corpus for this processor, and a *verified* recipe for pulling a per-instruction trace of a real Namco MCU out of MAME. There is a concrete, already-written-down payoff, and it is why this project exists rather than being an exercise. ### The payoff `/data/emu/emu-galaga` is a finished, deployed Galaga emulator. Three Z80s, video, inputs and sound; it reproduces MAME's per-frame RAM windows and device access streams byte for byte across three reference runs; it runs in a browser at 60.6 fps. It has **one weak point, and it is this processor**. Galaga's two Namco customs are MB88xx MCUs running mask ROMs. emu-galaga runs neither program. Its 51xx is a hand-written model of the coin/credit protocol, fitted to MAME's replies. Its **54xx is a hand-written noise model fitted to MAME's recording** — not to the MCU's output, to the *recording*, because the two did not agree. That project's `docs/build-record.md` calls the 54xx "the day's longest detour", and its `docs/sound-hardware.md` leaves the disagreement open in writing: > Simulating exactly that chain (MAME's `dst_op_amp_filt` coefficients, > rails, mixer, coupling capacitor) on the MCU's recorded output reproduces > neither MAME's level nor its spectrum: the recording peaks at 0.80 of > full scale where that chain cannot exceed 0.23, and two thirds of its > energy lies at 100-300 Hz with no linear relation to the noise bits > (waveform correlation 0.41 for the 450 Hz band, 0.0 for a 167 Hz band, > in both recordings). The cause was not found `[unverified]`. That is the open question. A working MB88xx core does two things to it. First, it removes a variable: with the 54xx's output nibbles *generated* from `54xx.bin` rather than replayed from a MAME capture, any remaining mismatch is MAME's discrete network and nothing else, and the question becomes answerable. Second, and independently of whether the question is ever answered, it replaces two fitted models with two Namco programs: the credit logic, the coin debounce, the lamp blink rate (emu-galaga's is a guess it inherited from MAME's pre-2020 model), the noise LFSR and its envelope all stop being reconstructions. That is milestone 4. Milestones 1-3 are how you earn the right to attempt it. ### Read these first, in this order 1. `docs/start-here.md` — the whole processor: 4-bit A/X/Y, RAM at `(X << 4) + Y`, the 6-bit PC inside a 64-byte page with PA beside it, the ST skip model (**every conditional on this chip is one inverted bit**), the 4-deep stack and the three flag bits it hides, ST/Z/C/V/S/I, all 256 opcodes with cycles and flag effects, the interrupt sequence and its vectors, both timer clocks, the serial port, the output PLA, reset. 2. `docs/timing.md` — six clocks per instruction cycle, 256 kHz on every Namco board, exactly 12 Z80 T-states per MCU cycle, and how to schedule one against the other. 3. `docs/validation.md` — the tier rule, every oracle, and **the four things MAME guesses that a core cannot prove**: the timer prescale (32), the serial prescale (6), the 3-cycle interrupt entry, and the vector addresses. Read this before you believe any number you produce. 4. `docs/mame-oracle.md` — the trace recipe, re-verified on this machine on 2026-09-12, with its numbers and its six gotchas. 5. `docs/namco-customs.md` — which chip is which, ROM hashes, pin wiring, protocols, and which games. 6. The shape to copy: `/data/emu/z80-python` (`docs/start-here.md`, `docs/validation.md`, `src/z80_python/_dispatch.py` for the explicit dispatch, the readability test) and `/data/emu/6502-python/README.md` for the smaller host contract. ## Your task Build a readable, dependency-free Python 3.12+ MB88xx instruction core in this repository, in the shape of z80-python, and take it up the ladder below in order. The end state is not "it passes tests"; it is that `/data/emu/emu-galaga` can run Namco's own programs. The host contract, fixed now so a host can be written in parallel. The core owns A, X, Y, the RAM nibble array, PC/PA, `SP[0..3]`/SI, ST/ZF/CF/VF/SF/IF, PIO, TH/TL and the prescale accumulator, SB, and the pending-interrupt mask. The host owns everything else and supplies: ```text read_k() -> 0..15 K3-K0, input only write_o(value, mask) value 0..255 O7-O0 through the PLA; mask says which nibble moved (0x0f/0xf0/0xff) write_p(value) value 0..15 P3-P0, output only read_r(port) port 0..3 -> 0..15 write_r(port, value) port 0..3 read_si() -> 0|1 ; write_so(bit) serial, MB8841/MB8843 only set_irq(level) ; set_tc(level) ; set_reset(level) ``` `step()` executes one instruction, or accepts one interrupt, and returns its cycle count (1, 2, or 3 for an interrupt entry). Multiply by 6 for clock periods. Variants are constructor arguments — ROM width, RAM width, serial present, PLA mode and optional PLA data — not subclasses with duplicated tables. Two design points that are not negotiable because they are where this processor bites: - **ST is inverted.** `UPDATE_ST_C` sets ST to 0 on a carry; `UPDATE_ST_Z` sets ST to 0 on a zero result; `ZF` is 1 *when the value is zero*. Transcribe the polarity from `docs/start-here.md` mechanically and put it in one place. Every bug you will have in milestone 2 is this. - **`TSTV` and `TSTS` clear the flag they read.** A pure-function test helper will hang a program that polls the timer. ## Milestones, each with its acceptance test, in oracle-tier order ### 1. Skeleton and per-opcode unit tests — tier: documentation The core, the disassembler, and a test per opcode transcribed from the table in `docs/start-here.md` (which is DS Table 5 plus MAME's semantics). Each test asserts the operation, the cycle count, and the ST/ZF/CF effect, and names the table row it encodes. Beyond the 256 opcodes: reset state field by field, the stack word layout (PC in 0-5, PA in 6-10, ST/ZF/CF in 13-15), the interrupt entry sequence and its three vectors, `RTI` versus `RTS`, both timer clock sources and the overflow into VF, the serial shift and SF, and both output-PLA modes including the callback mask. **Acceptance:** every one of the 256 opcodes has a test; the suite passes on CPython 3.12+ and PyPy; a readability test enforces that every handler's docstring starts with its Fujitsu mnemonic. State the count. ### 2. Lockstep against `54xx.bin`, reset through Galaga's boot burst — tier: emulator-derived, a detector Produce a MAME trace with `scripts/mame/trace_mcu.sh 800 out-54xx` — that is `:54xx:mcu`, 800 frames, about 12 seconds and 406,856 instructions on this machine. Run the core on `54xx.bin` (read in place from the MAME ROM set; **never copy it into this repository**) with a host that holds /RESET asserted until the trace's cycle 0 and then delivers the four 06xx chip-select edges at cycles 60,750 / 61,603 / 62,456 / 62,627 minus their 3-cycle entry cost, i.e. at the byte rate of 170.67 cycles that `docs/mame-oracle.md` derives. Emit the same six fields per instruction, **before** executing it — PA, PC, A, Y, the packed flag byte, the running cycle total — and `cmp` against `out-54xx/trace.txt`. Note the shape of the run, because it makes this milestone tractable: the first 60,750 cycles are a closed system. No interrupt, no input, nothing from the host at all. Get *that* identical first, then add the interrupts. **Acceptance, in two parts:** - 2a: identical from cycle 0 to cycle 60,745 — the whole pre-interrupt stretch, about 58,600 instructions, with no host involvement. - 2b: identical through the 12-byte boot burst and out the other side, to at least cycle 100,000. This is where the 3-cycle interrupt entry and the `TSTI` polling loop are proved (the program takes **4** interrupts for **12** bytes; if you get 12, your /IRQ edge model is wrong). Every divergence is decided from the datasheet and recorded, not patched to match. If the datasheet is silent, it goes in `docs/validation.md` beside MAME's other four unprovable points. ### 3. Lockstep against `51xx.bin` through coin and start — tier: emulator-derived, a detector `TRACE_MCU=:51xx:mcu scripts/mame/trace_mcu.sh 2500 out-51xx` gives 6,115,866 instructions across 2,500 frames with **7,140** external interrupts and **no** timer or serial interrupts — the 51xx counts vblank on /TC but polls VF with `TSTV`. The host must therefore drive three things: /RESET from Galaga's LS259 misc latch (released at frame 699), /TC from vblank, and /IRQ from the 06xx slot-0 chip select, with K3 carrying the 06xx R/W line and the command byte split across K0-K2 and R0. **Acceptance:** identical for a stated number of instructions covering at least one coin insertion, one credit, and one start — the run MAME makes when you script those inputs. Report the number and the first divergence if any. This milestone, not milestone 2, is what proves the R-port read-modify-write of `SETR`/`RSTR`, the `TSTD`/`TSTR` paths, the timer, and `OUTP`. ### 4. The payoff: hand emu-galaga a core — tier: behavioural, the judge Two deliverables, in this order. **4a. The 51xx replies.** `/data/emu/emu-galaga/oracle/reference/game-2400` records every byte Galaga's main CPU read from the 06xx window across 2,400 frames of a scripted game with coins, starts, joystick and fire. Drive this core's `51xx.bin` with the same input schedule through the same 06xx line model and produce that byte stream. **Acceptance:** byte-identical to `game-2400`'s 51xx replies over the whole run. Note what this settles: emu-galaga's `src/galaga/n51xx.rs` is a fitted model that already found four places where the real program disagrees with MAME's old hand-written one (switch-mode byte 2 is `0xff` not `0x00`; credit bytes 1-2 are `0xff` until a start is accepted; levels lag one frame and edges two; coins are ignored outside credit mode). A core that runs the program derives all four rather than encoding them, and the lamp blink rate — currently a guess — comes out with them. **4b. The 54xx sound, generated rather than fitted.** Run `54xx.bin` on this core with Galaga's command stream and produce the three 4-bit output channels. Compare against what emu-galaga measured from MAME's MCU: channel 1 (O7-O4, `OUTO` at address `0x09F` with the carry set) is a random bit times a stepped envelope — 13 for about 120 updates, then 15, 11, 8, 6, 4, 3, 2, 1 for about 784 updates each, then 0; 6,377 updates in 2.66 s, one every 106.8 cycles on average; channels 0 and 2 never move. There is an independent cross-check on the loop rate: Chris Kilgour's separate reverse engineering of the same ROM for Pole Position measured that loop at 90-164 cycles, mean 103.3 (`docs/validation.md`, oracle 5). **Acceptance:** the envelope ladder, the update rate within a few percent of both measurements, and channels 0 and 2 silent — all *generated*, with no fitted constants anywhere in the path. **Then state the open question's status.** With the nibble stream now generated, re-run emu-galaga's analog comparison. Either the discrete chain reproduces MAME's recording (in which case the earlier discrepancy was in the capture, and say so), or it still does not (in which case the cause is in MAME's `dst_op_amp_filt` chain, and the mismatch is now isolated to it). Write down which, with numbers. **Do not** claim to have solved it if you have only moved it. Do not skip a rung or reorder them. Milestone 2's failure is cheap to diagnose and milestone 4's is not. ## Constraints - **Never commit a ROM, a trace, or a corpus.** `*.bin`, `*.zip`, `FILE`, `error.log`, `traces/` are gitignored; keep them so. MCU programs are read in place from `$MAME_ROMPATH` through `-rompath` or by opening the zip read-only. A MAME `trace` file is a disassembly listing of a copyrighted mask ROM. - **Do not modify any other directory under `/data/emu`.** Read `/data/emu/emu-galaga` freely; when milestone 4 is ready, propose the change to that project rather than making it. - **Tier discipline.** State the tier of every oracle in every claim. "Agrees with MAME 0.285 for N instructions of `54xx.bin`" is a sentence you may write. "Verified against hardware" is one you may not, about anything in the instruction set, because no hardware oracle for this processor exists — see `docs/validation.md`. - **The four guesses stay labelled.** The timer prescale of 32, the serial prescale of 6, the 3-cycle interrupt entry and the vectors 0x002/0x004/ 0x006 are MAME's inferences. Implement them, match them, and keep them named as unproven in the README. If you find a fuller Fujitsu *MB8840 series user's manual* that settles any of them, that is a result worth more than a milestone. - **Shape.** Mirror z80-python: a small public facade, instruction families as modules, explicit dispatch that PyPy compiles well, every handler's docstring starting with its Fujitsu mnemonic, hardware reasons as comments on the lines that encode them, a readability test that enforces it. No runtime dependencies. The disassembler's mnemonics follow `mb88dasm.cpp` so a MAME `FILE` trace and this core's disassembly can be diffed directly. - **Scope boundaries, stated not apologised for**: no bus-cycle model (there is no external bus), no analog output modelling (that is the host's and emu-galaga's), no MB8850 CMOS variants beyond noting they share the instruction set, no assembler. - **Commits** in reviewable units with messages saying what the change rests on. Author `alewman `. Trailers on every commit: ```text Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01USzp3rFUxfVkjibErYHzCm ``` Local repository only. Push and open PRs only when the user asks. - Tools on this machine: `python3` at `/usr/bin/python3` (use a venv for anything extra), `git`, MAME 0.285 at `/usr/games/mame`, `gh` authenticated. No sudo. `pdftotext` is **not** installed; the datasheet was extracted with `pypdf` in a scratch venv. ## What done looks like A README that states, with numbers and their tiers: - how many of the 256 opcodes have unit tests, and against which datasheet table; - the MAME version, the trace lengths, and how many instructions of `54xx.bin` and `51xx.bin` this core matched instruction for instruction — and that this is agreement with MAME, not with silicon; - that emu-galaga's `game-2400` 51xx reply stream is reproduced byte for byte by Namco's own program; - that the 54xx's output is generated, with the measured envelope and loop rate beside both independent measurements of them; - a plain sentence naming the four things that remain unprovable and why; - and, for the open question, either an answer or a precise statement of where it now lives. Plus a CI job that runs the unit tests on every push. The lockstep gates need MAME and a ROM set, so they run locally and are recorded in `docs/validation.md` the way z80-python records ZEX. Before starting, tell the user in a few sentences how you read this brief and what you will do first.