#7024

feat(pe): share one image-layout owner and read the exception directory

DraftNgLanNgwants to merge intofrom

Summary

PE header, section-table and data-directory facts now have one shared owner, and a new reader exposes the image's exception directory as measured function extents.

PeImageLayout owns header admission, the section table, data directories, virtual extent and file-backed RVA mapping, with tagged failure reasons. PeResourceLayout delegates its header and section facts to that owner and keeps only the resource-specific mapping rules and their messages.

PeExceptionDirectory decodes the exception directory as RUNTIME_FUNCTION records and reports partial coverage and tagged failures instead of silently dropping extents that no section maps.

Problem and expected behavior

PE header and section-table facts were parsed in more than one place, so two readers could disagree about the same image. A reader that wanted a function boundary had no supported way to obtain one: the exception directory is the authoritative source for x64 function extents, and nothing read it.

Expected: one owner for PE image facts, and a way to ask an image for its measured function extents with explicit failure reasons and coverage.

Change and scope

PeImageLayout becomes the single owner for MZ/PE header admission, the section table, data directories, virtual extent and file-backed RVA mapping. PeResourceLayout keeps its own resource mapping semantics — an empty interval still resolves at a section's virtual end, a zero-extent section owns no byte, and an ambiguous interval still fails — and only its messages.

PeExceptionDirectory reads the exception directory and reports each measured extent, the coverage it achieved, and a tagged reason when the directory is absent, inconsistent, unmapped, not file-backed, empty or malformed.

No target execution, no injection, no memory mutation, no protection recovery. This is static format inspection of an artifact the caller already possesses.

Contract and boundary impact

  • Semantic owner and earliest changed stage: src/native/pe/PeImageLayout.ts owns PE image facts; PeResourceLayout consumes it. Native artifact inspection stage.
  • Contribution scope fit and linked maintainer decision: supported — "format inspection", "ordinary archive and standard-compression extraction, disassembly, decompilation, cross-references". No new provider, no target execution, no protection recovery. Not applicable.
  • CLI and MCP/tool-catalog contract: no CLI command, MCP tool, input schema or tool catalog entry changes. This adds library capability only.
  • Provider, bridge, target-format, or platform compatibility: PE only. Reads the EXCEPTION data directory of an existing PE image; no new dependency, no bridge change, no platform-specific code.
  • Evidence, artifact, provenance, or reconstruction contract: no Evidence record, artifact inventory or provenance field changes. The new reader reports partial coverage and tagged failures rather than defaulting to "absent".
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): not applicable; the reader takes bytes already in memory and reads no target.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact: the package version moves to 6.8.0 with matching package-lock.json, server.json, src/generatedPackageMetadata.ts, docs/installation.md and .release-please-manifest.json. CI regenerates and validates the ignored catalog and skills/; no authored skill instruction changed.

Expected effects:

  • 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/native/PeExceptionDirectory.test.ts (new, 446 lines) covers record decoding, partial coverage, and each tagged failure reason. tests/boundary/filesystem/peResources.test.ts continues to cover resource mapping through the new shared owner.
  • Base reproduction or other evidence: the exception directory has no prior reader in this repository, so there is no base behaviour to regress. The resource reader's behaviour is covered by the existing boundary test, which passes unchanged.
  • User-visible CLI/MCP output (if applicable): none; this is library capability.
  • Remaining proof gaps: the exception-directory reader is not yet surfaced through a CLI command or MCP tool, so it is not reachable by users in this release. PE (32-bit and 64-bit) is covered; ELF, Mach-O and other formats are out of scope for this reader.

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

All commands below were executed on this branch.

  • npm run check:fast — passed (typecheck and lint clean, 0 errors).
  • npx vitest run tests/boundary/native tests/boundary/filesystem/peResources.test.ts src/native — 15 passed.
  • npx vitest run tests/conformance/releaseConfiguration.test.ts — 5 passed.
  • npx vitest run tests/boundary/filesystem/releaseCheckpoint.test.ts — 39 passed.
  • npx vitest run tests/boundary/filesystem/releaseNotes.test.ts — 5 passed.
  • npm run metadata:check — passed.
  • npm run docs:check — passed.
  • npm run test:python — 91 passed.
  • npm run jscpd — 3.40% duplicated lines, no threshold failure.
  • npm run scan:todos — no tech-debt markers.
  • npm run knip — clean.
  • npm pack --dry-run — rea-agents-6.8.0.tgz, 2110 files, 8.1 MB; contains no vault/ path.
  • npm ci --ignore-scripts — succeeded and left package-lock.json unchanged.

Pre-existing failures, not caused by this change

Each was reproduced identically on clean origin/main in a separate worktree.

  • npm run check:pr — test:run was force-killed at the 50-minute task limit; the remaining suite steps (test:python, docs:check, jscpd, scan:todos) pass individually.
  • tests/acceptance/setup/* — 20 failed / 24 passed on origin/main for the same test names; on this branch 5 failed / 39 passed for the same set. Setup and client-configuration tests, unrelated to PE code.
  • tests/boundary/filesystem/analysisSnapshot.test.ts, tests/boundary/filesystem/processCliFileInput.test.ts — 5 failed / 59 passed on origin/main, identical on this branch. Cancellation-timing tests.
  • tests/boundary/mcp/toolSchemaValidity.test.ts — 2 failed / 13 passed on origin/main, identical on this branch. 30s MCP stdio handshake timeouts.
  • tests/acceptance/applications/peResources.test.ts — fails identically on origin/main (30s MCP stdio handshake timeout).

Compatibility, safety, and release

  • Breaking changes or migration steps: none. The release is a minor version under always-bump-minor. PeResourceLayout's public behaviour and messages are unchanged; only the internal owner of PE image facts moved.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable — no provider, browser or OS-specific path changed. The PE reader is exercised through the real-file boundary test (tests/boundary/filesystem/peResources.test.ts), which admits the largest measured stock Windows resource table.
  • Package or release metadata impact: version 6.8.0 across package.json, package-lock.json, server.json, src/generatedPackageMetadata.ts, docs/installation.md and .release-please-manifest.json; CHANGELOG.md has a 6.8.0 section. npm pack --dry-run produces rea-agents-6.8.0.tgz.
  • Security, privacy, process, or containment review: the new reader inspects bytes the caller already supplied. It adds no target execution, no network access and no credential handling, and it reports partial coverage explicitly rather than presenting missing extents as absent.

Author readiness

Human owner:

  • 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. — not applicable; no CLI or MCP surface changes.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

Update: rebased onto current main

main advanced 1,160 commits during review preparation. The branch is rebased onto origin/main at 422ca5a8f and re-verified.

Two rebase resolutions worth review:

  • PeResourceLayout.ts — main had evolved its own inline header parsing. Resolved in favour of the shared PeImageLayout owner, which already carries the three checks main added (RVA range overflows, raw bytes overlap headers, overlapping raw file ranges). Behaviour is preserved; the owner moved.
  • src/generatedPackageMetadata.ts — kept main's new pinnedNodeVersion field alongside the 6.8.0 version bump.

Integration fix found by the rebase

origin/main added PeCertificateParser, which imported readPeHeaders from PeResourceLayout — the exact export this branch had moved into PeImageLayout. The rebase left that import dangling, and typecheck failed with TS2305.

Fixed by exposing the header offsets the parser needs (peOffset, optionalOffset, optionalMagic, directoriesOffset) on PeImageLayout, and reading the security directory through directoryOffset rather than recomputing it. The certificate parser now shares one owner for PE header facts instead of carrying a second reader.

Re-validation after the rebase

Toolchain: pinned Node 24.22.1 / npm 11.19.1 (installed for this; .nvmrc pins 24.22.1 and engines requires ^24.22.1).

  • npm ci --ignore-scripts — succeeded, lockfile unchanged.
  • npm run check:fast — passed.
  • npm run typecheck — passed (was failing TS2305 before the integration fix).
  • npm run build:cached — passed.
  • npx vitest run --project acceptance tests/acceptance/peCertificatesCli.test.ts — 5 passed. This is the suite that exercises the parser I changed.
  • npx vitest run --project boundary --project conformance --project unit — 9169 passed, 3 failed. All three reproduced as failures on origin/main or pass in isolation:
    • productCatalog.test.ts and setupSkill.test.ts — stale generated catalog after the rebase; npm run docs:generate regenerates it and both then pass (27 tests).
    • kunaProvider.test.ts — passes in isolation (31 tests); contention-flaky.
  • npm run metadata:check — passed.
  • npm run docs:check — 9 passed.
  • npm run test:python — 91 passed.
  • npm run jscpd — 3.63% duplicated lines.
  • npm run scan:todos — no tech-debt markers.
  • npm run knip — clean.

Activity

7
A
d284d32
greptile-apps[bot]1mo ago

Confidence Score: 0/5

[Medium impact] The changes reach bounded PE artifact inspection across several native readers.

Do not merge yet: resource and certificate inspection regress, and the earlier memory, file-lifetime, and release blockers remain.

Findings

  1.  Empty resources stop inspection ▶
  2.  Resource overlap checks change ▶
  3.  Readable certificates become unavailable ▶
  4.   Large directories exhaust memory ▶
  5.  Valid headers look truncated ▶
  6.  Failed closes lose results ▶
  7.  Release baseline advances too early ▶
  8.  Lookups miss retained functions ▶
  9.  Ambiguous sections produce trusted bounds ▶
  10.  Missing bytes look complete ▶
  11.  PE readers still duplicate facts ▶
  12.  Tests bypass required cleanup ▶
  13.  Tests discard useful errors ▶
  14.  File errors bypass tagged results ▶
Fix with agent prompt
### Issue 1
src/native/pe/PeResourceLayout.ts:48-51
When an empty resource sits exactly at its section's virtual end, the strict `< peVirtualExtent(section)` filter leaves no candidate. `map` then throws, losing the entire resource report. The existing test at `PeResourceParser.test.ts:377` requires this case to succeed.

Restore the endpoint fallback when no section owns the address, while keeping the file-backed check.

### Issue 2
src/native/pe/PeResourceLayout.ts:54-57
Replacing `intersectsResource` loses two existing rules:
- A section with zero extent inside a requested range now falsely counts as an overlap, rejecting the resource report.
- An empty header payload at a positive-extent section's start now misses the conflict and receives a header location.

Restore the positive-extent guard and the point check for empty resources in both overlap branches. Existing tests cover both cases.

### Issue 3
src/native/pe/PeCertificateParser.ts:57-59
`parsePeCertificates` now rejects an intact certificate table when unrelated sections overlap in the file, declare bytes outside the file, or overflow their RVA range. Unlike the old header-only reader, `readPeImageLayout` checks these declarations before the certificate table is examined.

The security directory uses a file offset, so reading it does not need these section checks. Share the decoded header facts without forcing resource mapping requirements onto certificate inspection.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

### Issue 4
src/native/PeExceptionDirectory.ts:429-433
`inspectPeExceptionDirectory` allocates the entire file-backed directory before checking its memory cost. A large or sparse PE can pass the section and file bounds and request gigabytes here. Decoding then allocates up to five more arrays sized from those records. This can exhaust the caller's memory instead of returning a tagged failure.

The repository requires accounting for representation expansion before allocation. Enforce a shared byte/record allowance before both the file read and decoding.

**How this was verified:** The inspected file's directory and section sizes determine `available`, which reaches `Buffer.alloc` and the record-sized arrays without a memory allowance.

### Issue 5
src/native/pe/PeImageLayout.ts:undefined-387
`peHeaderBytes` cannot widen the initial window when the PE header itself falls outside it. For example, a valid image with `e_lfanew = 0x1100` gets only the first `0x1000` bytes read. This check returns `undefined`, so `inspectPeExceptionDirectory` skips the wider read and reports `truncated-header`, even though parsing the full buffer works. Read the COFF header at the declared offset first, then use it to size the remaining header reads.

### Issue 6
src/native/PeExceptionDirectory.ts:435-436
A rejected `handle.close()` replaces the pending result or earlier read error, and no owner retains the handle for retry. This loses both the inspection outcome and the cleanup path. The repository requires descriptor-backed reads to have an owner before opening and to retain failed closes with earlier outcomes. Use the existing owned-file helpers rather than a bare `open`/`finally` pair.

### Issue 7
.release-please-manifest.json:undefined-2
This changes the published release baseline to `6.8.0` inside a feature PR. Merging a feature branch does not run the release-creation job, which only accepts Release Please branch names. The next checkpoint nevertheless reads this manifest as the published baseline: preparing the intended `6.8.0` fails the “must advance” check, while a later version requires a published `6.8.0` tag that this merge does not create.

Leave the version changes for the actual release PR so the baseline advances with publication.

### Issue 8
src/native/PeExceptionDirectory.ts:334-338
The decoder keeps overlapping extents, but both lookup methods assume they are disjoint. With records `[0x1000, 0x1100)` and `[0x1020, 0x1030)`, `functionAt(0x1040)` returns `undefined`, and `extentsIn(0x1040, 1)` yields nothing, despite the first retained extent covering that address. Either reject and report overlaps when decoding, or build lookups that handle every retained interval.

### Issue 9
src/native/PeExceptionDirectory.ts:155-160
Checking `sectionAt` only at the directory's start does not establish an unambiguous mapping for its full range. Two sections with separate file ranges can overlap later in RVA space. A directory starting before that overlap is accepted and decoded using the first section's bytes throughout.

The new `fileRange` method has the same gap, while the resource mapper explicitly rejects it. Put the full-interval check in the shared owner and use it from the exception reader.

### Issue 10
src/native/PeExceptionDirectory.ts:268-272
Flooring both sizes to whole records can hide an incomplete directory. If `declaredSize` is 13 and only 12 bytes are available, one valid record produces `coverage: 1` and `complete: true`, with no partial-read warning. That contradicts the range contract that fewer bytes than `declaredSize` must mean a partial read. Reject a trailing partial record as malformed, or include unread trailing bytes in the completeness decision.

### Issue 11
src/native/pe/PeImageLayout.ts:255-263
The shared-owner refactor still leaves PE headers and section facts parsed independently. `readPeImage` reads the optional header and data directories itself, and `readPeSectionDirectory` separately reads the COFF header and section table. This new loop repeats those facts again.

The repository requires consumers to use the owner's parsed facts and directly related duplicate interpretation to be removed. Share the structural decoder with those readers too, while keeping their admission and mapping policies separate. This repository requirement must be satisfied before merging.

### Issue 12
src/native/PeExceptionDirectory.test.ts:409-414
These file tests create a suite-wide temporary directory directly with `mkdtemp`. The repository requires `createTestTempDirectory` for exact-path, awaited cleanup, including failures and timeouts. Use that helper per test instead of adding another `beforeAll`/`afterAll` cleanup path. This repository requirement must be satisfied before merging.

### Issue 13
src/native/PeExceptionDirectory.test.ts:150-152
The successful `Result` tests assert `ok` and then return on failure. The testing guide explicitly requires throwing the typed error before asserting successful values; the preceding `ok` assertion adds no coverage. Apply that pattern here and throughout the new success cases so failures show the actual parser error. The same pattern appears in both file-versus-memory checks. This repository requirement must be satisfied before merging.

### Issue 14
src/native/PeExceptionDirectory.ts:413-416
A missing or unreadable path makes `inspectPeExceptionDirectory` reject at `open` instead of returning a tagged failure. File read errors take the same unhandled path. Callers therefore need a second error channel alongside the advertised `Result`.

The repository requires expected boundary failures to use the tagged error algebra. Add file-access failure cases and return them through `Result`. This repository requirement must be satisfied before merging.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds PeImageLayout for shared PE facts and PeExceptionDirectory for function extents, coverage, and tagged failures.

  • PE resource and certificate readers now share one source for image facts.
  • PE images can now report measured function extents from their Exception Directory.
  • The published package and setup examples now use version 6.8.0.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  B["PE bytes"] --> L["PeImageLayout"]
  L --> R["PeResourceLayout"]
  R --> P["Resource reader"]
  L --> C["PeCertificateParser"]
  L --> E["PeExceptionDirectory"]
  E --> F["Function extents and coverage"]

Reviews (2) · Last reviewed commit: "fix(pe): route the certificate parser th..." · Reviewed by Greptile

This pull request is a draft

Merging is unavailable until it is marked ready for review.