Skip to content

feat(artifacts): inventory and extract ESP flash layouts - #8228

Merged
morluto merged 36 commits into
morluto:mainfrom
Entrpi:feat-artifacts-esp-flash-layout
Oct 31, 2026
Merged

morluto merged 36 commits into
morluto:mainfrom
Entrpi:feat-artifacts-esp-flash-layout

Conversation

@Entrpi

@Entrpi Entrpi commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

esptool read-flash 0 ALL dump.bin is the most common ESP32 input, and REA cannot read it as a layout. A C3 or S3 dump opens as its bootloader image with everything after it undescribed. An ESP32 dump, which starts with erased flash before its bootloader at 0x1000, is refused. This PR adds a container format, esp-flash-image, behind inspect_artifact and extract_artifact. It locates the bootloader and partition table, lists each partition, decodes the bootloader and app partitions with the existing ESP image decoder, and reads the OTA records.

Refs #3615 ("Partition Table Analysis" and "App Image Slicing"; the table is verified by its MD5 only, as ESP-IDF's bootloader does). It builds on the ESP image reader from #7498. Part of the embedded roadmap #7955. NVS decoding, raw loading of segments and Ghidra loading are not part of this PR.

Problem and expected behavior

  • Before, observed on main d48e472fa with two 256 KiB fixture dumps: rea inspect-artifact --json reads an ESP32-C3 dump (bootloader at 0x0, two apps) as esp-image with 229,376 undescribed bytes from 0x8000, and exits 1 with target_unavailable and file_format_rejected for an ESP32 dump (bootloader at 0x1000).
  • After: both open as esp-flash-image archives with nothing undescribed. Inspection reports the bootloader region, the partition table and how it was found, each partition's declaration and written bytes, ESP image facts for the bootloader and each app, the OTA records and a boot selection. Extraction writes the bootloader region, the table sector and each partition as files.

Change and scope

  • Domain (src/domain/firmware/, pure): the table is checked as esp_partition_table_verify does (an MD5 mismatch keeps the entries as an integrity fact), and REA requires one partition entry, so neither erased flash nor a lone MD5 entry is a table. The boot selection is derived as bootloader_utility_get_selected_boot_partition does, without rollback or anti-rollback. The bootloader is found at its chip's ROM offset, and the table at the caller's offset, at 0x8000 or by a sector scan for a verified MD5.
  • Reader and registry: entries bootloader.bin, partition-table.bin and partitions/<label>.bin, or partitions/<index>.bin for a label that is unsafe, repeated ignoring case, or a Windows device name such as NUL or COM1; the metadata keeps the label. Root classification locates the layout once and passes it to the reader as an admission, like the Godot PCK location. The esp-flash-image descriptor in artifactFormats.ts owns construction, retention, the container role and extraction. Members follow the ESP image reader's lifecycle: a member stays owned until its consumer closes it, cancellation retires its buffered bytes, and no inventory finishes after close().
  • Detection: layouts are detected before single ESP images, in the target resolver and in inventory classification; an explicit selection decides first. A single app or bootloader image is not scanned. Unless the caller names the table, a known chip's image at another chip's ROM offset is refused. ESP8266 dumps stay refused.
  • Inputs: format: "esp-flash-image", flash_offset and partition_table_offset on open_binary; --target-format esp-flash-image, --flash-offset and --partition-table-offset on inspect-artifact and extract-artifact. The offsets require the format; the table offset is a multiple of 0x1000.
  • Comparison: a partition's label, label_hex, type, subtype, address, size and flags are its declaration. Every partition from the dump's first byte on is an entry with the bytes the file holds, so two merge-bin dumps compare partition by partition, and a cut-short dump reports the partitions it lacks as changed.
  • More facts: each partition's written extent, with a limitation for an erased app slot that holds data; a boot_selection for every table, whose basis names the bootloader's branch; a flash_dump hint, with an open_binary next probe, when an esp-image is the bootloader of a dump read from a later address; and a summary view (esp-flash-image-summary) that gives each nested image a compact summary.
  • Not included: NVS, FAT and SPIFFS decoding, flash-encrypted layouts (not recognized by design), and dumps nested in other containers.
Deliberate choices that reviewers may question
  • App facts, segments included, are root metadata (apps[].facts), because the inventory does not expand nested containers. Extract a partition to inventory its image.
  • Written bytes are one bounding range and a count per partition: entry metadata stays flat for comparison, and a range list has no bound for a fragmented filesystem.
  • The encrypted flag is metadata: it says how the device stores the partition, not that the dump holds ciphertext.
  • The running partition is unknown: rollback, anti-rollback and load fallback decide it at boot.

Follow the contribution scope. Unresolved scope, authority, side effects, or required verification block integration. Link the required maintainer scope decision for new providers or capabilities involving target execution, injection, mutation, or protection recovery; ordinary fixes within existing boundaries may state "not applicable". Draft PRs may leave the scope decision pending and the readiness and merge checklists unchecked. Maintainers can help resolve open questions.

Contract and boundary impact

  • Semantic owner and earliest changed stage: espFlashLocation.ts locates the layout for both target resolution and inventory classification, espFlashLayout.ts plans the regions, and the registry descriptor owns construction. Nothing is superseded.
  • Contribution scope fit and linked maintainer decision: not applicable. It reads local files only, inside the existing artifact tools.
  • CLI and MCP/tool-catalog contract: a format value, two optional open_binary inputs, three CLI flags, the format_metadata kinds esp-flash-image and esp-flash-partition, a flash_dump field on esp-image, the summary-view kind esp-flash-image-summary, and an open_binary summary variant. tools/list against main d48e472fa, 233 tools in both: default profile +27,429 bytes (+0.71%), full input schemas +28,269 (+0.63%), compact output schemas +1,021 (+0.18%). Most is in inspect_analysis_view (+9,678) and inspect_artifact (+9,553); 198 tools grow by 18 bytes for the subject format enum. Token counts were not measured.
  • Provider, bridge, target-format, or platform compatibility: a new archive target format. Files whose layout REA locates, previously read as an ESP image or refused, now resolve as esp-flash-image. No provider runs.
  • Evidence, artifact, provenance, or reconstruction contract: Evidence subjects, snapshots and bundles can contain esp-flash-image, and the snapshot target variant makes flash_offset and partition_table_offset target identity. Older REA versions cannot parse these closed enums and unions (derived from the source; no older release was run). This REA still reads and compares esp-image Evidence recorded before flash_dump existed: the field is optional when read, so such a record keeps its graph digest. Compatibility decision requested: CONTRIBUTING.md requires an explicit decision for persisted formats. Maintainers, please decide whether these additions are acceptable as they are and whether they need a release note: the esp-flash-image format value; the metadata kinds (esp-flash-image, esp-flash-partition, esp-flash-image-summary, and flash_dump on esp-image); the snapshot target variant; the live open_binary summary variant; and the open_binary inputs flash_offset and partition_table_offset.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): an explicit selection decides before every other signature, and the offsets are refused with any other format. The reader starts no process.
  • 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. A new optional npm run verify:esp-flash 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

  • Tests added or updated: 95 tests in espFlashLayout (22), espFlashPlan (14), espFlashLocation (19), EspFlashImageArtifactReader (19) and its boundaries test (8), EspImageArtifactReader (2 added), artifactComparisonEspImage (1 added: an image record without flash_dump), MCP comparison (2), MCP inputs and summary view (3), the compiled CLI (2) and target resolution (3 added), plus the registry and vocabulary rows. The boundaries test runs main's shared stored-member lifecycle cases; before 543ace0cd two failed: a paused inventory finished after close(), and buffered member bytes stayed readable after cancellation.

  • Base reproduction or other evidence:

    • The before and after above ran on builds of main d48e472fa and this branch. On this branch the ESP32 dump has its bootloader at 0x1000 and selection factory-fallback.
    • Real builds, re-run on 19a612b8b after the review fixes: merge-bin dumps of four local ESP-IDF v5.5.2 builds (three ESP32-S3, one ESP32) gave the same report as before the merge with main. Coverage was complete, every partition agreed with gen_esp32part.py, bootloader and app facts agreed with esptool v5.6.0 image-info, and otadata records agreed with otatool read_otadata. MCP compare_artifacts of the three S3 dumps had no unknown path, the same result as on b47f0bd23.
    • A 16 MiB ESP32-S3 dump read from a device, inspected only before the merge with main: complete coverage, selection otadata slot 0, and an erased ota_1 holding 443,415 written bytes, which a limitation names.
    • Reviewers cannot rerun the real-build or device checks: the builds are local, and the device dump holds the device's NVS.
  • User-visible CLI/MCP output (if applicable): the C3 fixture dump's root metadata on this branch, trimmed.

    Root format_metadata
    { "kind": "esp-flash-image", "flash_offset": { "value": 0, "source": "default" },
      "chip": { "target": "esp32c3", "isa": "riscv", "source": "ESP-IDF v6.1" },
      "bootloader": { "path": "bootloader.bin", "flash_address": 0, "facts": { "status": "esp-image" } },
      "partition_table": { "flash_address": 32768, "method": "default", "partition_count": 6, "md5": { "status": "valid" } },
      "apps": [ { "path": "partitions/factory.bin", "partition_index": 3, "facts": { "status": "erased" } },
        { "path": "partitions/ota_1.bin", "partition_index": 5, "facts": { "status": "esp-image" } }, "…" ],
      "boot_selection": { "basis": "otadata", "active_record": 0, "slot": 1, "partition_index": 5,
        "running_partition": "unknown" },
      "undescribed": [] }
  • Remaining proof gaps: one device dump, not inspected since the merge with main. Only ESP32-C3, ESP32-S3 and ESP32 layouts came from real tools; the 0x2000 ROM offset is synthetic, and the other chips' offsets were checked against ESP-IDF v6.1 headers by inspection. The CRC-mismatch fallback, short or offset-0 otadata, a rejected table and gapped or repeated OTA subtypes have only synthetic fixtures. OTA states the bootloader writes, rollback, anti-rollback, its flash-size check and flash-encrypted dumps were not exercised.

For boundary fixes, identify the applicable boundary regressions and lifecycle regressions covered by the evidence above, and explain relevant gaps.

Boundary: malformed tables, truncated, outside and overlapping partitions, non-UTF-8 labels, forged entries and a changed carrier. Lifecycle: main's shared stored-member cases, and cancel or close during decoding and the written-bytes scan.

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

macOS arm64 with Node 24.22.1, on a1b264cc2, the head after the review fixes, unless noted.

  • npm run check:fast, npm run format:check, npm run docs:check and npm run verify:module-boundaries — passed.
  • npx knip — no findings.
  • npm run test:focused -- 38 files — 541 passed, 3 skipped (Windows-only). Besides the files above: registry, inventory, comparison, snapshot and input-contract tests, ESP image, FIT, uImage, HEX and UnityFS CLI tests, and MCP schema-budget tests.
  • npm run verify:esp-flash, with Clang/LLD 21.1.8 and ESP-IDF v5.5.2's tools, once with esptool v5.6.0 and once with 4.12.0 — all six cases passed in both runs: the default C3 layout with otatool's slot 0, slot 1 and erased-otadata selections, primary bootloader and table entries, a relocated table, a dump written from 0x1000, a corrupt factory app and a truncated dump. With the build cached, the v5.6.0 run took 18.0 s elapsed on 19a612b8b and 28.8 s on a1b264cc2, while other checks shared the Mac; its largest process peaked at a 279 MiB resident set.
  • npm run verify:esp-images, on 19a612b8b, with esptool v5.6.0 and Xtensa GCC 14.2.0 — 15 cases passed; the two ESP8266 cases now expect their refusal through the lane's opt-in refusal().
  • Review fixes, each against its own regression:
    • 7cbe83a57: against a server built with the required flash_dump, compare_artifacts rejects the old-shape record with evidence_integrity_mismatch; with the fix, the test passes.
    • cbfb20445, bf0d60d39 and 19a612b8b: with the fix reverted, its new tests fail.
    • fdcca49a4: with one scan per partition, the 60-partition test reads 52,493,480 bytes of a 1,114,112-byte dump and fails; the single pass reads 1,113,256.
    • a1b264cc2: without the shared decode, 60 app partitions over one image make 61 decodes and the test fails; the dump then reads 2,161,864 bytes, as a dump with one app partition does, instead of 64,029,736.
    • e8e50f232: otatool on a file without a table, inspect() on a file REA refuses and refusal() on a file REA opens each reject with their cause.
  • Mutations on b47f0bd23, whose comparison code is unchanged since: without the partition declaration term in declarationChanged, or without label_hex in espFlashPartitionDeclaration, artifactComparisonEspFlash.test.ts fails. Both were restored.

Compatibility, safety, and release

  • Breaking changes or migration steps: none for current versions. Older versions cannot read Evidence or snapshots that contain the new format; see the decision requested above.
  • Real Hopper/Ghidra, browser, or OS coverage: none needed; no provider runs. Only macOS arm64 was used.
  • Package or release metadata impact: none, pending the release-note decision.
  • Security, privacy, process, or containment review: the reader reads the selected file only and starts no process. Extraction writes nvs_keys partitions as ordinary files; without flash encryption they hold keys in plain text, as the docs say. The lane runs Clang, esptool and ESP-IDF scripts on generated fixtures as owned process trees and never runs the images.
  • Merge order with the comparison-table PR (branch fix-artifacts-comparison): whichever merges second adds comparison-table entries for esp-flash-partition and its sibling kind esp-flash-image, as the fork's integration branch already does.

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.

Entrpi added 29 commits October 27, 2026 22:54
ESP32-family app and bootloader images (magic 0xE9) had no reader, so
open_binary refused OTA downloads, app partitions and bootloaders.

Add the esp-image container format behind inspect_artifact and
extract_artifact. A pure decoder reads each byte once and keeps only
fixed-size fields. Derived facts cover the chip, from a table cited to
ESP-IDF v6.1; segment classification as ESP-IDF's should_map and
should_load; checksum and appended SHA-256 results; app and bootloader
descriptors; Secure Boot v2 signature blocks, observed and unverified;
and undescribed trailing byte ranges. Truncation and undescribed bytes
make coverage unknown. ESP8266 images are refused with a specific
reason, and ciphertext stays unrecognized.

Add the format to every target, Evidence, snapshot, live-summary and
artifact vocabulary, document it, and add an optional verify:esp-images
lane that compares esptool-built images with esptool image-info and
espsecure signature-info-v2.

Refs morluto#3615
The lane compared descriptor fields only when esptool image-info printed
one, so a descriptor that REA reports and esptool does not print passed
without comparison. Compare the descriptor kind in both directions.

Record that the lane passed for all 13 images with esptool and espsecure
v5.6.0, the version the layout facts cite, as well as with 4.12.0.
The decoder and the derived facts each defined the segment-header,
appended-digest and flash-sector sizes, the erased-byte scan and the
offset formatter. Define them once with the other fixed-layout structures
and import them in both places. The signature slot count is the one
constant that drives the slot scan.

Correct the observedEnd comment: it is the end of the last chunk read.
ESP-IDF's verify_segment_header rejects a segment of 16 MiB or more
unless the chip maps flash through 32-bit cache addresses
(SOC_SPI_MEM_SUPPORT_CACHE_32BIT_ADDR_MAP: ESP32-S3, P4, C5, C61, H4 and
S31 in v6.1). Record that capability in the chip table and add a
limitation for such segments; unknown chips get none.

`loaded` repeats should_load. It does not mean the bootloader accepts the
segment: verify_load_addresses still rejects one outside the chip's RAM,
which REA does not model. Say so in the docs, the skill reference and the
inventory limitation.
The lane started work before checking its tools, so a missing RISC-V
target, ld.lld, esptool or espsecure surfaced as a raw spawn or command
error. Check each one before building and name the variable to set. Warn
when esptool is not v5.6.0, the release the layout facts cite.

Assert each segment's class for the ESP32-C3 app, its variants and the
bootloader, as the Xtensa image already did. Extract the app and the
signed image through the CLI and compare every file with the bytes at
esptool's segment offsets or in the appended signature sector; the
source's SHA-256 must be unchanged and equal the reported root_sha256.
The Verification section listed the lane's checks but not its gaps: only
ESP32-C3 and ESP32 images come from a real producer, no real project
build, OTA download or flash dump is inspected, no signature is verified,
and the lane does not run in CI.

Record the timing of the final lane run on esptool v5.6.0.
Segment entries hash only their data, so compare_artifacts reported a
segment that moved to another load address with the same bytes as
unchanged; only the image itself changed. Compare each segment's
load_addr and data_len as its declaration, as Node SEA and PyInstaller
members are compared, and count a changed declaration as a metadata
change, also when content is unavailable.

Header offsets are layout and the classification is derived, so neither
is compared.
The lane ran its tools through execFile. A timeout killed only the direct
child, so a linker or assembler that Clang or GCC had started could keep
running while the lane removed its workspace. Run every command through
createVerifierCommands, check the tools inside withVerifierCleanup, and
remove the workspace only after commands.close() has stopped every tree;
a failed close keeps the workspace.

Only a nonzero exit now counts as a refusal or an expected esptool
failure; timeouts and spawn failures propagate. Supervising each command
roughly doubles the lane's run time.
The cancellation test requested cancel or close on setImmediate, which
can land while the file is still being opened and checked, so it never
showed that decoding had started. It also passed against a reader that
ignored both requests while decoding. Acknowledge the decoder's first
chunk, then cancel or close, join the operation, and assert that no
later chunk reaches the decoder and that the reader ends closed.
Segments are compared by their declaration. The image's and the
signature blocks' format_metadata are not: every field comes from their
own bytes, which content comparison already covers, and a block's
image_digest_matches follows the image's content.
A whole-flash dump of an ESP32-family chip was read as its bootloader
image, with the partition table, apps and data left as undescribed bytes,
or refused when it began with erased flash. Read it as an esp-flash-image
container instead.

The partition table is decoded as esp_partition_table_verify accepts it
and is found at the caller's partition_table_offset, at the default
0x8000, or by scanning 0x1000-aligned sectors for a table whose MD5
verifies, which the inventory reports as derived. The bootloader is
located at its chip's ROM bootloader offset. Each partition is an entry
with its declaration in flat format_metadata; the bootloader and app
partitions carry ESP image facts from the existing streaming decoder; the
otadata records are reported with a selection derived without rollback or
anti-rollback, and the running partition stays unknown. One unreadable
partition does not hide the others, and extraction writes every partition,
nvs_keys included, as ordinary data.

Flash layouts are detected before single ESP images. The scan runs only
when an ESP image sits at a ROM bootloader offset, and is refused when a
bootloader at another chip's offset shows that the dump does not start at
flash address 0. open_binary gains flash_offset and partition_table_offset,
which require format esp-flash-image and are part of the snapshot target
identity; the CLI takes them with --target-format esp-flash-image.
Comparison treats a partition's label, type, subtype, range and flags as
its declaration.
…in and otatool

Add the optional verify:esp-flash lane. It builds default and relocated
partition tables with ESP-IDF's gen_esp32part.py, assembles dumps with
esptool merge-bin, including one written from flash 0x1000, and writes
OTA records with otatool through flash_file_tool.py, which replaces
parttool's esptool calls with reads and writes of the dump file.

It compares REA's bootloader and app facts with esptool image-info, every
partition with gen_esp32part.py's decoding of the extracted table, and the
OTA records and derived slot with otatool read_otadata after each switch.
It also checks extracted bytes and source integrity, the scan and caller
table offsets, flash_offset on the 0x1000 dump, a corrupted app beside
valid partitions and a truncated dump. ESP32 linker scripts place the
conformance bootloader and app in ESP32 address ranges.
Read the partition table as bootloader_utility_load_partition_table
does: the last factory, otadata and same-subtype OTA declaration wins,
and a limitation names repeats. Plan each otadata record within its
partition and the dump. An otadata partition smaller than two sectors
selects none, the bootloader's INVALID_INDEX; a record the dump lacks
leaves the selection unknown while the other record stays reported. The
fallbacks follow the bootloader's indexes: ota_0-fallback and
factory-fallback name no partition when the table declares none, and the
assumptions add GPIO holds and deep-sleep wake.

Refuse a dump whose bootloader contradicts its origin before the default
table offset is tried, whether flash_offset was omitted or given, and keep
the ESP image reader's ESP8266 refusal. A table never lies inside the
located bootloader image, so single app images are no longer scanned. An
explicit esp-flash-image selection is decided before other container
signatures, and the native commands' --target-format no longer takes it.
Say when no bootloader confirms the default origin.

Exempt the primary bootloader and partition_table entries of ESP-IDF 5.3
from placement limits, report every region inside a longer one, and name
partitions by index when labels repeat ignoring case. Keep an undecodable
label's bytes in label_hex and compare them. Word undescribed ranges as
starting at a byte that is not erased, and treat a short erased region as
erased.

Add an MCP compare_artifacts test for partition declarations, reader
identity and close tests, scan edge cases, the 0x2000 ROM offset and a
literal otatool CRC.
…llback

Build a table with the primary bootloader and partition_table entries
that gen_esp32part.py fills from --primary-bootloader-offset, and check
that REA reads it with complete coverage, no overlap or misplacement
limitation, and a table that agrees with gen_esp32part's decoding. Erase
the otadata with otatool after the slot switches and check the records
against read_otadata and the factory fallback.
An esptool merge-bin dump ends after the last part it wrote, usually inside
its last partition. Such a partition made the layout's coverage unknown, so
artifact comparison of two merge-bin dumps reported every unchanged
partition as unknown.

The partition table names every partition whatever the file's length, so a
partition cut short or left out by the end of the file hides no entry. As
the ESP image reader does for a cut-short segment, its entry holds the bytes
the file has and an entry limitation gives the declared size; a partition
with no bytes stays in partitions_outside_dump. Coverage stays complete
unless undescribed bytes remain or no bootloader is located. An MCP
compare_artifacts test of two dumps that end inside ota_0 now classifies
every partition, and fails on the old rule.
…included

An app slot is erased for ESP-IDF's bootloader when its image header bytes
are erased flash, and REA reported only that status. A slot can still hold
data further in: a dump read from a device held a complete older app image
1 MiB into an OTA slot reported as erased, with no limitation.

Each partition entry now records where the bytes the dump holds are
written, relative to the partition: written_offset, the first byte that is
not 0xFF, written_end, just past the last, and written_bytes, how many are
not 0xFF. They are null for a partition outside the dump. The status stays
erased, which is the bootloader's view, and a limitation names an erased
app slot that holds written bytes and says they are not read as an image.
The reader reads every partition byte once more to find them.
The boot selection lived inside otadata, so a table without an otadata
partition, the common factory-only layout, had none. ESP-IDF's
bootloader_utility_get_selected_boot_partition returns the factory index
when the table declares no otadata partition.

Move it to a top-level boot_selection that every layout has. Its basis
names the bootloader's branch: otadata, factory-fallback and ota_0-fallback
from the records, no-otadata for a table without otadata, none for the
bootloader's INVALID_INDEX, and unknown when the dump lacks a record the
bootloader reads, which replaces the null selection. running_partition
moves with it, and otadata keeps its partition index and records. The
assumptions name what each branch leaves out: no records assumption
without otadata, and none for none or unknown. The real-tool lane checks
no-otadata on a table gen_esp32part built without otadata.
An ESP32 dump read from flash 0x1000, as read-flash 0x1000 or merge-bin
--target-offset 0x1000 writes it, opened automatically as its bootloader
image with a megabyte of undescribed bytes and no next probe. The flash
reader refuses that origin, but nothing told an agent which flash_offset to
pass.

espFlashDumpOrigin owns the inference: an image of a chip whose ROM loads
the bootloader from flash R, at file offset F, is the bootloader of a dump
read from R - F when a partition table sits where that origin puts 0x8000.
The ESP image reader asks it for a non-app image at file offset 0, so the
result does not depend on how the reader was created, and records
flash_dump {flash_offset, table_file_offset}, null otherwise, with a
limitation that says to reopen the file as esp-flash-image with that
flash_offset. inspect_artifact proposes the same open_binary call as a next
probe, and the flash reader's misplaced-origin refusal names the offset.
…ary view

The summary view returned an ESP flash layout's root facts whole, so each
app partition and the bootloader carried every segment and signature
block, about half of a dump's summary.

The summary view now gives each nested image a summary instead of its
facts: status, chip, entry point, segment count, load ranges (each mapped,
loaded or unclassified segment's address and declared length), the
checksum and appended SHA-256 statuses, coverage and limitations. Complete
detail keeps the full facts, every segment included, and the retained
Evidence is unchanged. On a 16 MiB device dump the summary's root falls
from 5,141 to 2,657 bytes, and the summary Evidence from 10,038 to 7,554.
… reports

8a748d3 added misplacedImage to the bootloader search, which the
locator uses to name the origin a misplaced bootloader implies, but one
test still compared the search result without it. Expect the image's
chip and file offset, and no image for an unknown chip.
After ecbc1a7 kept coverage complete for a dump cut short, a partition
wholly past the end of the file still had no entry, only a
partitions_outside_dump row. Comparing a merge-bin dump with a full device
read then reported that partition as added or removed, as if one table
did not declare it.

Every partition from the dump's first byte on is now an entry holding the
bytes the file has: none for one past the end, with a limitation saying
the file holds none of its bytes, no image facts and null written fields.
partitions_outside_dump keeps only partitions that begin before the dump's
first byte, and coverage is unknown when one does, since it has no entry.
Two dumps that lack the same partition now compare it as unchanged, and a
dump against a longer one reports the partition as changed; an MCP test
of a merge-bin dump against a full one checks that no path is added or
removed.

Unlike the ESP image reader, which marks a truncated image's coverage
unknown because later segments and signature blocks may be hidden, the
flash reader can list every partition from the table whatever the file's
length; only the entry limitation follows the image reader.
…er rejects

boot_selection followed bootloader_utility_get_selected_boot_partition but
not the table check before it. For a table whose MD5 does not match, or
that has a second MD5 entry, esp_partition_table_verify fails, the
bootloader selects no app and resets. REA still derived a slot from the
otadata records, although the table's own limitation said the bootloader
rejects it.

The selection now has basis none, with no assumptions, for a table the
decoder marks invalid. It also follows two more branches of the
bootloader: an otadata partition at offset 0, which the bootloader takes
for none, selects the factory index as no-otadata, and a table without an
OTA app selects its fallback even when the dump lacks a record, since the
bootloader then ignores the records.

The bootloader also rejects a table whose partitions end past the flash
size in its header. REA does not model that check; the format guide says
so.
espFlashDumpOrigin named a later flash origin whenever a partition table
decoded where that origin puts 0x8000. Bytes inside the image's own
segments could be read that way, so an ESP32 bootloader whose segment data
held table-shaped bytes at file offset 0x7000 was reported as a dump read
from 0x1000.

The table must now start at or after the image's end, the rule the locator
already applies to the default table. The ESP image reader passes the
image_end it decoded, or the file size for a truncated image; the flash
reader's refusal passes the end of the misplaced image's segments. The
bootloader search drops its misplaced flag, which only restated
misplacedImage, and the next probe formats offsets with offsetText.

Reader tests cover the 0x1000 and 0x2000 ROM offsets, a standalone
bootloader, bytes that begin like a table, an app with a table at 0x7000
and a table inside a segment; without the boundary check, three of them
fail.
…e's identity

The summary view's ESP flash root kept kind esp-flash-image, so a consumer
bound to kind could not tell an image's summary from its full facts, and
the advertised schema held two objects with the same kind const. It is now
esp-flash-image-summary.

The per-image summary also dropped the descriptor, which is what tells two
app slots apart, and named each image only by its partition index, which
the summary view, having no entry rows, could not resolve. Each nested
image now carries its entry path from the layout plan, in both views. The
summary adds the descriptor kind with its identifying fields (an app's
project_name, version, idf_ver, secure_version and app_elf_sha256; a
bootloader's version, idf_ver and secure_version), the signature block
count and each load range's classification. Its enums and fields derive
from the schemas that own them.

An MCP test reads a dump with an app in ota_0 and an erased ota_1 that
holds older bytes: it checks both summaries, that the summary's inventory
Evidence is the one the complete view returns with full facts, and the
erased slot's written range.
…scan

The written-bytes pass reads every byte of each partition the dump holds,
checking that the reader is open before each chunk, but only app decoding
had a cancellation and close test. A data partition, which only that pass
reads, now holds 9 MiB; once the scan has examined its first chunk, a
cancel rejects preparation with the caller's reason and a close with
unavailable, and the scan examines no further chunk.

The erased-slot test now asserts the whole set of erased-slot limitations,
so factory, ota_0 and nvs, which the bootloader reads or which are not app
slots, are shown to have none.
…auses

The lane ran again after its assertions changed; both esptool runs passed,
and the timed run's figures replace the earlier ones. The erased-slot
paragraph no longer names a cause for the older bytes, which REA cannot
observe, and the skill reference states that every table has a
boot_selection in its own sentence, with the none basis for a table the
bootloader rejects.
This branch carried morluto#7498's pre-squash commits, which upstream merged as
squash 64196b0 with maintainer commits. The merge therefore used the
absorbed prototype ea2b386 as its base, so the result differs from main
only in this branch's own changes; git's own base reported every morluto#7498
region as a conflict.

Adaptations to main:

- morluto#8054 describes formats in one registry. The esp-flash-image descriptor
  in artifactFormats.ts now owns the reader construction, admission,
  classification retention, container role, extraction and reader
  limitation that this branch had spread over createArtifactReader,
  classify, ArtifactGraphConstruction, ArtifactExtraction and the
  inventory reader. EspFlashAdmission joins ArtifactFormatAdmission.
- morluto#7498 moved the ESP image fixture to tests/fixtures/espImage.ts; the ESP
  flash tests import it from there.
- morluto#7481's vocabulary guard expected every caller-selected format hint to
  name an executable target; an ESP flash dump is read as an archive.
- morluto#7905 bounds MCP arguments at 1,024 elements by default, which the inline
  flash-dump inventories exceed, so the ESP flash comparison test compares
  the Evidence its session retained.
morluto#7498's maintainer commits made the ESP image reader keep a member owned
until its consumer closes it, retire fully buffered bytes when
cancellation arrives after production, and refuse to finish an inventory
paused across close. The ESP flash reader was copied from the earlier
reader. Main's shared stored-member lifecycle cases failed two of eight
against it: a paused inventory completed after close, and buffered member
bytes stayed readable after cancellation.

Give the flash reader the same lifecycle and run the shared cases against
it.
The lane passed again with esptool v5.6.0 and 4.12.0 on the merge of upstream main. Record the v5.6.0 run's time and peak resident set.
@greptile-apps

greptile-apps Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5 Tier: apex

[Medium impact] The code update appears safe to merge; no blocking code issue was found.

Summary

Adds esp-flash-image inspection and extraction for ESP flash dumps.

  • ESP flash dumps open as archives of their bootloader, partition table, and partitions.
  • Callers can choose how REA reads an ESP flash dump.
  • Artifact comparisons report changes to ESP partition declarations.
  • Summary views show compact facts for each image in a flash dump.
  • ESP image inspection can point to the full flash layout.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A["CLI or MCP input"] --> B["Locate flash layout"]
  B --> C["Plan bootloader, table and partitions"]
  C --> D["Read bytes and decode unique image ranges"]
  D --> E["Inventory and retained Evidence"]
  E --> F["Compact summary"]
  E --> G["Extract region files"]
Loading

Reviews (3) · Last reviewed commit: "fix(artifacts): decode an image shared b..." · Reviewed by Greptile

Each partition got its own scan of the bytes the dump holds, so
partitions declared over the same bytes read them again and again.
Overlaps only add limitations, so a crafted table reached this normally:
94 overlapping partitions over a 32 MiB dump would examine about 3 GiB
before the first entry.

The reader now reads the bytes the partitions cover once. Partition
boundaries cut them into segments; one pass counts each segment's
written bytes and bounds, and each partition's extent is the sum of the
segments inside it. Every partition keeps its own declaration, extent
and limitations. The pass checks the reader's open state before each
chunk, as the per-partition scan did.

A test declares 60 partitions over one MiB, 40 over all of it and 20
over its first half, and checks each partition's extent and the
overlap limitations. The reader reads 1,113,256 bytes of the
1,114,112-byte dump; one scan per partition read 52,493,480.
`otatool` turned a nonzero exit into returned text, which its callers
discarded, and `inspect()` returned `{ refused }`, which the flash lane
never checked. A failed command then surfaced later as a slot
assertion, an output-parser error or a TypeError, hiding its cause.

Commands the lanes need to succeed now reject with the output they
exited with: `otatool` and `inspect()` do so through a shared
`failedCommand`. An expected refusal is opt-in: `refusal()` returns
REA's output and fails the lane when REA opens the file. The ESP image
lane's two ESP8266 cases use it.

Checked by calling `otatool` on a file without a table, `inspect()` on a
file REA refuses and `refusal()` on a file REA opens; each rejects with
its cause.
The decoder counted the slot, not the partitions, so a lone MD5 entry
over the empty prefix, followed by the terminator, decoded as a table
with no partitions. Default and caller-selected detection then accepted
that empty layout, although the guide requires one partition.

A table now needs one partition entry before its terminator. An MD5
entry alone is refused as `entry 1 at 0x20 ends the table before any
partition entry`. The cases cover the decoder and both automatic and
caller-selected location.
Each app partition got its own decode, so app partitions declared over
the same bytes decoded and hashed the same image again and again, the
same pattern the written-bytes scan had. With 60 app partitions over
one 960 KiB image the reader read 64,029,736 bytes of a 1,114,112-byte
dump.

Regions with the same file range now share one decode; each keeps its
own copy of the facts. Partitions with different ranges still decode
separately, because truncation can change the facts: at most one decode
per partition the table holds, each within its partition.

A test declares 60 app partitions over one image, 40 holding all of it
and 20 cutting it short, and expects three decodes: the bootloader, the
whole image and the cut one. The 60-partition dump now reads
2,161,864 bytes, as a dump with one app partition does.
Entrpi added a commit to Entrpi/rea that referenced this pull request Oct 31, 2026
Takes morluto#8228's review fixes (`19a612b8b`, `a1b264cc2`) into integration.
The positional ESP flash reader keeps its base class and adopts the new
scan helpers: one `writtenExtents` call for every held partition,
`firstUnerasedInRange` with a range and the open check, and one decode
per distinct app range. Each uses the base class's `assertOpen` where
the plain reader has `#assertOpen`, including the gap call, which merged
without a conflict.

`artifactComparisonEspImage.test.ts` keeps the comparison topics' shared
MCP fixture for the existing test and imports what the new test for a
record without `flash_dump` needs.
@Entrpi
Entrpi marked this pull request as ready for review October 31, 2026 00:17
@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:17:20.882623Z
We couldn’t complete this review. Comment @codex review to try again.
a1b264c 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.

@morluto
morluto merged commit e6d0618 into morluto:main Oct 31, 2026
53 of 54 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
e6d0618 (morluto#8228) is the parent of morluto#8229's squash e669365, which the next merge records. The merge is clean.
Entrpi added a commit to Entrpi/rea that referenced this pull request Oct 31, 2026
Take main 6e9ee97. morluto#8228's ESP flash inputs join D1's load selection:
resolver, session and CLI options carry `loadSelection` and `espFlash`,
and `formatHint` comes from the selection. `inspect-artifact` and
`extract-artifact` now pass `--target-format esp-flash-image` as a load
selection; built from spreads, the old `formatHint` key compiled but was
dropped. The open_binary description keeps D1's M-profile sentence and
morluto#8361's investigation-record ending. Tests from main move to D1's inputs,
as embedded-integration did: morluto#7481's raw vocabulary target carries
`rawLoad`, morluto#8228's flash resolver tests pass `loadSelection`, morluto#8229's raw
scope case names its entry, and the pairing grid adds esp-flash-image's
four rows while the other sixteen keep d6f88be's hash.
Entrpi added a commit to Entrpi/rea that referenced this pull request Oct 31, 2026
…dot-node-sea

This branch held Q6's older head `9b960f49e`. morluto#8228's final head
`a1b264cc2` brings upstream `main` `d48e472fa` and the review fixes.
The resolution is integration's `94b6e4fa8`:

- The positional ESP flash reader adopts the new scan helpers: one
  `writtenExtents` call for every held partition, `firstUnerasedInRange`
  with a range and the open check, and one decode per distinct app
  range, each through the base class's `assertOpen`.
- The ESP image reader keeps main's limitation owners and `flash_dump`
  on the positional base.
- `PositionalArtifactReader` carries integration's `a04f88531`, morluto#7498's
  member lifecycle: a member stays owned until its consumer closes it,
  cancellation retires bytes already buffered, and an inventory paused
  across `close()` does not finish. The shared lifecycle cases now hold
  for every reader on the base.
Entrpi added a commit to Entrpi/rea that referenced this pull request Oct 31, 2026
…node-sea

The parent of morluto#8228's squash, so that the squash itself can be recorded next.
Entrpi added a commit to Entrpi/rea that referenced this pull request Oct 31, 2026
The squash is exactly this branch's copy of morluto#8228 (a1b264c): both patches have patch-id 57115b2a629d99db184eddad6e18023e7eb32a3e. Recording it with -s ours keeps the tree unchanged.
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