Refactor the pure-Python NMOS 6502 instruction core in `/data/emu/6502-python` into a readable, well-organised reference implementation matching the structure and quality bar of the sibling Z80 core, WITHOUT changing observable behaviour. This is a behaviour-preserving refactor of a complete, green, published codebase. It is NOT a feature campaign. No opcode semantics, cycle counts, bus accesses, flag effects, or public type names may change. ## Approved execution boundary - Work only in `/data/emu/6502-python`. - Use only `/data/emu/6502-python/.venv/bin/python`. - Never modify, regenerate, move, or delete anything under `tests/6502_test_vectors/` or `tests/dormann/`. Both are immutable oracles. - You MAY read `/data/emu/z80-python` for structural reference only. Do not copy Z80 instruction semantics into this core. ## Starting state (verified; do not re-derive) - Baseline commit `5fcbb28`, branch `main`, clean. Tag `pre-polish-baseline` marks it. It repairs the oracle fetchers and touches only `scripts/` and `tests/`; do not revisit it. - `sixfiveohtwo/` is a flat package. TOTAL physical lines at `5fcbb28`: `core.py` 1,421 (entire opcode catalog, addressing modes, CPU execution), `cpu.py` 266, `interrupts.py` 108, `__init__.py` 64, `memory.py` 28. - In `core.py`: `class CPU` starts line 572 and runs to EOF; `_execute_instruction` starts line 914 and is one ~400-line chain of `if mnemonic == ...` / `if mnemonic in {...}` blocks each returning a cycle count; `resolve_addressing` starts 781; `step` starts 1,351; `_OPCODE_ROWS` spans 191-392. - `OFFICIAL_OPCODES` contains all 256 opcodes. - Ruff selects only `E`, `F`, `I` at line-length 88, and currently passes. - The suite is green, including the vector sweep and both Dormann exercisers. ## Verified facts that constrain this refactor Confirmed empirically. Do not re-derive. Each silently breaks a phase if ignored. **The editable install hard-codes the repo root.** `_editable_impl_6502_python.pth` in site-packages holds one line, `/data/emu/6502-python`, putting the repo ROOT on `sys.path` -- which works only because `sixfiveohtwo/` sits there. After phase 2 moves it to `src/`, phase 2 MUST re-run `pip install -e .` with the venv Python. Beware split-brain: setting only pytest's `pythonpath` makes pytest pass while `python -c "import sixfiveohtwo"` still fails. Phase 2 is done only when both work; verify the second from outside the repo root. **The oracle corpus is ~273 MB under `tests/6502_test_vectors/` and is gitignored**, as is `tests/dormann/`. Missing vectors skip, not fail. So the phase-1 CI workflow must NOT fetch the corpus, CI's pass/skip counts will legitimately differ from the local baseline, and CI must carry no baseline-count assertion. **`sixfiveohtwo.core` is part of the test contract.** Tests import from it directly, including two PRIVATE helpers. After phase 3 all of these must still be importable from `sixfiveohtwo.core`: OFFICIAL_OPCODES, decode_opcode, AddressingMode, AddressingResult, CPU, OpcodeDefinition, InstructionContext, InstructionStep, InterruptStep, ResetStep, IRQStep, NMIStep, NmiStep, UnsupportedOpcodeError, _normalize_byte_address, _normalize_word_address Relocating a family is legal only if `core.py` re-exports these. **`test_build.py` is the packaging canary.** It asserts `"sixfiveohtwo/__init__.py" in names` for the built wheel. That must KEEP passing after the move, so `[tool.hatch.build.targets.wheel]` becomes `packages = ["src/sixfiveohtwo"]`, keeping `sixfiveohtwo/` at the wheel root. If it fails, the packaging move is wrong -- do not edit the test. ## The non-negotiable invariant Every task must leave the entire test suite passing, run as: /data/emu/6502-python/.venv/bin/python -m pytest with NO path argument, NO `-k`, NO `-m`, and NO test file selection. The whole suite, every time. A task that only runs the tests it happens to own has not verified this refactor. **This takes about 4 minutes** (baseline: 682 passed, 1 skipped, in 235 s). You MUST explicitly request a shell timeout of at least 1,500 seconds every time. A run command that does not request a timeout gets a 60-second default and is killed long before the suite ends. That looks like a hang or an infrastructure failure but is neither: do not read it as a broken refactor, and do not respond by narrowing test selection. Re-run with the correct timeout. Do NOT delete, skip, xfail, weaken, narrow, or add tolerances to any existing test to make a change pass. If a test fails, the refactor is wrong; fix it. **One narrow exception:** `tests/test_package.py`, during phase 4 only. It pins the public namespace via `assert package.__all__ == ("MemoryBus",)` and a matching `public_symbols` assertion. Phase 4 deliberately changes that namespace, so those two assertions MUST be updated to describe the new explicit API. Update them to assert the new export set precisely -- do not delete the test, do not loosen it to a subset check, and do not touch any other test file under this exception. Outside it, a failing test means the refactor is wrong. ## Comparing against the baseline "Matches baseline" means zero failures, zero errors, and no baseline-passing test now missing, skipped, or xfailed. Exactly ONE test is skipped at baseline: the Dormann decimal exerciser, which needs a cc65 toolchain absent on this host. That skip must stay a skip; do not install cc65 or build the decimal binary. The passed count may INCREASE when a phase adds tests; it may never decrease. Record any increase and its cause in `docs/refactor-baseline.md`. ## Baseline capture (first task) Before any file moves, record into `docs/refactor-baseline.md`: the full `pytest` summary line, the total collected count, and `git rev-parse HEAD`. Later tasks compare against those recorded numbers. Do not hard-code an expected count anywhere in the suite: a hard-coded catalog size in this project already drifted and hid a real failure. ## Required phase order 1. **Repository hygiene.** Add `CONTRIBUTING.md`, `SECURITY.md`, an `examples/` directory with a minimal host program exercising the public API, and a GitHub Actions workflow installing the package and running `ruff check` and the suite. The workflow must NOT download the corpus; it runs with vectors absent, where they skip cleanly. No changes under `sixfiveohtwo/`. 2. **Source layout.** Move `sixfiveohtwo/` to `src/sixfiveohtwo/`; update `pyproject.toml` packaging and pytest config. Pure relocation: no code edits beyond imports the move forces. Re-run the editable install afterwards, and add a test importing the package from outside the repo root so the stale `.pth` trap cannot silently return. 3. **Extract each instruction family into its own module, one family per task.** Per task, take ONE family: move its branch bodies VERBATIM out of the `_execute_instruction` chain onto methods of a `*Mixin` class in a new private module (e.g. `_alu.py` defining `ALUMixin`), have `CPU` inherit it, and leave the chain delegating to those methods. Families: flag set/clear; NOP and JAM; jumps and subroutine calls; branches; load/store/transfer; stack; arithmetic (ADC/SBC and the decimal path); logical and BIT; shift and rotate; compare; increment/decrement; and the undocumented combined operations. Preserve early-return semantics exactly; change no behaviour, cycle count, or bus-access ordering. Each task touches only `core.py` plus its one new module -- the largest family is ~72 lines, so this stays well inside the per-task ceilings -- and `core.py` must keep re-exporting every name in the contract above. The aim is that every opcode handler is greppable by mnemonic and filed with its group, as the Z80 core is. 4. **Public API.** Replace the lazy `__getattr__` import machinery in `__init__.py` with explicit imports and an explicit `__all__`, in the style of the Z80 core's `__init__.py`. Every name importable before must remain importable, from the same top-level package path. This is an additive change -- names are exposed explicitly rather than lazily, and nothing is removed. Update `tests/test_package.py` under the narrow exception, deleting its now-obsolete comment about lazily-loaded names attaching their owning submodule, since that side effect disappears. 5. **Lint parity.** Adopt the Z80 core's Ruff rule SELECTION: `E`, `W`, `F`, `I`, `UP`, `B`, `C4`, `SIM`, `PERF`, `RUF` at line-length 100, and resolve every diagnostic (about 13 today). Fixes must be mechanical and behaviour-preserving. Scope is `ruff check` only. Do NOT add a repo-wide `ruff format --check` gate, here or in CI: the Z80 core itself fails it (14 files), so it is not parity, and 27 files here would need reformatting -- far past the 6-file per-task ceiling. 6. **Final verification and documentation.** Run the ENTIRE suite with bare `pytest`, confirm it matches the captured baseline, update `README.md` and `docs/validation.md` for the new layout, add `docs/start-here.md` -- a primer teaching the 6502 as this core models it (registers, the status byte, addressing modes, the interrupt/RESET model), mirroring the Z80 core's `start-here.md` -- and record the result in `docs/refactor-baseline.md`. ## Readability bar The point is a core someone can learn a 6502 from. Prefer clear names and small, single-purpose functions. Each new module gets a docstring naming its family. Comment only where the code cannot explain itself. No metaprogramming, dynamic dispatch tricks, or lazy-import machinery. ## Out of scope No new features. No debugger, disassembler, tracer, or console. No performance optimisation that reduces clarity. No new runtime dependencies. No 65C02 or 65816 support. No change to public type names or their behaviour.