Repository navigation
feat(artifacts): inventory and extract UF2 and DfuSe firmware containers - #8230
Conversation
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.
[Medium impact] No actionable code defect was found; the code appears safe to merge once maintainers settle the stated compatibility decision. SummaryAdds UF2 and DfuSe inventory and extraction through the existing artifact tools.
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
Reviews (3) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." · Reviewed by Greptile |
…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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
# 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
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.
…sh) into embedded-integration
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_binaryrefuses 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,
uf2anddfuse, to the existinginspect_artifactandextract_artifacttools. 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 existingintegrity_policy.Part of the embedded roadmap #7955. Refs #7478 (the format vocabularies this PR extends).
Problem and expected behavior
main(d48e472fa),rea inspect-artifact <file> --jsonon an esptool v4.12.0merge_bin --format uf2output, 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".uf2archive with one region per familyID and address range; the DfuSe file opens as adfusearchive with one region per element. Extraction writes each region's bytes.Change and scope
src/domain/firmware/, pure andResult-based):uf2.tsjoins valid main-flash block payloads into address-contiguous regions per familyID and counts block numbering.dfuse.tsparses the prefix, targets, elements and DFU suffix, and computes the suffix CRC.uf2Families.tsnames 32 family IDs from microsoft/uf2utils/uf2families.jsonatcf3bd7f9(MIT; notice preserved), including 8 that LibreTiny builds for; other IDs keep their value only.addressRuns.tsandregionDecoder.tsreplace HEX's private run merging and failure types.DecodedRegionArtifactReadertakes over the retained-region plumbing thatHexRecordArtifactReaderowned (streams, cancellation, close, carrier identity). HEX, UF2 and DfuSe readers are thin subclasses with format adapters.DfuSeprefix and a DFU 1.1a suffix; the CRC is not part of recognition, and classification reads the file's last 16 bytes.family-0x<id>/0x<start>-0x<end>.bin, one address space per family. Out-of-order blocks are sorted, identical rewrites count asduplicate_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.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.DFUImageSizemay include the suffix or not, because producers disagree.compare_artifactstreats the alternate setting and target name as a declaration, so the same bytes moved to another device memory arechanged.integrity_policy.failrefuses withartifact_integrity_mismatch(algorithm: "dfu-crc32");record-and-continuemarks the rootmismatchedwith adfu-crc32contradiction that extraction carries.docs/uf2-dfuse.md, linked from the existing guides and the skill; the lane indocs/testing.md; container contradictions indocs/mcp-contracts.md; notices for the family names.Deliberate choices reviewers may question:
declared_integrity, which holds entry digests; the DFU CRC lives in the contradiction and informat_metadata.family_nameis an REA label;family_idis the fact, and the root recordsfamily_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
uf2.tsanddfuse.tsown recognition and decoding;artifactFormats.tsowns both formats' capabilities;scanReader.tsapplies the integrity policy to a reader'scontainerIntegrity(). Resolution, classification, inventory, extraction, inspection and comparison consume them. Superseded: HEX's private stream and merge code and four identical failure types.uf2anddfuse;format_metadatakindsuf2,uf2-region,dfuseanddfuse-element; adfu-crc32variant in the inventory and inspection contradiction schemas and theartifact_integrity_mismatchdetails (docs/error-contract.schema.jsonregenerated). No new inputs. Againstd48e472fa,tools/listgrows 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.open_binaryrefused, now resolve asuf2ordfusearchives.docs/public/product-catalog.json), package, or installation impact: none. New optionalnpm run verify:uf2lane.Expected effects (check known effects; use documentation-only on its own). Unchecked items do not establish absence; leave uncertainties visible.
Evidence and regression coverage
Real tools.
npm run verify:uf2ran ondf4154b4cwith esptool v4.12.0 (the ESP-IDF v5.5.2 environment) and with v5.6.0, on macOS. It builds UF2 files with esptoolmerge-bin --format uf2from 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:--chunk-size 256 --md5-disableHand-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'sdfuse-pack.py(f9a537c9) and MicroPython'stools/dfu.py(cb99ca98), one perDFUImageSizeconvention. 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'sTargetFormatVocabularies.test.ts,binaryTarget.test.tsandArtifactGraphConstruction.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 byHexRecordArtifactReader.test.ts, which now runs the shared reader.Base reproduction or other evidence: with
maind48e472fabuilt,node scripts/rea.mjs inspect-artifactrefused an esptool v4.12.0 ESP32-S3 UF2 and a two-target DfuSe file, as quoted above;df4154b4copens both. One9a77ba0c, before the merge withmain, 11 mutations of the owning code each failed their tests; they were not repeated after the merge. Ondf4154b4c, removing one LibreTiny row fails the new naming test.User-visible CLI/MCP output (if applicable), from
df4154b4cand 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 LibreTinyltchiptooloutput 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:
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(withdist/built from this tree) andverify: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.tsandfirmwareContainersMcp.test.ts) — 174 tests passed, 1 skipped.df4154b4cit ran out of memory under a 128 MB V8 heap limit, and with the default heap it peaked at 1.59 GB RSS. On1f935949fit 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 mergesmaind48e472fa:npm run check:fast,format:check,docs:check(with a freshdist/build) andverify:module-boundaries— passed.npx knip— no findings.npm run test:focused --with 100 files — 99 passed and 1 skipped (firmwareMcp.test.tsruns 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 thetests/conformance/contractsfiles.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
d73b1b969passed the same checks and focused files before the LibreTiny names were added.Compatibility, safety, and release
fix-artifacts-comparison) merges second adds table entries fordfuse-elementand its sibling kindsuf2,uf2-regionanddfuse, as the fork's integration branch already does.verify:uf2(esptool), on macOS arm64 only.Author readiness
Human owner: @Entrpi
Before merge
type(scope): outcome.