regenerator2000
AGENTS.md166 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 four workspace crates forming a one-way dependency DAG (regenerator2000 -> regenerator2000-tui -> regenerator2000-core -> regenerator2000-unpacker -> mos6502, with regenerator2000-tui also depending directly on regenerator2000-unpacker and regenerator2000 depending on both regenerator2000-core and regenerator2000-tui):
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 35,337 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
41 rules. About 0 are common, 2 are distinctive, and 39 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.
39
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 80
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 86
Never hardcode platform constants: Do not hardcode machine-specific memory addresses (such as $0800 RAM start, $0801 BASIC start, $0400 …
- Very specific: line 88
Keep Documentation System-Agnostic: When updating docs/unpacker.md or adding unpacker documentation, describe memory boundaries and …
- Very specific: line 114
All AI-generated code MUST follow the rules below.
- Very specific: line 118
Thin
mod.rsfiles: Keep non-leaf mod.rs files limited to module declarations, module doc comments (//!), and pub use re-exports. - Very specific: line 119
Flat
usestatements: Import items from one module per use statement — avoid nested use trees (write separate use … - Very specific: line 121
No glob imports in production code: Avoid use foo::*;. Glob imports are permitted only for facade re-exports (pub use error::*.
- Very specific: line 129
No check-then-unwrap or check-then-expect: Prefer pattern matching (if let Some(val) = ..., let Some(val) = ...
- Very specific: line 131
Use anyhow::Result for application-level errors where context strings suffice, and typed thiserror enums for library-facing error surfaces.
- Very specific: line 133
All three library lib.rs files gate these lints via:
- Distinctive: line 138
Do not remove these attributes.
- Very specific: line 142
Prefer ? over manual match/if let for error propagation.
- Very specific: line 143
Add context with .context("what was attempted") (from anyhow) when propagating errors across module boundaries.
- Very specific: line 144
Do not silently swallow errors with let _ = some_fallible_call();.
- Very specific: line 149
Add #[must_use] to every pure function (one with no side effects whose return value carries meaning).
- Very specific: line 150
Add #[must_use] to error, outcome, and small value types (such as CorpusError) when ignoring a returned instance is likely a bug.
- Very specific: line 154
Descriptive lifetimes on public types: Prefer named domain lifetimes ('app, 'ctx, 'mem, 'emu, 'cfg) over generic 'a on public structs …
- Very specific: line 155
Run cargo clippy -- -W clippy::must_use_candidate to find unannotated candidates in existing code.
- Very specific: line 163
Use shorthand intra-doc links (` [TypeName] ) to cross-reference types rather than redundant explicit targets such as EnumDefinition …
- Very specific: line 164
Run RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --all-features and cargo clippy -p regenerator2000-unpacker -p …
- Very specific: line 168
Prefer newtypes over raw primitives when a value has a distinct semantic meaning (e.g., Addr(u16) instead of raw u16).
- Very specific: line 173
Avoid
boolparameters in public APIs: Use descriptive two-variant enums instead (AssetReload, Reanalysis, ExternalXRefs, BlockItemTarget, … - Very specific: line 177
Prefer &str over &String, &[T] over &Vec<T>, and &Path over &PathBuf in function signatures.
- Very specific: line 178
Use impl Into<String> (or impl AsRef<str>) for constructor arguments that store a String, as System::new does.
- Very specific: line 179
Avoid unnecessary .clone() (clippy::redundant_clone) and redundant clone assignments (buf = src.clone(), clippy::assigning_clones) — pass …
- Very specific: line 181
When passing closures that only forward to a free function (|x| f(x)), write f directly (clippy::redundant_closure).
- Very specific: line 186
Use BTreeMap/BTreeSet for address-keyed maps that must be iterated in order (deterministic output for project files).
- Very specific: line 187
Prefer .entry().or_default() over if !map.contains_key() { map.insert() }.
- Very specific: line 191
Run cargo fmt --all before committing (enforced by pre-commit hook and CI).
- Very specific: line 192
Prefer .is_some_and(...) / .is_ok_and(...) over .map_or(false, ...) (clippy::manual_is_variant_and).
- Very specific: line 193
Prefer write!(buf, "{x}") over buf.push_str(&format!("{x}")) (clippy::format_push_string) and avoid .map(...).collect::<String>() …
- Very specific: line 194
Use inline format capture syntax (format!("{x}"), clippy::uninlined_format_args) rather than positional format!("{}", x).
- Very specific: line 199
Every non-trivial function in regenerator2000-core should have at least one unit test in the same file (#[cfg(test)]).
- Very specific: line 202
Avoid check-then-expect in tests: Do not write assert!(x.is_some()).
- Very specific: line 204
Use AppState::new() (not a manually built struct) as the test baseline.
- Very specific: line 256
New Block Type: Add to BlockType enum in types.rs, update analyzer.rs, and add a shortcut in input.rs.
- Very specific: line 257
New Assembler: Add to Assembler enum, implement Formatter trait in disassembler/formatter_*.rs.
- Very specific: line 258
New Command: Add variant to Command in commands.rs, implement apply and undo.
- Very specific: line 263
Use present tense, imperative mood (e.g., Add support for D71 disk images).
- Distinctive: line 267
Never: create a git commit automatically after completing a task.
- Very specific: line 273
Verification: Always run cargo test --workspace --all-features, cargo clippy --workspace --all-targets --all-features -- -D warnings, and …
≈ “Common” is an estimate: at least 1 in 5 of the 45,344 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 four workspace crates forming a one-way dependency DAG (regenerator2000 -> regenerator2000-tui -> regenerator2000-core -> regenerator2000-unpacker -> mos6502, with regenerator2000-tui also depending directly on regenerator2000-unpacker and regenerator2000 depending on both regenerator2000-core and regenerator2000-tui):
regenerator2000-unpacker(crates/regenerator2000-unpacker/): Standalone 6502 emulation binary unpacker and 26-family packer detector (mos6502,thiserror,log).system.rs: Closed#[non_exhaustive]TargetMachinehardware profile enum (Copy),IrqVector,default_machine(), and platform memory-map helpers (ram_start,default_basic_start,screen_ram,default_irq,is_c64, etc.).roms.rs: Optional embedded C64 ROM blobs (C64_BASIC_ROM,C64_KERNAL_ROM,C64_CHAR_ROM, gated behind the defaultembedded-romsfeature) and zero-copydefault_*_rom(TargetMachine) -> Option<&'static [u8]>helpers.basic.rs: Commodore BASICSYStoken parser (find_sys_address).error.rs:UnpackErrorenum.bus.rs,cia.rs,machine.rs,engine.rs,detector.rs,runner.rs: 2-phase 6502 emulation unpacker sandbox (UnpackConfigwithtarget_machineandOption<Cow<'static, [u8]>>ROM overrides,UnpackResult,unpack,UnpackReport, andBoundSource).packers/: Declarative 6502 binary packer specifications (PackerSpec,Signature,Hints,MemoryPatch,PackerHooksinspec.rs,PackerInfoininfo.rs, and the orderedREGISTRYinregistry.rs).
regenerator2000-unpacker-corpus(crates/regenerator2000-unpacker-corpus/,publish = false): Internal differential corpus test harness (tests/unpack_corpus.rs) andunpacker_compare_allbenchmark CLI againstunp64(src/bin/unpacker_compare_all/{corpus/constants.rs,unp64/runner.rs}).regenerator2000-core(crates/regenerator2000-core/): Contains all UI-agnostic reverse-engineering and state logic (no directmos6502dependency).action_handlers/: Modular domain action handlers (context.rs[ActionContext,DisassemblyViewAnchor,DomainActionHandler],file_handler.rs,disassembly_handler.rs,debug_handler.rs,navigation_handler.rs).analyzer.rs: Auto-analysis (walking code, generating labels, building typed cross-references).assets.rs: System asset loading (labels, comments, exclude lists) and C64 ROM re-exports/delegation toregenerator2000-unpacker.commands.rs: TheCommandenum andUndoStack. Every undoable action is a command.config.rs: System-wide configuration management.core.rs: Central orchestration logic (CorecombiningAppStateandCoreViewState, andapply_actiondispatch).cpu.rs: 6502 opcode table, addressing mode logic, andOpcode::xref_kind().disassembler/: 6502 decoding, sharedDisassemblyLinegeometry/lowering (line.rs,context.rs),Disassemblerengine (engine.rs,pipeline.rs,symbols.rs,data_blocks.rs,handlers.rs), and assembler formatters (formatter_*.rs: 64tass, ACME, KickAssembler, ca65).error.rs: Typedthiserrorerror hierarchy (CoreError, wrapping re-exportedUnpackError).event.rs: Application event types (CoreEvent,DialogType).exporter/: 3-stage Exporter IR pipeline (ir.rs), pure ASM/HTML backends (asm.rs,html.rs), and roundtrip verification (verify.rs).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.parser/: File format parsers (.prg, .d64/.d71/.d81, .t64, .crt, .vsf snapshots, .dis65, VICE labels;basic.rsdelegatesfind_sys_addresstoregenerator2000-unpacker).state/: Persistent application state (AppState), sparseAnnotationManager, domain types (TargetSystemdelegating hardware queries toTargetMachine), and project serialization.utils.rs: Shared utility functions.vice/: VICE binary monitor protocol client for live debugging.view_state.rs: View state management (CoreViewState).
regenerator2000-tui(crates/regenerator2000-tui/): Contains all terminal UI-related code.ui/: Top-level frame composition (render.rs, re-exported via thinmod.rs), TUI widgets (widget.rs,navigable.rs,minimap_bar.rs,statusbar.rs,scoped_input.rs), top menu (menu/:menu_model.rs,menu_render.rs,menu_action.rs,menu_widget.rs, thinmod.rs), views (view_disassembly/submodule breakdown [layout.rs,navigation.rs,mouse.rs,render.rs,view.rs,mod.rs], HexDump, Sprites, Charset, Bitmap, Blocks, Debugger), and modal dialogs (dialog_*.rs, including unifiedFileBrowserDialog,PromptDialog,ContainerPickerDialog, and table-drivenDocumentSettingsDialog).ui_state.rs: Transient UI state (cursor, scroll, active dialog, wrappingCoreViewStateviaDeref).events/: Event loop (runner.rs), event enum (app_event.rs), global input mapping (input.rs), background MCP coordination (mcp.rs), and VICE monitor integration (vice.rs), re-exported via thinmod.rs.terminal_graphics.rs: Terminal image protocol probing, Kitty/iTerm2/Sixel helpers, and headless picker setup.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.TargetSystem(Systemalias): Target machine (C64,C128,Vic20,Pet20,Pet40,Plus4,C16,C1541,C1571,C1581,Custom).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,Return,Pointer,ZeroPagePointer,Field,ZeroPageField,AbsoluteAddress,ZeroPageAbsoluteAddress,ExternalJump,Predefined,UserDefined,LocalUserDefined).XRef/XRefKind: Typed cross-reference edge (from: Addr,kind: XRefKind—Read,Write,ReadModifyWrite,Call,Jump,Offset).
State Management
AppState(crates/regenerator2000-core/src/state/app_state.rs): The single source of truth for persistent data. Includesraw_data,block_types,labels,annotations(AnnotationManagerconsolidating comments, immediate value formats, bookmarks, scopes, and enum usages),undo_stack,settings,cross_refs(BTreeMap<Addr, Vec<XRef>>), andsplitters. Serialized to.regen2000proj.UIState(crates/regenerator2000-tui/src/ui_state.rs): Transient state like cursor positions, scroll offsets, and active dialogs (wrappingCoreViewState). Never serialized.
Application Logic Flow
Regenerator 2000 follows a unidirectional data flow (Redux/Elm style):
- Input:
crates/regenerator2000-tui/src/events/input.rsandWidget::handle_inputmap key events toAppAction(MenuAction). - Dispatch:
handle_menu_action(crates/regenerator2000-tui/src/ui/menu/menu_action.rs) forwardsAppActiontoCore::apply_action, which delegates toaction_handlers/and converts actions intoCommandvariants andCoreEventnotifications. - Execution:
Command::apply(&mut AppState)modifies the state and pushes toUndoStack. - Analysis:
AppState::perform_analysis()(viaanalyzer.rs) updates labels and typed cross-references (XRef). - Render:
ui()incrates/regenerator2000-tui/src/ui/render.rs(re-exported fromui/mod.rs) re-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-unpacker/src/ 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 incrates/regenerator2000-unpacker/src/or documentation. Always query machine properties viaTargetMachinemethods (machine.ram_start(),machine.default_basic_start(),machine.screen_ram(),machine.default_irq(),machine.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 machine.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 & Subagents (.agent/)
Specialized agents (.agent/agents/) and skills (.agent/skills/) are available for common tasks:
Custom Agents (.agent/agents/)
r2000-cbm-principal-swe: Commodore 8-Bit (CBM) and MOS 6502 Principal Systems, Demo-Coding, and Reverse-Engineering agent (r2000_cbm_principal_swe.md). Used by ther2000-analyze-*skills and for 6502 assembly tasks.
Skills (.agent/skills/)
r2000-analyze-basic: Analyze BASIC programs and mark pointers (usesr2000-cbm-principal-swe).r2000-analyze-blocks: Auto-detect and set block types (text, data) (usesr2000-cbm-principal-swe).r2000-analyze-program: Orchestrate 2-tier MapReduce full-program analysis usingr2000-cbm-principal-swesubagents across BASIC, blocks, routines, and symbols.r2000-analyze-routine: Trace a subroutine and mark code paths (usesr2000-cbm-principal-swe).r2000-analyze-symbol: Find and label all references to a specific address (usesr2000-cbm-principal-swe).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.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 workspace enforces baseline lints through cargo clippy -- -D warnings; violations will block CI.
Module Layout and Imports
- Thin
mod.rsfiles: Keep non-leafmod.rsfiles limited to module declarations, module doc comments (//!), andpub usere-exports. Place structs, traits, implementations, and unit tests in named leaf submodules (e.g.,action_handlers/context.rs,disassembler/engine.rs,disassembler/line.rs,packers/info.rs,crates/regenerator2000-unpacker/src/runner.rs,bin/unpacker_compare_all/{corpus/constants.rs,unp64/runner.rs},events/runner.rs,ui/render.rs,ui/menu/menu_widget.rs, andui/view_disassembly/view.rs). - Flat
usestatements: Import items from one module perusestatement — avoid nestedusetrees (write separateuse std::collections::BTreeMap;anduse std::fs;imports rather thanuse std::{collections::BTreeMap, fs};). Grouping sibling items from the same module in{...}is fine (e.g.,use crate::state::{Addr, AppState};). - Import types; avoid inline multi-segment paths: Import types, traits, and enums at module scope (or inside
#[cfg(test)] mod tests) and refer to them unqualified (Range<usize>,HashSet<Addr>,Path). Qualify free functions with their parent module when it improves clarity or avoids name collisions (fs::read,analyzer::analyze,navigation::resolve_jump_content_line_index,basic::find_sys_address). Exceptions: disambiguating shadowed prelude names (std::result::Resultwherecrate::Resultis in scope) and$crate::...paths insidemacro_rules!. - No glob imports in production code: Avoid
use foo::*;. Glob imports are permitted only for facade re-exports (pub use error::*;inlib.rs,pub use ...::*;instate/mod.rs) anduse super::*;inside#[cfg(test)] mod tests.
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. - Never use
std::panic::catch_unwindfor control flow or error recovery. - No check-then-unwrap or check-then-expect: Prefer pattern matching (
if let Some(val) = ...,let Some(val) = ... else { ... };) over checking.is_some()/.is_ok()followed by unwrapping or.expect(). - 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.- All three library
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 and Naming
- 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. - Add
#[must_use]to error, outcome, and small value types (such asCorpusError) when ignoring a returned instance is likely a bug. - 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.- No
get_prefix on public getters: Name simple getters after the concept (opcodes(),pointer(),formatter(),line_index_for_address(),hardware_name(),basic_start()). Use descriptive verbs (parse_*,find_*,resolve_*) for fallible parsing or non-trivial lookups (e.g.,parse_address_arg). - Descriptive lifetimes on public types: Prefer named domain lifetimes (
'app,'ctx,'mem,'emu,'cfg) over generic'aon public structs holding borrowed references (ActionContext<'app>,DisassemblyContext<'app>,HandleArgs<'ctx>,LoadedImage<'mem>,StepContext<'emu>,UnpackEngine<'cfg>). - Run
cargo clippy -- -W clippy::must_use_candidateto find unannotated candidates in existing code.
Documentation
- All
pubitems inregenerator2000-unpacker,regenerator2000-core, andregenerator2000-tui— including modules (//!), structs, struct fields, enums, enum variants, functions, and constants — must have doc comments (///). - Functions returning
Resultmust include a# Errorssection explaining when they fail. - Functions that can panic (outside tests) must include a
# Panicssection. - Wrap code identifiers, CamelCase names (e.g.,
`AppState`,`KickAssembler`), hex addresses ($0801), flags, and file paths in backticks (clippy::doc_markdown). - Use shorthand intra-doc links (
[`TypeName`]) to cross-reference types rather than redundant explicit targets such as[`EnumDefinition`](EnumDefinition)(rustdoc::redundant_explicit_links). - Run
RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --all-featuresandcargo clippy -p regenerator2000-unpacker -p regenerator2000-core -p regenerator2000-tui --all-targets --all-features -- -D warnings -D missing_docs -D clippy::doc_markdownto verify doc links, doc-tests, and 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. - Prefer named structs over multi-element tuples in public APIs: Define small documented structs with named fields instead of returning or accepting unlabeled tuples (
AddrSpan,OffsetSpan,IrqVector,EffectiveTarget,DecodedPacket,ParsedCrt,ExpandedBlocks,AnalysisOutcome,DetectedPacker,ResolvedEnumValue,ViceLabel). - 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 standard library traits (
Display,From/TryFrom,Error) where appropriate instead of custom conversion or formatting methods. - Implement
Defaultfor options/config structs (UnpackConfig,DocumentSettings); use#[derive(Default)]and#[default]on enum variants when zero-values apply, or an explicitDefaultimpl for non-zero defaults. - Avoid
boolparameters in public APIs: Use descriptive two-variant enums instead (AssetReload,Reanalysis,ExternalXRefs,BlockItemTarget,LabelLocality,PetsciiCharset,TrimMode) so call sites are self-documenting and cannot transpose arguments.
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()(clippy::redundant_clone) and redundant clone assignments (buf = src.clone(),clippy::assigning_clones) — pass references or borrow slices where ownership is not needed. - Pass borrowed views or references instead of unused owned values (
clippy::needless_pass_by_value). - When passing closures that only forward to a free function (
|x| f(x)), writefdirectly (clippy::redundant_closure). - Provide explicit type annotations when type inference would obscure a non-obvious type (such as
.collect()destination types).
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 fmt --allbefore committing (enforced by pre-commit hook and CI). - Prefer
.is_some_and(...)/.is_ok_and(...)over.map_or(false, ...)(clippy::manual_is_variant_and). - Prefer
write!(buf, "{x}")overbuf.push_str(&format!("{x}"))(clippy::format_push_string) and avoid.map(...).collect::<String>()formatting loops (clippy::format_collect). - Use inline format capture syntax (
format!("{x}"),clippy::uninlined_format_args) rather than positionalformat!("{}", x). 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, unpacker corpus). - Prefer
.expect("reason")/.expect_err("reason")over.unwrap()/.unwrap_err()in all unit tests, integration tests, and doc-tests (#![cfg_attr(test, allow(...))]exempts tests from clippy errors, so write clear failure context rather than bare unwraps). - Avoid check-then-expect in tests: Do not write
assert!(x.is_some()); let v = x.expect(...);— call.expect("...")directly or pattern match. - Add context strings to non-obvious assertions (
assert!,assert_eq!), especially inside loops or table-driven test cases. - 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 / Readability Checks (apply to new code, enforced via -D on regenerator2000-unpacker, regenerator2000-core, and regenerator2000-tui readability passes):
| Lint | Category / Apply when |
missing_docs | Public API docs in regenerator2000-unpacker, regenerator2000-core, and regenerator2000-tui |
clippy::doc_markdown | Backtick code/identifiers in doc comments |
clippy::redundant_clone | Unnecessary .clone() calls |
clippy::assigning_clones | Reassigning via .clone() instead of clone_from / slice copy |
clippy::needless_pass_by_value | Writing new functions taking unused owned params |
clippy::manual_is_variant_and | Boolean checks on Option / Result |
clippy::uninlined_format_args | Format string readability |
clippy::format_collect | Building strings in loops (write! instead) |
clippy::redundant_closure | Passing single-arg closures (f instead of |x| f(x)) |
Development Workflow
Commands
cargo build # Debug build
cargo run -- [file.prg] # Run with optional file
cargo test --workspace --all-features # Run all workspace unit, integration, and doc tests
cargo fmt --all -- --check # Check formatting
cargo clippy --workspace --all-targets --all-features -- -D warnings # Workspace lints (warnings are errors)
RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --all-features # Verify rustdoc builds and intra-doc links
cargo clippy -p regenerator2000-unpacker -p regenerator2000-core -p regenerator2000-tui --all-targets --all-features -- \
-D warnings -D missing_docs -D clippy::doc_markdown \
-D clippy::redundant_clone -D clippy::assigning_clones \
-D clippy::needless_pass_by_value -D clippy::manual_is_variant_and \
-D clippy::uninlined_format_args -D clippy::format_collect # Strict readability lint passAdding 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-unpacker/src/packers/<name>.rsdefiningpub static SPEC: PackerSpecwith declarativeSignaturepatterns (Anchor,sig!),Hints(AddrSource), optionalpatches(MemoryPatch), optionalresolveescape hatch (fn(&LoadedImage<'_>, &SignatureMatch) -> Option<ResolvedSpec>), optionalhooksfactory (PackerHookswithStepContextandRefineContext), and a syntheticfixture(fixture_load_addr). Exportpub mod <name>;insrc/packers/mod.rs, register&<name>::SPECin ascendingpriorityorder inREGISTRYinsrc/packers/registry.rs, add a unit test, and (when a real packed.prgfixture is available) add a[[case]]entry totests/6502/unpack_corpus.toml, record itsunp64reference withcargo run -p regenerator2000-unpacker-corpus --bin unpacker_compare_all -- --update, and updatetests/6502/unpack_baseline.toml(UPDATE_UNPACK_BASELINE=1 cargo test -p regenerator2000-unpacker-corpus --test unpack_corpus).
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/(workspace root),crates/regenerator2000-unpacker/tests/(unpacker_fuzz_test.rs), andcrates/regenerator2000-unpacker-corpus/tests/(unpack_corpus.rs). Use these for testing disassembler output, project serialization, MCP functionality, and unpacker corpus/fuzz behavior. - Verification: Always run
cargo test --workspace --all-features,cargo clippy --workspace --all-targets --all-features -- -D warnings, andRUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps --all-featuresbefore 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.

