Skip to content

feat(artifacts): inventory and extract UF2 and DfuSe firmware containers - #8230

Merged
morluto merged 8 commits into
morluto:mainfrom
Entrpi:feat-artifacts-uf2-dfuse
Oct 31, 2026
Merged

morluto merged 8 commits into
morluto:mainfrom
Entrpi:feat-artifacts-uf2-dfuse

Conversation

@Entrpi

@Entrpi Entrpi commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

REA cannot read the two drag-and-drop and DFU update containers that most microcontroller firmware ships in. UF2 is the format of the RP2040 and RP2350 bootloaders, of TinyUF2 on ESP32-S2 and ESP32-S3, of LibreTiny's module builds, and of esptool merge-bin --format uf2. DfuSe (.dfu) is ST's DFU update container. open_binary refuses both as an unsupported format, so an analyst cannot see which bytes such a file writes to which addresses.

This PR adds two artifact formats, uf2 and dfuse, to the existing inspect_artifact and extract_artifact tools. They follow the region model that #7136 landed for Intel HEX and S-record: each address-contiguous region is an extractable inventory entry with region metadata. A DfuSe suffix CRC mismatch follows the existing integrity_policy.

Part of the embedded roadmap #7955. Refs #7478 (the format vocabularies this PR extends).

Problem and expected behavior

  • Before: on main (d48e472fa), rea inspect-artifact <file> --json on an esptool v4.12.0 merge_bin --format uf2 output, and on a two-target DfuSe file, both exit 1 with "code": "target_unavailable", "category": "unsupported_target", "Cannot open artifact: unsupported binary format." and "constraint": "file_format_rejected".
  • After: the UF2 file opens as a uf2 archive with one region per familyID and address range; the DfuSe file opens as a dfuse archive with one region per element. Extraction writes each region's bytes.

Change and scope

  • Domain (src/domain/firmware/, pure and Result-based): uf2.ts joins valid main-flash block payloads into address-contiguous regions per familyID and counts block numbering. dfuse.ts parses the prefix, targets, elements and DFU suffix, and computes the suffix CRC. uf2Families.ts names 32 family IDs from microsoft/uf2 utils/uf2families.json at cf3bd7f9 (MIT; notice preserved), including 8 that LibreTiny builds for; other IDs keep their value only. addressRuns.ts and regionDecoder.ts replace HEX's private run merging and failure types.
  • Reader: DecodedRegionArtifactReader takes over the retained-region plumbing that HexRecordArtifactReader owned (streams, cancellation, close, carrier identity). HEX, UF2 and DfuSe readers are thin subclasses with format adapters.
  • Format registry (refactor(artifacts): describe formats in one registry #8054): both formats get the HEX capabilities and one reader limitation each.
  • Recognition is by strong magic only, after HEX and S-record and before ESP images and FIT. UF2 needs a complete first block with all three magic numbers. DfuSe needs the version 1 DfuSe prefix and a DFU 1.1a suffix; the CRC is not part of recognition, and classification reads the file's last 16 bytes.
  • UF2 regions are family-0x<id>/0x<start>-0x<end>.bin, one address space per family. Out-of-order blocks are sorted, identical rewrites count as duplicate_bytes, and a conflicting rewrite fails the file, as in HEX. Invalid, partial, not-main-flash and file-container blocks are excluded and reported; MD5 and extension-tag blocks are counted, not decoded. Numbering is grouped by familyID and block count, and each block number records the addresses it was seen at, because esptool numbers each merged input from 0. Missing or ambiguous numbering makes coverage unknown.
  • DfuSe regions are target-<t>/element-<e>-0x<start>-0x<end>.bin: one entry per element at its file range, with its target's alternate setting and name. Overlaps within one alternate setting are named, and structural faults fail with a byte offset. DFUImageSize may include the suffix or not, because producers disagree. compare_artifacts treats the alternate setting and target name as a declaration, so the same bytes moved to another device memory are changed.
  • Integrity: a CRC mismatch follows integrity_policy. fail refuses with artifact_integrity_mismatch (algorithm: "dfu-crc32"); record-and-continue marks the root mismatched with a dfu-crc32 contradiction that extraction carries.
  • Limits: 128 MiB per file, as for HEX ([Enhancement] Make hard-coded admission ceilings configurable with documented defaults #6176 tracks configurable ceilings); at most 65,536 UF2 regions and 65,536 DfuSe elements with bytes.
  • Docs: docs/uf2-dfuse.md, linked from the existing guides and the skill; the lane in docs/testing.md; container contradictions in docs/mcp-contracts.md; notices for the family names.
  • Not included: MD5 region checks, extension tags, UF2 file-container reconstruction, plain DFU suffix files, CRC checks for nested DfuSe files, and raw-binary or Ghidra loading of regions.

Deliberate choices reviewers may question:

  • Invalid UF2 blocks are excluded, not fatal, because each block carries its own framing and address. A malformed HEX record still fails its file.
  • The UF2 MD5 structure is not verified. It describes device flash for a flasher, not the block's file bytes, and esptool v4.12.0 and v5.6.0 do not place it where the specification says.
  • The root carries no declared_integrity, which holds entry digests; the DFU CRC lives in the contradiction and in format_metadata.
  • family_name is an REA label; family_id is the fact, and the root records family_name_registry.

Contribution scope: reads local files only, inside the existing artifact tools; no execution, injection, mutation or protection recovery. Not applicable.

Contract and boundary impact

  • Semantic owner and earliest changed stage: uf2.ts and dfuse.ts own recognition and decoding; artifactFormats.ts owns both formats' capabilities; scanReader.ts applies the integrity policy to a reader's containerIntegrity(). Resolution, classification, inventory, extraction, inspection and comparison consume them. Superseded: HEX's private stream and merge code and four identical failure types.
  • Contribution scope fit and linked maintainer decision: not applicable.
  • CLI and MCP/tool-catalog contract: format values uf2 and dfuse; format_metadata kinds uf2, uf2-region, dfuse and dfuse-element; a dfu-crc32 variant in the inventory and inspection contradiction schemas and the artifact_integrity_mismatch details (docs/error-contract.schema.json regenerated). No new inputs. Against d48e472fa, tools/list grows by 16,998 bytes (+0.44%) in the default profile and 17,586 bytes (+0.39%) with full input schemas, almost all in output schemas; by 14 bytes with compact output schemas.
  • Provider, bridge, target-format, or platform compatibility: two new archive target formats; no provider is involved.
  • Evidence, artifact, provenance, or reconstruction contract: Evidence, snapshots and bundles can carry the new values, which older REA versions cannot parse (closed enums and unions; derived from the source). Compatibility decision requested: CONTRIBUTING.md requires an explicit decision for persisted formats. Please decide whether this addition is acceptable as is and whether it needs a release note.
  • Target selection, authority, upstream behavior, and cleanup details: files that pass recognition, which open_binary refused, now resolve as uf2 or dfuse archives.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact: none. New optional npm run verify:uf2 lane.

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

Real tools. npm run verify:uf2 ran on df4154b4c with esptool v4.12.0 (the ESP-IDF v5.5.2 environment) and with v5.6.0, on macOS. It builds UF2 files with esptool merge-bin --format uf2 from inputs at known addresses. Inspection and extraction through the built CLI must return every input, byte for byte, at its address and under the familyID that esptool reports. Both runs passed:

Case What it covers
ESP32-S3, 4 inputs, MD5 on 452-byte payloads; an input that is not word-aligned; two equal-count inputs in one numbering group
ESP32-S2, --chunk-size 256 --md5-disable TinyUF2-style output
Concatenation of the two A two-family file
The ESP32-S3 file minus one block of an equal-count input Coverage unknown, with one ambiguous numbering group

Hand-built fixtures. Builders written from the UF2 specification and ST UM0391 back the other tests. Two DfuSe fixtures are byte-identical, CRC included, to the output of the build() functions of dfu-util's dfuse-pack.py (f9a537c9) and MicroPython's tools/dfu.py (cb99ca98), one per DFUImageSize convention. Those functions were transcribed and run under Python 3; the scripts were not run.

  • Tests added or updated: domain tests for UF2 (16) and DfuSe (17), reader tests (5 and 6), compiled-CLI acceptance tests (4) and stdio MCP tests (3), plus rows in artifactFormats.test.ts, test: guard target format vocabularies and DOL snapshot saves #7481's TargetFormatVocabularies.test.ts, binaryTarget.test.ts and ArtifactGraphConstruction.test.ts. They cover malformed and partial input, accepted boundaries beside refusals, 65,536 regions or elements accepted and one more refused, 65,537 empty DfuSe elements counted with only four named, forged entries and changed carriers, both integrity policies, and comparison. Reader lifecycle stays covered by HexRecordArtifactReader.test.ts, which now runs the shared reader.

  • Base reproduction or other evidence: with main d48e472fa built, node scripts/rea.mjs inspect-artifact refused an esptool v4.12.0 ESP32-S3 UF2 and a two-target DfuSe file, as quoted above; df4154b4c opens both. On e9a77ba0c, before the merge with main, 11 mutations of the owning code each failed their tests; they were not repeated after the merge. On df4154b4c, removing one LibreTiny row fails the new naming test.

  • User-visible CLI/MCP output (if applicable), from df4154b4c and trimmed: the esptool v4.12.0 ESP32-S3 file, and a DfuSe element.

    { "logical_path": ".", "format_metadata": { "kind": "uf2", "block_count": 12,
        "md5_block_count": 12, "family_count": 1, "numbering_group_count": 3,
        "missing_block_count": 0, "region_count": 3, "data_bytes": 4572 } }
    { "logical_path": "target-0/element-0-0x08000000-0x0800000f.bin",
      "source_location": { "offset": 293, "length": 16 },
      "format_metadata": { "kind": "dfuse-element", "alternate_setting": 0,
        "target_name": "Internal Flash", "start_address": 134217728, "length": 16 } }
  • Remaining proof gaps: no Pico SDK, picotool, uf2conv.py, TinyUF2, MakeCode or LibreTiny ltchiptool output was run; RP2040 and RP2350 cases are hand-built, and the LibreTiny names come from the registry only. No real DfuSe producer was run. No device accepted any file. The lane ran on macOS only and is not in CI.

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

Run on macOS (Darwin 25.5.0, arm64) with Node 24.22.1.

On the head 1f935949f, which bounds what the DfuSe decoder keeps for declarations without bytes:

  • npm run check:fast, format:check, docs:check (with dist/ built from this tree) and verify:module-boundaries — passed.
  • npx knip — no findings.
  • npm run test:focused -- with the 7 DfuSe-related files (dfuse.test.ts, DfuSeArtifactReader.test.ts, HexRecordArtifactReader.test.ts, ArtifactGraphConstruction.test.ts, binaryTarget.test.ts, firmwareContainersCli.test.ts and firmwareContainersMcp.test.ts) — 174 tests passed, 1 skipped.
  • A one-off decode of a 32 MB DfuSe file with 4,000,000 empty elements: on df4154b4c it ran out of memory under a 128 MB V8 heap limit, and with the default heap it peaked at 1.59 GB RSS. On 1f935949f it completes under the 128 MB limit in 114 ms with a 220 MB peak, and reports the same count and limitation text. One run each, on a shared host.

On df4154b4c, which merges main d48e472fa:

  • npm run check:fast, format:check, docs:check (with a fresh dist/ build) and verify:module-boundaries — passed.
  • npx knip — no findings.
  • npm run test:focused -- with 100 files — 99 passed and 1 skipped (firmwareMcp.test.ts runs on Linux only); 1,173 tests passed and 6 skipped. The files are this PR's tests, the tests of the modules it changes, the ESP image, FIT, uImage and HEX reader, CLI and MCP tests, and the tests/conformance/contracts files.
  • npm run verify:uf2 — passed with esptool v4.12.0 and with v5.6.0. The lane exercises UF2 only, so it was not re-run for the DfuSe fix.

The merge commit d73b1b969 passed the same checks and focused files before the LibreTiny names were added.

Compatibility, safety, and release

  • Breaking changes or migration steps: none for current versions. Older versions cannot read Evidence that contains the new values; see the compatibility decision requested above.
  • Merge order with the comparison table: whichever of this PR and the comparison-table PR (branch fix-artifacts-comparison) merges second adds table entries for dfuse-element and its sibling kinds uf2, uf2-region and dfuse, as the fork's integration branch already does.
  • Real Hopper/Ghidra, browser, or OS coverage: none applies, because the readers start no provider. The only real-tool lane is verify:uf2 (esptool), on macOS arm64 only.
  • Package or release metadata impact: one npm script; release notes depend on the decision above.
  • Security, privacy, process, or containment review: the readers read the selected file only, start no process, and keep decoded bytes within the 128 MiB ceiling until they close. The lane runs caller-supplied esptool in a temporary directory as owned process trees, and removes the directory afterwards.

Author readiness

Human owner: @Entrpi

  • 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.

Before merge

  • 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.

open_binary refused UF2 and DfuSe firmware containers as an unsupported
format, so inspect_artifact and extract_artifact could not show which
bytes a drag-and-drop or DFU update writes at which addresses.

UF2 is recognized by a complete first block with all three magic
numbers. Valid main-flash payloads are joined into address-contiguous
regions per familyID, named family-0x<id>/0x<start>-0x<end>.bin, and
known IDs are named from a small table copied from Microsoft's
uf2families.json at a pinned commit. Numbering is counted per familyID
and block count: absent, repeated, out-of-order and out-of-range block
numbers are reported, and absent blocks leave coverage unknown.
Not-main-flash blocks are excluded and reported; file-container blocks
are reported and leave coverage unknown; invalid blocks and a partial
final block are excluded with their position. A rewrite of one address
with different bytes fails closed, naming both block spans.

DfuSe is recognized only by its prefix together with a DFU 1.1a suffix.
Each element becomes one region at its file range with its target's
alternate setting and name. Structural faults fail closed with a byte
offset; overlapping elements stay separate and are reported. A suffix
CRC mismatch follows integrity_policy: fail refuses with a dfu-crc32
integrity error, and record-and-continue records a root contradiction
that extraction also carries.

HEX, UF2 and DfuSe share one retained-region reader and one run
merger, so the HEX decoder and reader lose their private copies.
Describe recognition, region names, metadata, numbering, failures, the
DfuSe suffix CRC under integrity_policy, and limits, and link the page
from the CLI and firmware guides and the agent skill reference.

npm run verify:uf2 runs esptool merge-bin --format uf2 on generated
inputs at known addresses, with and without MD5, with 256-byte
payloads, and on a concatenation of two chips' outputs. Inspection and
extraction through the built CLI must return every input at its address
under the familyID esptool itself reports.
UM0391 calls DFUImageSize the file length, and dfu-util's dfuse-pack.py
writes that value, while ST's DfuFileMgr, MicroPython's dfu.py and pydfu
leave the 16-byte suffix out. The decoder accepted only the second form,
so it refused dfuse-pack.py output as malformed.

Accept either value and keep the declared one in image_size; any other
value still fails with the suffix offset and the file length. The tests
pin both producers' output for one image, CRC included, from their
build() functions transcribed and run under Python 3.
esptool numbers every merged input from 0, so two inputs with the same
block count share one numbering group. A block lost from one input left
its number present in the other, and the file reported complete
coverage. Each block number now records the target addresses it was
seen at: equal address counts are complete copies, a resend to the same
address is one block, and unequal counts make coverage unknown with a
limitation and ambiguous_numbering_group_count. sequence_count becomes
numbering_group_count, and region block positions become
first_file_block and last_file_block.

Review follow-ups in the same change:
- compare_artifacts compares a DfuSe element's alternate setting and
  target name, so bytes moved to another device memory are changed;
- the shared reader keeps no region bytes outside its map after close;
- one domain type replaces four identical decoder failure types;
- the UF2 decoder returns a typed limit instead of throwing on bytes
  beyond its admitted size, and caps retained regions, not runs;
- DfuSe caps elements with bytes only, names empty elements and
  element-less targets, drops the constant bVersion and bcdDFU fields,
  and says whether the CRC matches when DFUImageSize fits neither
  convention;
- classification evidence carries a suffix only when the probe saw the
  end, and root classification reads the tail only for a DfuSe prefix;
- the UF2 domain region owns family_name, and the root records the
  family registry revision; the table's MIT notice is preserved;
- docs pin the producer revisions (dfu-util ee6b393d and f9a537c9,
  MicroPython cb99ca98), give the MD5 structure's real meaning, and
  describe container contradictions in the MCP contract guide;
- tests and the esptool lane add the equal-count inputs and a block
  lost from one of them, accepted boundaries beside each refusal, a
  DfuSe root larger than the classification prefix, and CLI refusals.
Take main d48e472. morluto#8054's registry, src/artifacts/artifactFormats.ts,
now owns the per-format switches this branch extended, so `uf2` and
`dfuse` become registry entries with the old switches' flags and
limitation texts, and the reader-format test lists them. morluto#7481's
vocabulary guard gains `uf2` and `dfuse` targets. The DfuSe element
declaration joins main's `declarationChanged`. Format lists keep both
sides, in embedded-integration's order.
LibreTiny writes UF2 for Realtek, Beken and Bouffalo Lab modules. The
Microsoft registry revision REA already cites (cf3bd7f9) lists eight of
those families: RTL8710A, RTL8710B, RTL8720C, RTL8720D, BK7231U, BK7231N,
BK7251 and BL602. Their regions now carry those names. LN882H, which
that revision omits, keeps its familyID with no name.
@greptile-apps

greptile-apps Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5 Tier: apex

[Medium impact] No actionable code defect was found; the code appears safe to merge once maintainers settle the stated compatibility decision.

Summary

Adds UF2 and DfuSe inventory and extraction through the existing artifact tools.

  • UF2 files now expose separate address regions for each family.
  • DfuSe files now expose each nonempty target element as a region.
  • HEX and S-record files now use shared region-decoding code.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Selected local file] --> B[Recognize UF2 or DfuSe]
  B --> C[Decode bounded regions]
  C --> D[Shared region reader]
  D --> E[Inventory and hash regions]
  E --> F{DfuSe CRC mismatch?}
  F -->|No| G[Inspection or extraction]
  F -->|Fail policy| H[Integrity error]
  F -->|Record and continue| I[Root marked mismatched]
  I --> G
Loading

Reviews (3) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." · Reviewed by Greptile

Comment thread src/domain/firmware/dfuse.ts Resolved
…ting them

Empty DfuSe elements have no entry, so DFUSE_MAX_ELEMENTS does not cap
them, and the target walk kept a description string for each one. At 8
bytes per element, a file under the 128 MiB ceiling can declare about
16.7 million of them. The walk now counts every declaration without bytes
and builds only the first NAMED_ELEMENTS descriptions, which is all that
the limitation shows. The limitation text and empty_element_count do not
change. The guide now says that both DfuSe limitations name the first four.

On this host, decoding 4,000,000 empty elements (a 32 MB file) ran out of
memory under a 128 MB V8 heap before this change, and it peaked at 1.59 GB
RSS with the default heap. It now decodes in 114 ms with a 220 MB peak.
Entrpi added a commit to Entrpi/rea that referenced this pull request Oct 31, 2026
@Entrpi
Entrpi marked this pull request as ready for review October 31, 2026 00:19
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-31T00:19:48.164443Z
We couldn’t complete this review. Comment @codex review to try again.
1f93594 Draft marked ready
ℹ️ 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

# Conflicts:
#	docs/testing.md
#	src/application/BinaryTargetResolver.ts
#	src/artifacts/ArtifactReader.ts
#	src/artifacts/artifactFormats.test.ts
#	src/artifacts/artifactFormats.ts
#	src/artifacts/inventory/ArtifactGraphConstruction.ts
#	src/domain/analysisSnapshot.ts
#	src/domain/analysisView/artifactInventoryView.ts
#	src/domain/artifactComparison.ts
#	src/domain/artifactFormatMetadata.ts
#	src/domain/artifactGraph.ts
#	src/domain/evidenceSubject.ts
#	tests/boundary/filesystem/binaryTarget.test.ts
@morluto
morluto merged commit b43c329 into morluto:main Oct 31, 2026
49 checks passed
Entrpi added a commit to Entrpi/rea that referenced this pull request Oct 31, 2026
Main's ESP flash layout (morluto#8228) and UF2/DfuSe (morluto#8230) changes compare
their declarations through per-format fields. Here the table owns every
kind: esp-flash-partition and dfuse-element get table entries with
main's fields, and esp-flash-image, uf2, uf2-region and dfuse state why
they are not compared. espFlashPartitionDeclaration, its
EspFlashPartitionMetadata alias, dfuSeElementDeclaration and
pyInstallerEntryDeclaration are removed, and the contract paragraph names
the two compared kinds.
Entrpi added a commit to Entrpi/rea that referenced this pull request Oct 31, 2026
Entrpi added a commit to Entrpi/rea that referenced this pull request Oct 31, 2026
@morluto morluto mentioned this pull request Nov 11, 2026
3 tasks done
@morluto morluto added area: evidence Evidence, artifacts, and reconstruction enhancement New feature or request labels Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: evidence Evidence, artifacts, and reconstruction enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants