Skip to content

feat(artifacts): inventory Nintendo 64 ROM images and normalize byte order offline - #14911

Merged
morluto merged 4 commits into
morluto:mainfrom
mvanhorn:fix/n64-rom-inventory
Nov 27, 2026
Merged

morluto merged 4 commits into
morluto:mainfrom
mvanhorn:fix/n64-rom-inventory

Conversation

@mvanhorn

Copy link
Copy Markdown
Contributor

Summary

Nintendo 64 cartridge dumps circulate in three byte orders: big-endian .z64, 16-bit byte-swapped .v64 and 32-bit little-endian .n64. REA does not recognize any of them today, so inspect-artifact cannot report the cartridge header or the boot-code (CIC/IPL3) variant, and a disassembler handed a swapped dump sees the wrong bytes.

This adds an n64-rom artifact format. inspect-artifact and extract-artifact recognize all three orders from the first word (the file name does not matter), report the header, name the IPL3 variant from its CRC32, recompute the cartridge CRC pair when the variant is known, and extract a big-endian program.z64 with header.bin and ipl3.bin. Nothing is executed or patched. No issue exists for this; it is a read-only format-inspection addition within the supported contribution scope.

Problem and expected behavior

Use case: given game.v64, find out what the cartridge is, which boot code it carries and whether its CRC pair is consistent, then get a big-endian image to open in a MIPS loader.

Observable outcome:

  • Root format_metadata (kind: "n64-rom") reports source_order, rom_bytes, clock_rate, boot_address, libultra_release, title_ascii and title_raw_hex, media, cartridge_id, destination code and name, and version, all read after normalizing to big-endian.
  • ipl3_crc32 names cic (6101, 6102/7101, 6103/7103, 6105/7105, 6106/7106 or unknown). For a known variant, crc is match or mismatch with the declared and computed pairs; otherwise it is not-checked. A mismatch is reported and the file is not corrected.
  • Entries are header.bin (64 bytes), ipl3.bin (0x40..0x1000, omitted when the file is shorter) and program.z64 (the whole ROM, big-endian). A z64 dump serves stored ranges; a v64 or n64 dump serves members decoded with one byte-order swap, and entry metadata says decoded: true.
  • A short checksum window, an unknown IPL3, a file shorter than 0x1000, non-zero reserved header bytes and a CRC mismatch are limitations, and coverage is unknown whenever one is present. A length that is not a multiple of 4 or an implausible boot address is refused. A file above 64 MiB is refused with the fixed allowance n64.rom_bytes.

Change and scope

  • src/domain/n64Rom.ts: byte-order detection and swap, recognition, header decoding, the IPL3 table, the CRC routines (including the 6105/7105 boot-code XOR) and limitations. A z64 input is returned without a copy.
  • src/artifacts/N64RomArtifactReader.ts: the positional reader. z64 members are stored ranges; v64 and n64 members are decoded on read.
  • src/artifacts/OwnedArtifactStream.ts: new decodedArtifactMemberSource, the cancellation wiring for a member whose bytes come from a decode step. SwitchExecutableArtifactReader had the same wiring inline; it now uses this helper, so both decoded-member readers share one owner. Switch behavior is unchanged and its tests pass.
  • Format registration: artifactFormats.ts, artifactFormatRecognition.ts, artifactFormatMetadata.ts, packageAndGameMetadata.ts, targetFormats.ts, artifactGraph.ts, artifactInventoryView.ts, ArtifactReader.ts and the PE overlay format list. compare-artifacts does not count source_order or decoded as a metadata change, so a z64 dump and a swapped dump of the same program compare as the same members.
  • Docs: new docs/guides/firmware/n64-roms.md, CLI examples in docs/getting-started/cli.md, docs/reference/limits-and-recovery.md, one row in docs/reference/supported-targets.md, the docs index and sidebar, and the skill references under .agents/skills/reverse-engineer-anything/ and .cursor-plugin/. The 64 MiB ceiling is registered in scripts/verify/fixed-ceiling-registry.json, and scripts/ci/scopes.mjs maps the new files.

Not included: loading program.z64 as MIPS inside REA. The Ghidra MIPS lane admits ELF only and raw-binary has no MIPS architecture; routing raw console images through an installed Ghidra language is the open design in #5657. The guide gives the facts for an external big-endian MIPS loader instead (map file offset 0x1000 at boot_address).

Contract and boundary impact

  • Semantic owner and earliest changed stage: n64Rom.ts interprets the header once after byte-order normalization; the reader, metadata and comparison consume its parsed facts.
  • Contribution scope fit and linked maintainer decision: read-only inspection of a local file; not applicable (no target execution, injection, mutation, or protection recovery). CRC mismatches are reported, never patched.
  • CLI and MCP/tool-catalog contract: no new tool or command. inspect-artifact, extract-artifact and compare-artifacts gain one format, n64-rom.
  • Provider, bridge, target-format, or platform compatibility: one new target format. The Switch NSO reader now calls the shared helper for the same cancellation behavior.
  • Evidence, artifact, provenance, or reconstruction contract: new n64-rom and n64-rom-entry metadata.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): not applicable.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact (CI generates and validates ignored catalogs and skills/; edit authored instructions in .agents/skills/reverse-engineer-anything/ and never commit build outputs): none committed; authored skill references updated under .agents/skills/reverse-engineer-anything/ and .cursor-plugin/.

Expected effects (check known effects; use documentation-only on its own).
Unchecked items do not establish absence; leave uncertainties visible.

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

  • Tests added or updated: src/domain/n64Rom.test.ts (13 tests: the three orders normalize to the same facts, CRC match and mismatch, the 6105/7105 XOR, a short checksum window, unknown IPL3, a file ending inside IPL3, non-zero reserved bytes, truncated header, odd length, implausible boot address, the 64 MiB ceiling), src/artifacts/N64RomArtifactReader.test.ts (7) and src/artifacts/N64RomArtifactReader.boundaries.test.ts (10, including cancelling a decoded v64 or n64 member before and during its read), plus entries in artifactFormatRecognition.test.ts, artifactComparison.test.ts, TargetFormatVocabularies.test.ts and tests/boundary/providers/native/artifactProvider.standaloneFormats.test.ts. Fixtures are built in src/domain/n64Rom.fixture.ts. The Switch NSO tests and OwnedArtifactStream.test.ts cover the shared helper's other caller.
  • Base reproduction or other evidence: on the base revision an N64 dump in any of the three orders falls through to plain-file classification with no header facts. The CLI output below is executed against this branch.
  • User-visible CLI/MCP output (if applicable): executed on synthetic 12,288-byte ROMs built with the fixture helpers in all three byte orders (no commercial ROM). The fixture's IPL3 is a test stub, so to show a named CIC and a CRC result the runs preloaded a module that registers that stub as 6102/7101, the same registration the unit tests use. Without it the built CLI reports cic: "unknown" and crc: not-checked for these files, which is the documented behavior for an unknown IPL3.

rea inspect-artifact game.v64 --json:

source_order "v64", title_ascii "DEMO CART           ", cartridge_id "RE"
destination_code "E", destination_name "North America", version 1
clock_rate 15, boot_address 2147484672 (0x80000400)
ipl3_crc32 1811869526, cic "6102/7101"
crc: status "match", declared_crc1 4240843240, computed_crc1 4240843240

game.z64 and game.n64 gave the same values except source_order.

rea extract-artifact game.v64 --json wrote header.bin (64 bytes), ipl3.bin (4032) and program.z64 (12288), each with kind: "n64-rom-entry", source_order: "v64", decoded: true. The extracted program.z64 has the same SHA-256 as game.z64 (bdc1acd0...).

rea inspect-artifact bad-crc.z64 --json reported crc.status: "mismatch" (declared_crc1 4240843241, computed_crc1 4240843240) with the limitation "Declared CRC1 0xfcc621e9 and CRC2 0x1c461555 differ from computed CRC1 0xfcc621e8 and CRC2 0x1c461555 for CIC 6102/7101."

rea inspect-artifact odd.z64 --json on a 12,289-byte file exited 1 with unsupported_target, file_format_rejected: "Nintendo 64 ROM length 12289 is not a multiple of 4, so byte order cannot be normalized".

  • Remaining proof gaps: no commercial ROM was used, so the published IPL3 table entries were not matched against a real boot image in this run. They are table data, and the CRC routines were exercised through the test stub.

Not a boundary fix. The new reader's boundary tests cover truncation, the size ceiling, the expansion budget and cancellation of decoded members.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Validation performed

  • npx vitest run on the N64, Switch, OwnedArtifactStream, recognition, comparison, vocabulary and standalone-format test files: 10 files, 241 tests passed.
  • npm run lint: passed. Its fixed-ceilings step accepts the new n64.rom_bytes entry.
  • node scripts/rea.mjs inspect-artifact and extract-artifact on the fixture-built ROMs: output as shown above.

Compatibility, safety, and release

  • Breaking changes or migration steps: none. decodedArtifactMemberSource is a new export; the Switch reader's cancellation behavior is unchanged.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable. The reader never invokes a disassembler or the OS loader; the runs above used Node 24 on an Apple silicon Mac.
  • Package or release metadata impact: one new artifact format.
  • Security, privacy, process, or containment review: reads a local file through bounded positional reads. The 64 MiB ceiling is checked before any swap, decoded members count toward artifact_limits.expanded_bytes before hashing, and decoded member streams honor caller cancellation.

AI was used for assistance.

Author readiness

Human owner: @mvanhorn

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Author checklist (completed by the PR author before requesting review)

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.
  • I ran every test, build, or measurement needed to validate this change, reported a browser, GPU, or environment gap only when that runtime or hardware is unavailable, and reported the checks I ran and their results without presenting inferred correctness or speedups as measured.
  • Comments explain constraints or non-obvious decisions; task history and conversations stay out of code and docs.
  • Documentation is concise and factual, without punchy slogans or promotional language.
  • This change fixes the root cause and follows the engineering rules in AGENTS.md.
  • Formatted input is interpreted once at the owning boundary, and consumers use the owner's parsed facts. See Interpret boundary facts once.
  • Combined failures preserve partial observations, remaining resources, and cleanup facts. See Own the lifecycle.
  • A hardcoded limit is an REA_ runtime setting with a default, floor, and maximum, unless a fixed ceiling has a stated reason. See Adding a runtime setting.

Demo

demo

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-27T18:07:56.098324Z cd0dfd5 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The reviewed code appears safe to merge, with no new actionable findings.RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[Medium impact] The reviewed code appears safe to merge, with no new actionable findings.

Summary

Adds offline Nintendo 64 ROM inspection and big-endian extraction for all three dump orders.

  • REA identifies Nintendo 64 ROMs and serves their contents in big-endian order.
  • Decoded artifact streams share one cancellation helper.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Local ROM] --> B[Detect byte order]
  B --> C[Check size and member allowance]
  C --> D[Normalize header and checksum bytes]
  D --> E[Report header, CIC, CRC and limitations]
  E --> F{Source order}
  F -->|z64| G[Serve stored ranges]
  F -->|v64 or n64| H[Swap member bytes]
  G --> I[Hash or extract members]
  H --> I
Loading

Reviews (4) · Last reviewed commit: "fix(n64): keep the present bytes of a fi..." · Reviewed by Greptile

Comment thread src/artifacts/N64RomArtifactReader.ts Resolved
Comment thread docs/guides/firmware/n64-roms.md Resolved
@morluto

morluto commented Nov 27, 2026

Copy link
Copy Markdown
Owner

Maintainer follow-up in 698a82b: both review threads are fixed, plus one more defect from a whole-PR review.

Fixed

  • Allowance before allocation (thread): artifact_limits.expanded_bytes is now charged from the file size and the 4-byte magic, before the checksum window is read or swapped. The member layout has one owner, n64RomRegions, which both the parser and the allowance use.

  • Length rule followed one fixed byte order: any length that wasn't a multiple of 4 was refused, whatever the order. Only the swap needs alignment, so the rule now follows each order's swap unit (N64_SWAP_UNIT):

    • z64 needs no swap, so any length is accepted;
    • v64 swaps 16-bit halves, so it needs an even length;
    • n64 reverses 32-bit words, so it needs a multiple of 4.

    This matches mupen64plus-core's is_valid_rom. Recognition, the reader and swapN64Bytes all share that one check.

  • Destination docs (thread): the code already kept the source byte and a null destination_name for unknown codes. The guide now says so.

Checked against reference implementations and left unchanged

  • Byte-order magics (80371240, 37804012, 40123780) and header offsets match mupen64plus-core (src/main/rom.c is_valid_rom and swap_copy_rom; src/api/m64p_types.h m64p_rom_header).
  • 0x3B as the media category code matches libdragon tools/n64tool.c (CATEGORY_OFFSET, codes N/D/C/E/Z).
  • CIC checksum:
    • Seeds (F8CA4DDC for 6101 and 6102, A3886759 for 6103, DF26F436 for 6105, 1FEA617A for 6106), the 0x1000..0x101000 window, the 6105 boot-code word at 0x750 + (offset & 0xFF), and the add combine for 6103 and multiply-add for 6106 all match Project64 Source/Project64-core/N64System/N64Rom.cpp (CalculateRomCrc).
    • Identification: Project64 identifies the CIC by a 64-bit sum of the IPL3 words, where this PR uses the IPL3 CRC32 table published with n64crc. Both are exact-match tables, and an unknown IPL3 stays unknown rather than being guessed.
  • Destination table: mupen64plus-core maps codes only to NTSC/PAL, so I couldn't cross-check the region names against a reference implementation. They are unchanged.

Not changed, for the maintainer to decide: the 64 MiB ceiling is registered with class format, but its reason is the retail mask size. The cartridge bus addresses more than that, and artifact_limits.expanded_bytes already bounds memory.

Validation: N64 and recognition source tests (129), the standalone-formats boundary test, build:cached, check:fast, oxfmt --check and docs:check pass. Each new regression fails on the previous code. Sources were read through DeepWiki (mupen64plus/mupen64plus-core, project64/project64, DragonMinded/libdragon).

Comment thread src/domain/n64Rom.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 698a82b397

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/domain/n64Rom.ts Resolved
@morluto

morluto commented Nov 27, 2026

Copy link
Copy Markdown
Owner

Brittleness pass, in 4ce9291.

Found and fixed

  • Magic numbers without a source:

    • The header offsets now live in one named table, N64_HEADER_FIELD, citing mupen64plus-core m64p_rom_header and libdragon n64tool.c for 0x3B.
    • The first-word magics are N64_MAGIC, from mupen64plus-core is_valid_rom.
    • The CIC 6105 table offset is N64_CIC_6105_TABLE_OFFSET (0x750), from Project64 CalculateRomCrc.
    • The KSEG bounds are named.

    The parser, the reserved-byte check and the fixture all use these constants.

  • Duplicated boot-address decision: recognition and the parser each read 0x08 and built the same refusal. They now share bootAddressFailure.

  • Duplicated layout and size decisions (from the earlier commit): n64RomRegions owns the member layout, and N64_SWAP_UNIT owns the length rule for each byte order.

  • A test that mirrored the implementation: the fixture writes its declared CRC with n64CartridgeCrc and the parser then checks it with the same function. A new test checks every CIC against a closed form derived from the checksum routine for an all-zero window. For example, t1 ends at seed × 0x40001; 6103 adds its accumulators and 6106 multiplies then adds.

Checked against sources

  • Destination table: matches Project64's Country enum (N64Types.h) and mupen64plus-core's NTSC/PAL classification. Project64 calls A "Asian NTSC" and X/Y "PAL"; this PR names them Asia and Europe. Neither source contradicts those names.
  • CIC seeds and combine steps: match Project64.
  • CIC identification: the IPL3 CRC32 values come from the n64crc table. Project64 identifies the CIC by a 64-bit word sum instead, so I couldn't confirm the CRC32 values against a second implementation. An IPL3 that doesn't match exactly still reports unknown.
  • The 0x3B media category: comes from libdragon. mupen64plus-core folds 0x38..0x3B into Manufacturer_ID without naming 0x3B, so that is consistent but not a second confirmation.

Left as is, deliberately

  • registerN64TestCic is a module-level registry that only tests write to. Passing the CIC table as a parameter would need to be threaded through the reader. No production caller registers, so I left it alone.
  • The 64 MiB fixed ceiling, as noted in my earlier comment.
  • Two lint warnings that were already there: the complexity of parseN64Rom, and the length of the test file's describe.

Validation: the N64 and recognition source tests, the standalone-formats boundary test, build:cached, check:fast and oxfmt --check pass. CI is running on 4ce9291.

Sources were read through DeepWiki: mupen64plus/mupen64plus-core, project64/project64 and DragonMinded/libdragon. Context7 had no N64 format sources.

mvanhorn and others added 3 commits November 27, 2026 09:28
…order offline

An n64-rom image is recognized from the first word in z64 (80 37 12 40),
v64 (37 80 40 12), or n64 (40 12 37 80) order plus a 4-byte-aligned boot
address in KSEG0 or KSEG1. The reader normalizes the cartridge header
and serves header.bin, ipl3.bin, and program.z64 in big-endian order,
swapping v64 and n64 bytes and recording that swap as decoded. It names
the IPL3/CIC variant from the CRC32 of bytes 0x40..0x1000 and, for a
known variant, recomputes the CRC pair over the 1 MiB window; a
mismatch, unknown CIC, short window, or non-zero reserved header bytes
leave coverage unknown, and a file above 64 MiB is refused before any
swap. Comparison ignores n64-rom and n64-rom-entry metadata so dump
order is not treated as a content change, and decoded members share the
idle-abort helper the Switch executable reader now calls.
…wap unit

Charge artifact_limits.expanded_bytes from the file size and byte order
before the checksum window is read and swapped. The member layout now has
one owner, n64RomRegions, which the parser and the allowance both use.

The length rule follows the order's swap unit, as in mupen64plus-core: a
z64 image of any length needs no swap, a v64 image needs an even length and
an n64 image a multiple of 4. The guide now says that a printable
destination byte outside the known table keeps its code with a null
destination_name.
…dress check

Header offsets, the first-word magics, the CIC 6105 table offset and the
KSEG bounds are now named constants with their reference sources, and
recognition and parsing share one boot-address decision. A closed-form
test checks the cartridge checksum on an all-zero window for every CIC,
derived from the checksum routine rather than from n64CartridgeCrc.
@mvanhorn
mvanhorn force-pushed the fix/n64-rom-inventory branch from 4ce9291 to ab30da5 Compare November 27, 2026 17:28
…sum window

The checksum routine now reads one defined window, n64ChecksumWindow: the
image through 0x101000 with only the bytes past a shorter file taken as
zero. A z64 or v64 image that ends inside a word keeps that word's bytes
instead of losing the whole word. The limitation now says how many bytes
were assumed.
@morluto
morluto enabled auto-merge (squash) November 27, 2026 18:15
@morluto
morluto merged commit 17b53ee into morluto:main Nov 27, 2026
57 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants