regenerator2000
AGENTS.md164 starsChanged 10 months agoApache-2.0View on GitHub
Regenerator 2000 is an interactive 6502 disassembler TUI written in Rust, targeting Commodore 8-bit machines. It uses ratatui + crossterm for the terminal UI and exposes an MCP (Model Context Protocol) server for programmatic access. The project is split into two main crates to separate logic from presentation: Regenerator 2000 follows a unidirectional data flow (Redux/Elm style):
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,736 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repositoryOne other file it gives its agents.
- CLAUDE.mdCLAUDE.md
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
33 rules. About 0 are common, 2 are distinctive, and 31 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
31
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 67
When adding or modifying a feature, ask: *"Would this logic need to be duplicated if a third client (e.g., a GUI, a CLI) were added?"* If …
- Very specific: line 73
Never hardcode platform constants: Do not hardcode machine-specific memory addresses (such as $0800 RAM start, $0801 BASIC start, $0400 …
- Very specific: line 75
Keep Documentation System-Agnostic: When updating docs/unpacker.md or adding unpacker documentation, describe memory boundaries and …
- Very specific: line 97
All AI-generated code MUST follow the rules below.
- Very specific: line 105
Use anyhow::Result for application-level errors where context strings suffice, and typed thiserror enums for library-facing error surfaces.
- Distinctive: line 112
Do not remove these attributes.
- Very specific: line 116
Prefer ? over manual match/if let for error propagation.
- Very specific: line 117
Add context with .context("what was attempted") (from anyhow) when propagating errors across module boundaries.
- Very specific: line 118
Do not silently swallow errors with let _ = some_fallible_call();.
- Very specific: line 123
Add #[must_use] to every pure function (one with no side effects whose return value carries meaning).
- Very specific: line 126
Run cargo clippy -- -W clippy::must_use_candidate to find unannotated candidates in existing code.
- Very specific: line 133
Use intra-doc links (` [TypeName] ) to cross-reference types.
- Very specific: line 134
Run cargo clippy -- -W clippy::missing_errors_doc -W clippy::missing_panics_doc to audit doc coverage.
- Very specific: line 138
Prefer newtypes over raw primitives when a value has a distinct semantic meaning (e.g.
- Very specific: line 141
Use Default for structs with sensible zero-values.
- Very specific: line 142
Avoid bool parameters in public APIs.
- Very specific: line 146
Prefer &str over &String, &[T] over &Vec<T>, and &Path over &PathBuf in function signatures.
- Very specific: line 147
Use impl Into<String> (or impl AsRef<str>) for constructor arguments that store a String, as System::new does.
- Very specific: line 148
Avoid unnecessary .clone() — pass references where ownership is not needed.
- Very specific: line 149
When passing closures that only forward to a free function (|x| f(x)), write f directly (clippy::redundant_closure).
- Very specific: line 153
Use BTreeMap/BTreeSet for address-keyed maps that must be iterated in order (deterministic output for project files).
- Very specific: line 154
Prefer .entry().or_default() over if !map.contains_key() { map.insert() }.
- Very specific: line 158
Run cargo fmt before committing (enforced by pre-commit hook and CI).
- Very specific: line 159
Prefer write!(buf, "{x}") over buf.push_str(&format!("{x}")) (clippy::format_push_string).
- Very specific: line 160
Use format! capture syntax: format!("{x}") not format!("{}", x) (Rust 2021+).
- Very specific: line 165
Every non-trivial function in regenerator2000-core should have at least one unit test in the same file (#[cfg(test)]).
- Very specific: line 168
Use AppState::new() (not a manually built struct) as the test baseline.
- Very specific: line 207
New Block Type: Add to BlockType enum in types.rs, update analyzer.rs, and add a shortcut in input.rs.
- Very specific: line 208
New Assembler: Add to Assembler enum, implement Formatter trait in disassembler/formatter_*.rs.
- Very specific: line 209
New Command: Add variant to Command in commands.rs, implement apply and undo.
- Very specific: line 214
Use present tense, imperative mood (e.g., Add support for D71 disk images).
- Distinctive: line 218
Never: create a git commit automatically after completing a task.
- Very specific: line 224
Verification: Always run cargo test and cargo clippy before finalizing changes.
≈ “Common” is an estimate: at least 1 in 5 of the 16,597 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Regenerator 2000 - Agent Instructions
Regenerator 2000 is an interactive 6502 disassembler TUI written in Rust, targeting Commodore 8-bit machines. It uses ratatui + crossterm for the terminal UI and exposes an MCP (Model Context Protocol) server for programmatic access.
Architecture & Crate Structure
The project is split into two main crates to separate logic from presentation:
regenerator2000-core: Contains all UI-agnostic logic.analyzer.rs: Auto-analysis (walking code, generating labels).assets.rs: System asset loading (labels, comments, exclude lists).commands.rs: TheCommandenum andUndoStack. Every undoable action is a command.config.rs: System-wide configuration management.core.rs: Central orchestration logic (file loading, command dispatch, integration).cpu.rs: 6502 opcode table and addressing mode logic.disassembler/: 6502 decoding and assembler formatters (64tass, ACME, KickAssembler, ca65).event.rs: Application event types.exporter/: Code for exporting disassembly to ASM or HTML, with roundtrip verification.mcp/: MCP server implementation (stdio and HTTP transports). Containshandler.rsdispatcher andtools/submodules (analysis_tools,navigation_tools,modification_tools,session_tools,common).navigation.rs: Address navigation logic.packers/: 6502 binary packer strategies (Packertrait, signature detection, pre/post emulation hooks).parser/: File format parsers (.prg, .d64/.d71/.d81, .t64, .crt, .vsf snapshots, .dis65, VICE labels).state/: Persistent application state and project serialization.utils.rs: Shared utility functions.vice/: VICE binary monitor protocol client for live debugging.view_state.rs: View state management.
regenerator2000-tui: Contains all terminal UI-related code.ui/: TUI widgets, views (view_disassembly/submodule breakdown [layout.rs,navigation.rs,mouse.rs,render.rs,mod.rs], HexDump, Sprites, Charset, Bitmap, Blocks, Debugger), and dialogs.ui_state.rs: Transient UI state (cursor, scroll, active dialog).events/: Input handling and event loop.theme.rs: Color scheme and styling logic.theme_file.rs: Theme file parsing and custom theme support.utils.rs: TUI utility functions.
Core Domain Model
Key Types (crates/regenerator2000-core/src/state/types.rs)
Addr: A wrapper aroundu16representing a 6502 address.System: Target machine (C64, C128, VIC20, PET, etc.).Assembler: Target assembler syntax (Tass64, Acme, Ca65, Kick).BlockType: How a range of bytes is interpreted (Code, DataByte, DataWord, Address, PetsciiText, ScreencodeText, LoHiAddress, HiLoAddress, LoHiWord, HiLoWord, ExternalFile, Undefined).LabelType: Semantic meaning of a label (Subroutine, Jump, Branch, Pointer, ZeroPagePointer, Field, ZeroPageField, AbsoluteAddress, ZeroPageAbsoluteAddress, ExternalJump, Predefined, UserDefined, LocalUserDefined).
State Management
AppState(crates/regenerator2000-core/src/state/app_state.rs): The single source of truth for persistent data. Includesraw_data,block_types,labels,user_side_comments,user_line_comments,undo_stack,settings,cross_refs,bookmarks, andscopes. Serialized to.regen2000proj.UIState(crates/regenerator2000-tui/src/ui_state.rs): Transient state like cursor positions, scroll offsets, and active dialogs. Never serialized.
Application Logic Flow
Regenerator 2000 follows a unidirectional data flow (Redux/Elm style):
- Input:
crates/regenerator2000-tui/src/events/input.rsmaps key events toMenuAction. - Dispatch:
MenuActionis converted into one or moreCommandvariants. - Execution:
Command::apply(&mut AppState)modifies the state and pushes toUndoStack. - Analysis:
AppState::analyze()(viaanalyzer.rs) updates labels and cross-references. - Render:
ui()incrates/regenerator2000-tui/src/ui.rsre-renders the TUI fromAppState+UIState.
No Logic Duplication — State Logic Lives in Core
All validation, business rules, and state-mutation logic must live in regenerator2000-core (typically as methods on AppState in state/). Both the TUI (regenerator2000-tui) and the MCP server (mcp/ handler + mcp/tools/ submodules) are consumers of core logic — they must call shared AppState methods, not re-implement the same checks independently.
For example, if label creation needs to reject duplicate names, that validation belongs in an AppState method (e.g., create_set_user_label_command). The MCP tool submodules (mcp/tools/) and the TUI dialogs both call that single method. Never add domain logic directly into mcp/tools/ or events/input.rs if it can be expressed as a core method. TUI disassembly rendering belongs in view_disassembly/render.rs, view navigation in view_disassembly/navigation.rs, visual layout math in view_disassembly/layout.rs, and mouse interaction in view_disassembly/mouse.rs.
When adding or modifying a feature, ask: "Would this logic need to be duplicated if a third client (e.g., a GUI, a CLI) were added?" If yes, it belongs in regenerator2000-core.
System-Agnostic Design & Unpacker Rules
The core disassembler and binary unpacker (crates/regenerator2000-core/src/unpacker/ directory) target Commodore 8-bit machines (C64, C128, VIC-20, PET, Plus/4).
- Never hardcode platform constants: Do not hardcode machine-specific memory addresses (such as
$0800RAM start,$0801BASIC start,$0400screen RAM, or$0314IRQ vector) directly insrc/unpacker/or documentation. Always query system properties viaSystemplatform methods (system.ram_start(),system.default_basic_start(),system.screen_ram(),system.default_irq(),system.is_c64()). - Guard platform-specific features: System-specific behavior (such as C64 PLA processor port
$01banking or zero-page template copying) must be explicitly guarded (e.g.if system.is_c64()). - Keep Documentation System-Agnostic: When updating
docs/unpacker.mdor adding unpacker documentation, describe memory boundaries and zero-page setups in a system-agnostic way (referencing system RAM start$0800on C64,$1C00on C128,$1000on VIC-20,$0400on PET) rather than assuming C64 defaults globally.
AI Agent Skills (.agent/skills/)
Specialized tools are available for common tasks. Invoke them via activate_skill:
r2000-analyze-basic: Analyze BASIC programs and mark pointers.r2000-analyze-blocks: Auto-detect and set block types (text, data).r2000-analyze-program: Orchestrate full-program analysis using subagents for blocks, routines, and symbols.r2000-analyze-routine: Trace a subroutine and mark code paths.r2000-analyze-symbol: Find and label all references to a specific address.compare-unpacker: Benchmark Regenerator 2000 unpacker against unp64 and generate comparison reports.add-mcp-tool: Templates for adding new programmatic tools to the MCP server.bump-version: Automate version bumping and changelog updates.coding: General Rust coding assistance with project context.code-review: Review changes for idiomatic Rust and project conventions.update-keyboard-shortcuts: Sync keyboard shortcuts across docs and source files.update-mcp-docs: Syncdocs/mcp.mdwith the actual MCP tools.verify-mcp: Run MCP integration test suite to verify server functionality.
Rust Best Practices
All AI-generated code MUST follow the rules below. The project enforces them through cargo clippy -- -D warnings; violations will block CI.
Panic Safety
Production code must never panic silently.
- Never use
.unwrap()or.expect()outside of#[cfg(test)]blocks. Both are banned byclippy::unwrap_used/clippy::expect_used. - Return
ResultorOptionand propagate errors with?. - Use
anyhow::Resultfor application-level errors where context strings suffice, and typedthiserrorenums for library-facing error surfaces. unreachable!()inside exhaustivematcharms (e.g. an enum variant that logically cannot appear) is acceptable. All other panic macros require a comment explaining why the invariant holds.- Both
lib.rsfiles gate these lints via:
Do not remove these attributes.#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::panic))] #![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))]
Error Handling
- Prefer
?over manualmatch/if letfor error propagation. - Add context with
.context("what was attempted")(fromanyhow) when propagating errors across module boundaries. - Do not silently swallow errors with
let _ = some_fallible_call();. Log or propagate them. - MCP tool handler functions must return explicit
McpErrorvariants for invalid/missing parameters — seemcp/tools/submodules for the established pattern.
API Hygiene (#[must_use])
- Add
#[must_use]to every pure function (one with no side effects whose return value carries meaning). This includes constructors (fn new), getters, and any function returningbool, a numeric type, or a wrapped newtype. - Functions that mutate state (
&mut self) and return()do not need#[must_use]. #[must_use]on animplblock annotates every method — use sparingly; prefer per-method annotations.- Run
cargo clippy -- -W clippy::must_use_candidateto find unannotated candidates in existing code.
Documentation
- All
pubitems inregenerator2000-coremust have a doc comment (///). - Functions returning
Resultmust include a# Errorssection explaining when they fail. - Functions that can panic (outside tests) must include a
# Panicssection. - Use intra-doc links (
[`TypeName`]) to cross-reference types. Runcargo doc --no-depsto verify they resolve. - Run
cargo clippy -- -W clippy::missing_errors_doc -W clippy::missing_panics_docto audit doc coverage.
Type Design
- Prefer newtypes over raw primitives when a value has a distinct semantic meaning (e.g.
Addr(u16)instead of rawu16). Seestate/types.rsfor the established pattern. - Derive
#[derive(Debug, Clone, Copy, PartialEq, Eq)]for all small value types. AddHashwhen the type is used as a map key,Ord/PartialOrdwhen ordering is needed. - Implement
Displayfor types shown to users; implementFrom/Intoconversions where they remove boilerplate. - Use
Defaultfor structs with sensible zero-values; use#[default]on enum variants rather than a manualDefaultimpl. - Avoid
boolparameters in public APIs; a two-variant enum is self-documenting and prevents argument-order bugs.
Ownership and Borrowing
- Prefer
&strover&String,&[T]over&Vec<T>, and&Pathover&PathBufin function signatures. - Use
impl Into<String>(orimpl AsRef<str>) for constructor arguments that store aString, asSystem::newdoes. - Avoid unnecessary
.clone()— pass references where ownership is not needed. - When passing closures that only forward to a free function (
|x| f(x)), writefdirectly (clippy::redundant_closure).
Collections
- Use
BTreeMap/BTreeSetfor address-keyed maps that must be iterated in order (deterministic output for project files). UseHashMap/HashSetonly when iteration order does not matter and performance is critical. - Prefer
.entry().or_default()overif !map.contains_key() { map.insert() }.
Formatting and Style
- Run
cargo fmtbefore committing (enforced by pre-commit hook and CI). - Prefer
write!(buf, "{x}")overbuf.push_str(&format!("{x}"))(clippy::format_push_string). - Use
format!capture syntax:format!("{x}")notformat!("{}", x)(Rust 2021+). matcharms that do nothing should use the_ => {}form, not_ => unreachable!()unless you are genuinely asserting the arm is unreachable.
Tests
- Every non-trivial function in
regenerator2000-coreshould have at least one unit test in the same file (#[cfg(test)]). - Integration tests live in
tests/and cover cross-module behavior (disassembler output, project serialization, MCP protocol). - Tests may freely use
.unwrap()/.expect()— the per-cratelib.rsallows this under#[cfg(test)]. - Use
AppState::new()(not a manually built struct) as the test baseline; it sets a safe throwaway config path that never touches the real user config.
Clippy Configuration
Lint policy is defined in [workspace.lints.clippy] in the root Cargo.toml. All crates inherit it via [lints] workspace = true in their own Cargo.toml — do not add per-crate [lints.clippy] blocks.
Currently enforced (error in CI via -D warnings):
| Lint | Category |
unwrap_used | Panic safety |
expect_used | Panic safety |
panic | Panic safety |
must_use_candidate | API hygiene |
missing_errors_doc | Documentation |
missing_panics_doc | Documentation |
Aspirational (run manually, apply to new code):
| Lint | Apply when |
needless_pass_by_value | Writing new functions |
redundant_closure | Writing closures |
Development Workflow
Commands
cargo build # Debug build
cargo run -- [file.prg] # Run with optional file
cargo test # Run all tests
cargo fmt -- --check # Check formatting
cargo clippy -- -D warnings # Lint (warnings are errors)Adding Features
- New Block Type: Add to
BlockTypeenum intypes.rs, updateanalyzer.rs, and add a shortcut ininput.rs. - New Assembler: Add to
Assemblerenum, implementFormattertrait indisassembler/formatter_*.rs. - New Command: Add variant to
Commandincommands.rs, implementapplyandundo. - New Packer: Create a new module file in
crates/regenerator2000-core/src/packers/<name>.rsimplementing adetect()function that returnsOption<Box<dyn Packer>>. For simple signature-only packers, instantiateSimplePacker::new(PackerInfo { ... }). For packers requiring pre-emulation memory patches, instruction step tracking, or post-emulation boundary overrides, define a custom struct implementing thePackertrait (pre_emulate,on_step,post_emulate). Finally, declarepub mod <name>;and registerif let Some(p) = <name>::detect(...) { return Some(p); }insidedetect_packer()insrc/packers/mod.rs, and add a signature unit test.
Git Commit Style
Use present tense, imperative mood (e.g., Add support for D71 disk images). Limit first line to 72 chars.
No Automatic Commits
Never create a git commit automatically after completing a task. Only commit when the user explicitly asks for it (e.g., "commit this", "create a commit"). Staged changes (git add) are acceptable as part of normal workflow, but the final git commit requires an explicit user instruction.
Testing
- Unit Tests: Located in
srcfiles (e.g.,cpu.rs). - Integration Tests: Located in
tests/directory. Use these for testing disassembler output, project serialization, and MCP functionality. - Verification: Always run
cargo testandcargo clippybefore finalizing changes.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

