Add a debugging and introspection surface to the pure-Python NMOS 6502 instruction core in `F:\storage-dev\6502-python`, matching the capability and quality bar already established by the sibling Z80 core, WITHOUT changing any existing observable CPU behaviour. This is an additive capability project on a complete, green codebase. No opcode semantics, cycle counts, bus accesses, flag effects, or existing public type names may change. ## Prerequisite This project assumes the polish/refactor project (`6502-polish-refactor-goal.txt`) has ALREADY COMPLETED and been merged. It expects to start from a `src/sixfiveohtwo/` layout with per-family mixin modules, an explicit `__init__.py`, and the wider Ruff ruleset already adopted. If you find a flat `sixfiveohtwo/` package with a 1,400-line `core.py` and a lazy `__getattr__` in `__init__.py`, STOP and report that the prerequisite has not been met. Do not attempt both projects at once. ## Approved execution boundary - Work only in `F:\storage-dev\6502-python`. - Use only the target-local interpreter `F:\storage-dev\6502-python\.venv\Scripts\python.exe` for project commands. - Never modify, regenerate, move, or delete anything under `tests/6502_test_vectors/` or `tests/dormann/`. Both are immutable oracles. - Do not read, copy, or import source from any sibling `6502-python-*` directory. Those are abandoned experiments. - You MAY read `F:\storage-dev\z80-python` for structural and API reference. Do not copy Z80 instruction semantics or Z80 mnemonics into this core. ## The non-negotiable invariant Every task must leave the entire test suite passing, run as: F:\storage-dev\6502-python\.venv\Scripts\python.exe -m pytest with NO path argument, NO `-k`, NO `-m`, and NO test file selection. The whole suite, every time. **This command takes about 17 minutes.** Measured at the pre-refactor `b57ad11` baseline: 681 passed in 1,001 seconds. You MUST explicitly request a shell timeout of at least 1,500 seconds every single time you run it. A run command that does not ask for a timeout gets a 60-second default and will be killed long before the suite finishes, which looks like a hang or an infrastructure failure but is neither. Do not interpret such a kill as a broken change, and do not respond to it by narrowing the test selection -- re-run with the correct timeout. Do NOT delete, skip, xfail, weaken, narrow, or add tolerances to any existing test in order to make a change pass. ## Two verified facts that must shape the design These were confirmed empirically against the real core. Do not re-derive them, and do not design as though they were false. ### 1. Retained step results alias live mutable state `InstructionStep`, `ResetStep`, and `InterruptStep` are declared `@dataclass(frozen=True)`, but `InstructionStep.context.state` holds a REFERENCE to the CPU's live, mutable `CPUState`. Freezing the dataclass freezes only the reference, not the registers behind it. Demonstrated: after stepping `LDA #$11`, `first.context.state.accumulator` read `0x11`. After a second `LDA #$22` step, that same `first` object reported `0x22`. `first.context.state is cpu.state` is `True`. Consequence: a debug history built directly out of returned step objects is worthless -- every entry would report the final state. Recording history REQUIRES taking an immutable snapshot at each boundary. This is the single most important correctness constraint in this project, and the history tests must explicitly prove that an older record does not change when later steps run. ### 2. The name `CPUState` is already taken, and means something else In this core, `CPUState` is the CPU's live, MUTABLE register container holding `Accumulator`, `IndexRegisters`, `ProgramCounter`, `StackPointer`, `StatusFlags`, and a `cycles` counter. It is public and exported. The Z80 core uses the name `CPUState` for its immutable snapshot value. Do NOT copy that name here and do NOT repurpose or re-type the existing `CPUState` -- either would silently break every existing embedder. Introduce a NEW, distinctly named immutable value for snapshots. Use `CPUSnapshot` unless you find a clearly better name, and say so if you do. ## What this core already has that the Z80 core does not The Z80 `step()` returns a bare integer T-state count, so its debug layer has to infer what kind of boundary occurred by inspecting CPU state afterwards. This core is better off. `CPU.step()` already returns a typed result -- `InstructionStep`, `ResetStep`, `IRQStep`, or `NMIStep` -- carrying `cycles`, `total_cycles`, `vector`, `accepted_events`, and, for instructions, an `InstructionContext` with `opcode`, `opcode_address`, and `boundary`. Use that. Derive boundary kind from the returned TYPE, not by re-inspecting state after the fact. Do not port the Z80's `_boundary_kind(state)` inference helper; reproducing it here would discard information the core already hands you and would be a downgrade. ## Invariants All phases must preserve these properties: 1. `CPU.step()` remains the small, authoritative one-boundary operation, and its existing return types and values are unchanged. 2. The instruction core retains no debugger, trace-history, UI, network, or AI state. 3. Normal execution pays no per-instruction callback cost when debugging is not in use. Control belongs AROUND `step()`, not inside opcode handlers or the dispatch chain. Do not add `before_instruction`/`after_instruction` hooks to the hot path. 4. The base installation remains pure Python with no runtime dependencies. 5. CPU state and machine state remain distinct. The core cannot snapshot or restore host RAM or devices. A snapshot restores the processor, not a machine. 6. Debug reads must not accidentally perform device reads. Generic tooling uses an explicit side-effect-free `peek_byte()` contract rather than assuming a host's `read_byte()` is safe for disassembly or memory views. Hosts that do not provide `peek_byte` must degrade with a clear error, not a silent device read. 7. Structured output is deterministic, compact, versioned, and independent of terminal formatting. No timestamps, colours, or prose in the data contract. 8. Existing hosts remain source-compatible. New capabilities are adapters or optional protocols, never new required methods on the host memory object. 9. The debugger wraps a CPU instance. Do not create a debug-specific `CPU` subclass; real machines already subclass `CPU` and the debugger must not compete for that inheritance slot. ## Required phase order 1. **Immutable snapshot.** Add a frozen, slotted `CPUSnapshot` value covering everything needed to resume the processor: A, X, Y, PC, S, the persistent status flags, the cycle total, and pending lifecycle state (RESET/IRQ levels and the latched NMI indication). Add `CPU.capture_state()` and `CPU.restore_state()`. Restoration must validate widths and legal values rather than assigning an arbitrary object into the CPU. Include a test that proves a snapshot taken before a step is unchanged after that step runs. 2. **Disassembler.** Add a pure, side-effect-free disassembler over a `ByteReader` protocol producing an immutable `Instruction` value with address, length, mnemonic, operand text, and raw bytes. It must cover all 256 opcodes including the undocumented ones, and must agree with the existing opcode catalog rather than duplicating it as a second hand-written table. A disagreement between disassembler and catalog is a test failure. 3. **Debug session.** Add a `DebugSession` that wraps a CPU, records a bounded history of immutable step records (see the aliasing fact above), supports PC breakpoints, and offers a bounded `run()` returning a structured result with an explicit stop reason (breakpoint, jammed, step limit, cycle limit). Note this core has real JAM/KIL opcodes that halt the processor until RESET; a jammed CPU is a first-class stop reason, not a hang. 4. **Trace records.** Add versioned, deterministic serialization of step records to and from a text stream, plus comparison helpers that report the first divergence between two traces. This is the seam that makes the core usable as a differential oracle against another emulator. 5. **Command surface.** Add a small, dependency-free command debugger that parses bounded text commands (step, run, disassemble, memory, history) and returns structured results. Presentation is a thin formatting layer over those results, not the source of truth. 6. **Documentation.** Add `docs/cpu-state.md`, `docs/disassembly.md`, `docs/debug-session.md`, and `docs/trace-comparison.md`, mirroring the Z80 core's documentation set. Update `README.md` and the public `__all__`. ## Readability bar The point of this core is that someone can learn a 6502 from it. Prefer clear names and small, single-purpose functions over cleverness. Each new module gets a module docstring saying what it provides. Add a comment only where the code cannot explain itself. Do not introduce metaprogramming, dynamic dispatch tricks, or lazy-import machinery. ## Out of scope No 65C02 or 65816 support. No memory maps, cartridges, or machine-specific devices. No full-screen TUI, curses, Rich, or Textual. No AI orchestrator, prompt engine, or model-provider SDK. No network or remote-debug protocol. No change to existing public type names or their behaviour. No performance optimisation that reduces clarity.