# Machine-Layer Delivery Plan ## Purpose Galemu is now a consumer of the separately released `z80-python` instruction core. The next goal is not a pygame display; it is a deterministic, inspectable Galaxian board model that executes the verified ROMs and produces stable machine evidence. The ROM dump, address map, video layout, and discrete-sound register map are already captured in [rom-manifest.md](rom-manifest.md), [memory-map.md](memory-map.md), [video-hardware.md](video-hardware.md), and [sound-hardware.md](sound-hardware.md). Every implementation task must cite one of those sources or record newly researched evidence before it changes behavior. ## Delivery milestones ### M0: Consumer cutover - Pin Galemu to `z80-python==0.3.0` and import `z80_python.Z80CPU` at the board boundary. - Remove the formerly embedded CPU implementation, its vector corpus, benchmarks, and CPU-only test suite in a dedicated deletion commit after clean-install validation proves Galemu is not importing them. - Retain only a short dependency/provenance record. CPU instruction validation belongs to the released package, not to each machine consumer. **Gate:** a fresh virtual environment installs Galemu and resolves `z80_python` from the installed dependency. A minimal host executes the documented two-instruction smoke program. ### M1: Deterministic headless board tracer Build `GalaxianBoard`, a `Z80CPU` host with no pygame or audio dependency: - immutable, size- and CRC-checked program-ROM loading; - exact address decoding and mirrors from [memory-map.md](memory-map.md); - documented active-high idle inputs: `IN0=0x00`, `IN1=0x00`, and `IN2=0x04` (upright cabinet, 1C/1C coinage, 7,000-point bonus, three lives), whose state is owned by a small explicit input object; - board-owned RAM arrays for work RAM, tile RAM, and the shared attribute/sprite/bullet RAM block; - mapped-write event capture for hardware-visible state: lamps, coin devices, sound latches, star enable, screen flips, IRQ enable, and all video-area writes; and - cumulative instruction count and T-states from `Z80CPU.step()`. The trace format is data, not console text: immutable records with instruction number, T-states, PC, kind, address, value, and decoded target. Tests compare the structured records directly. The current headless exporter writes canonical JSON without timestamps or random IDs: `python -m galemu --rom-path rom/galaxian.zip --instructions 5000 --output boot-trace.json`. An optional bounded input-read diagnostic trace records the first requested reads without inflating the normal mapped-write evidence stream. **Gate:** repeated runs from identical ROMs and inputs produce byte-for-byte identical trace serialization and selected RAM snapshots. The initial golden trace must show ROM initialization reaching expected board-visible writes; it must not merely assert that the program counter moved. **Current evidence:** the verified parent ROM reaches its real `0x7001` NMI-enable write at instruction 632,753 / T-state 4,434,249, after initializing the starfield, flip latches, sound pitch, and RAM regions. ### M2: Interrupt lifecycle dependency The verified parent board's vblank circuit generates an NMI once per frame, rather than a maskable interrupt. Its `0x7001` latch enables that flip-flop. M1 therefore traces boot safely without pretending to run a full frame loop. The reusable core provides both interrupt lifecycles in `z80-python==0.3.0`. The Galaxian board requests an NMI through that public API; it must never synthesize one by mutating `PC`, `SP`, or flags behind the core's back. **Gate:** focused core and board tests prove NMI acceptance, HALT wakeup, priority, and `0x7001` latch gating. ### M3: Headless multi-frame board evidence - schedule frame/vblank events from the documented 3.072 MHz CPU clock and 60.606 Hz display cadence; - run multiple frames with deterministic inputs; - freeze compact golden traces and RAM snapshots; and - compare changed input bits to the expected input-port observations. **Gate:** the trace, RAM snapshots, and event counters are deterministic across runs. **Current evidence:** snapshots now expose vblank and accepted-NMI counters. Two runs through vblank 90 produce byte-identical boundary snapshots, mapped-write traces, and terminal snapshots. The compact terminal checkpoint is instruction 646,976 / T-state 4,554,252 / PC `0x0066` / SP `0x43fe`, after accepting three real-ROM vblank NMIs. A controlled active-high player-one fire bit at vblank 120 is observed at the ROM's next `IN0` read (`0x6000`) as `0x10`, then as idle `0x00` after it is released; the complete bounded input-read trace is deterministic across repeated runs. ### M4: Pure render and device transforms Implement and unit-test these as pure functions, independent of pygame and a running ROM: 1. palette-PROM decode; 2. graphics bitplane decode; 3. tilemap plus column attributes; 4. sprite and bullet decode; 5. starfield table/scroll transform; 6. input-bit routing; and 7. sound-register-to-semantic-event mapping. **Current evidence:** the color-PROM resistor DAC is implemented as pure byte-to-RGB decoding, with unit fixtures for each channel's full-scale and mixed-weight outputs. The pure graphics transform also decodes the complete 4 KiB two-plane region into 256 8×8 tiles and 64 16×16 sprites, with synthetic fixtures covering bit order, high code indices, and sprite quadrants. The tilemap transform composes the visible 32×28 tile area into 32-entry palette indices, verifies the 1 KiB tile and 64-byte attribute RAM shapes, and applies the documented odd-byte per-column color group. It deliberately leaves the paired horizontal-scroll byte as a later explicit transform because plain Galaxian does not use it. Sprite and bullet decoders now produce immutable descriptors from their distinct 32-byte RAM regions, preserving slot order, sprite flips and color groups, and the source-backed bullet geometry/colors. Board-screen flips, viewport cropping, and layer compositing remain explicit later transforms. The starfield now builds its fixed 17-bit LFSR source deterministically and applies the native scroll and twinkle transform. These transforms have no pygame or ROM-file dependency. The remaining device transforms are also explicit: active-high cabinet controls route through a pure port-bit mapping that preserves DIP-switch bits, and every mapped discrete-sound write decodes into a typed semantic event (background resistor, tone enable, hit, fire, volume, or pitch). The board records those normalized events in its deterministic trace while the pure mapping remains available to the future pygame shell. ### M5: Interactive composition Compose M4 outputs into pygame, then verify attract screens, sprite layering, starfield motion, controls, and approximate sound perceptually. Capture reference screenshots and small trace excerpts as review artifacts, but do not mistake a pixel screenshot alone for the board-level correctness gate. **Current evidence:** M5 begins with a pure native-raster boundary: verified graphics and palette assets load independently of the program ROM, while the 256×224 tilemap palette-index frame maps to immutable RGB rows without pygame. This keeps the first pygame adapter mechanical and makes its visual inputs independently testable. The pure compositor now covers MAME-derived star RGB levels, transparent tile pens, sprite slot priority, bullets, and board flips. The optional `pygame-ce` display extra loads only after those transforms, advances the real board one vblank at a time, and routes keyboard transitions through `set_input()`: arrows (move), Space (fire), 1/2 (start), and 5 (coin). The adapter rotates the logical 256×224 raster clockwise into its 224×256 cabinet portrait orientation. It was smoke-tested headlessly against the verified local ROM through 90 vblanks (646,976 instructions), producing a non-black native frame; the local screenshot stays outside the repository with the ROM assets. The complete cabinet path also has ROM-gated evidence: a deterministic coin pulse (vblanks 300–420), then a start pulse (480–600), reaches a gameplay frame at vblank 900. Its immutable RGB-byte SHA-256 is asserted rather than storing any ROM-derived image. ### M6: Optional approximate sound The board already exposes typed sound-register events. The first audio slice is a pure, 48 kHz PCM16 transform: every exact board frame maps to 792 samples, with immutable oscillator/latch/envelope state and no pygame dependency. It approximates continuous background/tone generators and rising-edge fire/hit envelopes; an optional device adapter now reconstructs typed sound writes from the immutable board event stream and queues the frames through pygame when a mixer device is available. A dummy-device smoke run carried 120 real-ROM vblanks through that path (95,040 PCM samples). This preserves the established rule that audio failure must never prevent visual play. ## Visibility and determinism contract Every subsystem must expose a small testable state surface: | Subsystem | Required evidence | | --- | --- | | ROM loader | file name, length, SHA/CRC result, load offset | | Address decoder | table-driven unit cases covering canonical and mirrored addresses | | CPU execution | instruction count, accumulated T-states, sampled PC/register state | | Memory | selected named ranges and deterministic snapshots | | I/O writes | typed event records, never print-only logging | | Frame scheduler | explicit frame/vblank counters and requested/accepted IRQ counts | | Rendering transforms | exact fixture input/output tests | | pygame shell | manual screenshots and a short repeatable smoke run | Avoid nondeterministic timestamps, random IDs, unordered collections in serialized traces, and mutable objects stored in events. Test fixtures must construct the input state explicitly. Golden artifacts should be small, reviewable, and regenerated only when an intentional, explained board behavior change occurs. ## Work allocation ### Terra-led - consumer-cutover deletion/release boundary; - M1 board integration and first ROM trace investigation; - reusable interrupt-lifecycle API and release; - golden-trace selection/review; - pygame composition and all perceptual/playability decisions. ### afk-developer Use one bounded task or batch at a time after M1 has established stable fixtures: - ROM-manifest loader/checksum tests; - palette, graphics, tile, sprite, bullet, and starfield pure transforms; - input and sound-register mapping; and - narrowly scoped test expansion with pytest/Ruff/diff-check gates. Do not delegate open-ended ROM bring-up, interrupt semantics, trace interpretation, or visual acceptance as a broad autonomous stage. Those tasks need the forced, short feedback loop and judgment available in an interactive session. ## Standard acceptance gate For every implementation milestone: targeted tests, full `pytest`, `ruff check .`, format check, `git diff --check`, and a review of `git status`. For M0 also validate from a fresh environment; for M1-M3 also compare structured golden artifacts.