Skip to content

feat(artifacts): inventory and extract cpio archives and Linux initramfs images - #15083

Open
TYFSADIK wants to merge 2 commits into
morluto:mainfrom
TYFSADIK:feat/cpio-archives
Open

TYFSADIK wants to merge 2 commits into
morluto:mainfrom
TYFSADIK:feat/cpio-archives

Conversation

@TYFSADIK

Copy link
Copy Markdown

Summary

rea inspect-artifact and extract-artifact refused standalone cpio archives with file_format_rejected, so a Linux initramfs, an RPM payload or a ramdisk carved from a boot image needed cpio on another host. This adds a cpio artifact format that inventories and extracts them like tar, including the concatenated stored + compressed segments of an x86 initramfs. Refs #15082 (the issue also proposes ar, which would be a separate PR).

Problem and expected behavior

On 4dafa3a58, a GNU cpio 2.15 -H newc archive:

$ rea inspect-artifact root-newc.cpio
error: Analysis failed
code: target_unavailable
details:
  reason: unsupported binary format
  constraint: file_format_rejected

Expected: members with mode, owner, link count, mtime and link targets, as for tar; for a dracut-style initramfs, both the early-microcode archive and the compressed root archive behind it.

Change and scope

Two commits:

  1. refactor(artifacts): the plain and gzip byte streams the tar walk reads move to CarrierByteStream with a caller-named format and an optional start offset (a second segment starts inside the file); the gzip stream reports the file offset where its member ended. The RFC 1952 header helpers move from tarFormat to gzipMember, and the bounded gzip probe is split from its tar check, so cpio does not carry a second copy. Tar behaviour and messages are unchanged.
  2. feat(artifacts): src/domain/cpioFormat.ts parses the newc (070701), crc (070702) and odc (070707) headers (cpio(5)); src/artifacts/cpio/ walks and reads them, modelled on the tar reader.
    • Regular files, directories and symlinks are occurrences (cpio-entry metadata: segment, dialect, offsets, inode, mode, uid, gid, nlink, mtime, crc checksums). Devices, FIFOs and sockets are omissions.
    • newc/crc hard links: the data-less names are omissions and the name that stores the data is the member (GNU cpio writes it with the last name). odc stores each copy, so each is a member.
    • crc checksums are checked for regular files only; GNU cpio and libarchive write 0 for other members.
    • After a trailer the walk skips zero padding and continues with another header, a gzip member as a new segment, or names a zstd/xz/lz4/bzip2/LZMA/LZO segment in a limitation without reading it (coverage unknown). Root cpio metadata lists the segments with offset, compression, dialects, archive/member counts and end state.
    • A first header that is not cpio, or whose name is not NUL-terminated, refuses the file; later malformed/truncated headers, a missing trailer or a damaged gzip stream keep earlier members with unknown coverage.
    • Bounds: artifact_limits.cpio.name_bytes (64 KiB), artifact_limits.cpio.metadata_bytes (64 MiB), and artifact_limits.expanded_bytes for decompression.

Not included: the old binary cpio format (0x71c7), decompressing zstd/xz/lz4 segments (REA has no bounded decoder wired for archive streams), ar (separate PR), and replacing src/artifacts/macosPkg/CpioOdc.ts (the .pkg payload reader keeps its in-memory odc parser; moving it onto this walk could be a follow-up if wanted).

Contract and boundary impact

  • Semantic owner and earliest changed stage: src/domain/cpioFormat.ts owns header facts; CpioWalk owns segment and member facts; CpioArtifactReader projects them. Byte streams are shared with tar through CarrierByteStream; the gzip probe through gzipMember.

  • Contribution scope fit and linked maintainer decision: format inspection and ordinary archive extraction (listed as supported in CONTRIBUTING); issue [Feature] Inventory standalone cpio (initramfs, newc/crc/odc) and Unix ar (static library) archives #15082 opened for the scope decision, pending.

  • CLI and MCP/tool-catalog contract: new artifact format cpio, new metadata kinds cpio and cpio-entry, new artifact_limits.cpio per-call group; compare-artifacts compares cpio-entry mode (docs/reference/mcp-contracts.md updated).

  • Provider, bridge, target-format, or platform compatibility: cpio added to target formats as an archive; no provider changes.

  • Evidence, artifact, provenance, or reconstruction contract: occurrences as for tar; gzip-segment source_location is null (offsets are decompressed positions).

  • Target selection, authority, upstream behavior, and cleanup details: not applicable (read-only, existing extraction path).

  • Generated metadata, package, or installation impact: none committed.

  • 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/artifacts/cpio/CpioArtifactReader.test.ts (20): recognition of the three dialects and gzip, refusal reasons, each dialect's inventory and data, stored+gzip segments, two archives in one stream, an unread zstd segment, data after the trailer, hard links, crc checksums (regular files only), FIFOs, ./ prefixes, corrupt later header, truncated member, missing trailer, first-header refusal, name_bytes and expanded_bytes limits.
    • tests/acceptance/cpioArchiveCli.test.ts (4): inventory and extraction through the compiled CLI for a stored archive, a gzip archive and a microcode + gzip initramfs; malformed first header.
    • tests/boundary/mcp/cpioArchiveMcp.test.ts (1): segments, paged member view and extraction through MCP.
    • tests/support/targetFailure/readers/containers.ts: cpio-first-name-unterminated in the target-failure conformance suite (CLI and MCP).
    • TargetFormatVocabularies.test.ts, artifactComparisonDocs contract text.
  • Base reproduction or other evidence: archives written by GNU cpio 2.15 (Debian trixie) in newc, crc and odc, a gzip archive, and a dracut-layout microcode.cpio + root.cpio.gz concatenation, inspected with the built CLI and compared by hand with cpio -itv: names, sizes, modes, symlink targets, FIFO and hard-link layout matched. Extracted bin/busybox (70 000 random bytes), init, etc/hostname.link and the microcode file had the same SHA-256 as the archive data. The first run found a false crc mismatch on GNU's symlink (check=0), which is why only regular files are checked.
  • User-visible CLI/MCP output (built CLI, dracut-layout image):
root format_metadata
{"kind":"cpio","segments":[{"offset":0,"compression":"none","dialects":["newc"],"archives":1,"member_count":4,"stream_bytes":1024,"end_state":"trailer","end_offset":644},{"offset":1024,"compression":"gzip","dialects":["newc"],"archives":1,"member_count":9,"stream_bytes":71680,"end_state":"trailer","end_offset":71476}],"member_count":13,"trailing_nonzero_bytes":0,"checksum_mismatches":0}
  • Remaining proof gaps: no archives from libarchive bsdcpio, the kernel's gen_init_cpio, or real distribution initramfs images; no Windows run.

  • 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 27 (arm64), Node 24.22.1, npm 11.21.3:

  • npm run check:fast — typecheck and lint passed; architecture guards passed across 3331 source files.
  • npm run test:focused -- <cpio, tar, conformance and recognition files> — 10 files, 197 tests passed.
  • npm run test:focused -- <46 files that reference tar, the format registry or reader limits> — 1143 passed, 40 skipped (platform/provider gated).
  • npm run test:focused -- tests/acceptance/targetFailureConformance.test.ts — 69 passed.
  • npm run verify:test-discovery — 4074 test files discovered once.
  • npm run docs:check — passed.
  • oxfmt --check on changed files — passed.

Compatibility, safety, and release

  • Breaking changes or migration steps: none. Files previously refused as unsupported are now read as cpio; gzipTarExtraFieldProbeBytes is renamed gzipExtraFieldProbeBytes (internal).
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: read-only; extraction uses the existing contained path (symlinks are not materialised, as for tar); names, link targets, metadata and decompression are bounded.

Author readiness

Human owner: @TYFSADIK

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

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

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

The plain and gzip byte streams the tar walk reads were tar-only in name
and in their read-failure label, and the gzip stream could only start at
file offset 0. Move them to CarrierByteStream with the format named by the
caller and an optional start offset, so another archive reader can walk a
stream that begins inside the file, as the second segment of a
concatenated archive does. The gzip stream also reports the file offset
where its member ended.

Move the RFC 1952 member-header helpers from tarFormat to gzipMember, and
split the bounded gzip probe from its tar check, so a reader asks what a
gzip member starts with without its own copy of the header walk. The
prefix-extension helper drops "tar" from its name for the same reason;
its two callers are updated.

Tar behaviour and its failure messages are unchanged.
…mfs images

Standalone cpio archives were refused as an unsupported binary format, so
an initramfs, an RPM payload or a ramdisk carved from a boot image needed
cpio on another host. Recognize the newc (070701), crc (070702) and odc
(070707) headers, plain or as the first bytes of a gzip member, as the new
cpio artifact format, and inventory and extract it like tar.

The walk reads every header once. Regular files, directories and symbolic
links become occurrences with mode, owner, link count and mtime; a link's
target is its stored data. Devices, FIFOs and sockets are omissions. In
newc and crc a hard-linked file stores its data once; its data-less names
are omissions and the name that stores it is the member. The crc dialect's
checksum is checked for regular files, the only members GNU cpio and
libarchive sum.

After a trailer the walk skips zero padding and continues: another header
in the same stream, a gzip member as a new segment read by forward
decompression, or a zstd, xz, lz4, bzip2, LZMA or LZO segment named in a
limitation and not read. This covers the uncompressed early-microcode
archive dracut and mkinitramfs put before the compressed root archive.
Segments are reported in order with their offset, compression, dialects,
archive and member counts and end state.

A first header that is not cpio, or whose name is not NUL-terminated,
refuses the file. A later malformed or truncated header, a missing trailer
or a damaged gzip stream keeps the members read so far with unknown
coverage. Names and link targets are bounded by
artifact_limits.cpio.name_bytes, retained metadata by
artifact_limits.cpio.metadata_bytes, and decompression by
artifact_limits.expanded_bytes.

Refs morluto#15082
members.splice(index, 1);
omissions.push({ path: link.path, kind: "unsupported" });
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 security Hard links pin the CPU

Hostile cpio archive can pin the CPU for minutes, and the analyst cannot cancel it. After the walk, walkCpio resolves newc/crc hard links by running members.findIndex — a linear scan of the whole member list — once per data-less link name, inside a fully synchronous double loop. Nothing bounds this work: pendingLinks is not charged to any budget, and assertArtifactReadActive(signal) cannot fire during the loop, so an abort or Ctrl-C cannot interrupt it.

With the default artifact_limits.cpio.metadata_bytes of 64 MiB, about 126,000 members fit (512 + 2×path bytes each). An archive that lists its non-zero data members first and its ~63,000 zero-size link names last forces roughly 6×10⁹ path comparisons, on the order of minutes of blocked event loop per inspect-artifact or extract-artifact call — a ~15 MB file (smaller gzipped) is enough. The metadata_bytes limit is meant to bound exactly this retained-member work, but the resolution loop turns the members it admits into quadratic effort.

Fix the root cause rather than the symptom: build a path-to-index map of zero-size members once and resolve links through it (or charge link-resolution work to the metadata budget), instead of scanning the member list once per link.

@greptile-apps

greptile-apps Bot commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

security Security Review

This PR appears safe to merge from a security standpoint.

What was checked
  • Traced cpio member names through inventory and extraction: normalizeArtifactPath rejects absolute, .., NUL and non-normalized names before any file is written, and symlink entries are never materialized, matching tar.
  • Checked gzip decompression bounds: every decompressed byte, including bytes queued while idle, is charged to the expanded_bytes budget and the stream is destroyed when it refuses, so a gzip-bomb-style archive stops at the allowance.
  • Checked the walk's other bounds: member names are capped at 64 KiB, retained metadata at 64 MiB, the recognition probe inflates at most ~4 MiB, and the segment loop cannot accumulate unbounded segment records.
  • Confirmed no secrets, no dependency changes, and that the tar refactor keeps tar's recognition, limits and extraction behavior unchanged.
  • Checked for superseding work: origin/main has no cpio reader after this PR's base, and the old src/artifacts/CpioArtifactReader.ts history is an abandoned macOS-pkg lineage, not a competing implementation.

Findings

  • P2 Hard links pin the CPU ▶

@greptile-apps

greptile-apps Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 0/5 · Fix the archive-boundary, hard-link and memory-limit failures before merging.RetriggerView in GreptileConfidence Score: 0/5 Tier: plus

[Medium impact] The PR extends the existing artifact inspection and extraction workflows to cpio archives.

Fix the archive-boundary, hard-link and memory-limit failures before merging.

Findings

  1. P1 Gzip hides the next archive ▶
  2. P1 Hard links cross archive boundaries ▶
  3. P1 Hard links freeze the process ▶
  4. P1 Security Names bypass the memory limit ▶
  5. P1 Padding hides the next archive ▶
  6. P2 Checksums ignore the work limit ▶
  7. P2 Hard links pin the CPU ▶
Fix with agent prompt
### Issue 1
src/artifacts/cpio/CpioWalk.ts:315-320
`GzipCarrierStream` reads the rest of the file with `createGunzip`, which does not stop at one gzip member. For a valid initramfs laid out as `gzip(cpio A) + cpio B` without intervening zeros, Node treats the stored header as another gzip header and raises `Z_DATA_ERROR`. The probe can reject the image, and the walk cannot reach archive B.

Read gzip members separately and return their exact end offsets. Cover both compressed-to-stored and stored-to-compressed layouts.

### Issue 2
src/artifacts/cpio/CpioWalk.ts:749-755
Hard-link groups survive across `TRAILER!!!`, but their key contains only the segment, device and inode. Two independent archives in one stored stream therefore share a group when their inode numbers match. An empty hard-link group in archive A is removed if archive B reuses that inode for a non-empty group. Valid files then disappear from inventory and extraction.

Scope link groups to each archive and track the exact member being omitted rather than finding it again by path.

### Issue 3
src/artifacts/cpio/CpioWalk.ts:403-413
Each pending hard link scans `members` with `findIndex` and then shifts the array with `splice`. An archive with 40,000 ordinary files followed by 40,000 data-less links fits the default metadata allowance but causes roughly 1.6 billion path checks, plus array shifts. This loop never yields, so the CLI or MCP server cannot respond to cancellation.

Resolve links with stored member identities and one linear filter.

### Issue 4
src/artifacts/cpio/CpioWalk.ts:730-738
The metadata charge uses the shortened `path`, but the member also retains the full `sourcePath`. A name made from thousands of `./` prefixes followed by `f` costs only 514 bytes here while retaining nearly 64 KiB of text. Repeating such members bypasses `artifact_limits.cpio.metadata_bytes` and can exhaust memory.

Charge the full retained name before keeping it. This also violates the repository requirement to account for representation growth before allocation.

> **How this was verified:** Archive names lose repeated `./` prefixes before the charge, while each member retains the original name as `sourcePath`.

### Issue 5
src/artifacts/cpio/CpioWalk.ts:221-227
`nextNonZero` returns only the remainder of its current chunk, which may contain fewer than six bytes of the next header. Inside gzip, the trailer branch treats that short prefix as trailing junk and discards the next archive. For example, a 124-byte newc trailer followed by 65,532 zero bytes leaves only `0707` in the lookahead chunk even when a complete archive follows.

Gather enough bytes to identify the next format before deciding that it is junk.

### Issue 6
src/artifacts/cpio/CpioWalk.ts:625-626
The stored `crc` preparation pass reads and sums every regular file without charging `artifact_limits.expanded_bytes`. A caller with a small plaintext-work allowance therefore pays for the whole checksum pass before a later member read can refuse it.

Charge these stored-data reads before reading each chunk, without charging gzip output twice.

### Issue 7
src/artifacts/cpio/CpioWalk.ts:undefined-416
**Hostile cpio archive can pin the CPU for minutes, and the analyst cannot cancel it.** After the walk, `walkCpio` resolves newc/crc hard links by running `members.findIndex` - a linear scan of the whole member list - once per data-less link name, inside a fully synchronous double loop. Nothing bounds this work: `pendingLinks` is not charged to any budget, and `assertArtifactReadActive(signal)` cannot fire during the loop, so an abort or Ctrl-C cannot interrupt it.

With the default `artifact_limits.cpio.metadata_bytes` of 64 MiB, about 126,000 members fit (512 + 2×path bytes each). An archive that lists its non-zero data members first and its ~63,000 zero-size link names last forces roughly 6×10⁹ path comparisons, on the order of minutes of blocked event loop per `inspect-artifact` or `extract-artifact` call - a ~15 MB file (smaller gzipped) is enough. The `metadata_bytes` limit is meant to bound exactly this retained-member work, but the resolution loop turns the members it admits into quadratic effort.

Fix the root cause rather than the symptom: build a path-to-index map of zero-size members once and resolve links through it (or charge link-resolution work to the metadata budget), instead of scanning the member list once per link.

<!-- greptile-security:61290:finding:0 -->

---

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

Summary

Adds newc, crc and odc inventory and extraction, including stored and gzip initramfs segments. Tar and cpio now share byte streams and gzip probing.

  • REA now inventories and extracts stored and gzip cpio archives.
  • Tar and cpio now use the same archive byte-stream helpers.

Acknowledged exclusions from TYFSADIK: old binary cpio, decoding the listed non-gzip compression formats, ar, and replacing the macOS package parser are intentionally outside this PR. TYFSADIK also states that Windows, real distribution images, libarchive and kernel-generated archives remain unverified.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Selected archive] --> B[Recognize cpio or gzip]
  B --> C[Open carrier stream]
  C --> D[Walk headers and trailers]
  D --> E[Retain members and omissions]
  D --> F{What follows a trailer?}
  F -->|cpio header| D
  F -->|another carrier segment| C
  F -->|unsupported compression or junk| G[Keep partial inventory]
  E --> H[Hash and classify regular files]
  H --> I[Inventory and comparison]
  H --> J[Contained extraction]
Loading

Reviews (1) · Last reviewed commit: "feat(artifacts): inventory and extract c..." · Reviewed by Greptile

Comment on lines +315 to +320
const stream: CarrierByteStream =
compression === "gzip"
? new GzipCarrierStream(handle, size, charge, {
format: CPIO_STREAM,
start: carrierOffset,
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Gzip hides the next archive

GzipCarrierStream reads the rest of the file with createGunzip, which does not stop at one gzip member. For a valid initramfs laid out as gzip(cpio A) + cpio B without intervening zeros, Node treats the stored header as another gzip header and raises Z_DATA_ERROR. The probe can reject the image, and the walk cannot reach archive B.

Read gzip members separately and return their exact end offsets. Cover both compressed-to-stored and stored-to-compressed layouts.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/artifacts/cpio/CpioWalk.ts
Line: 315-320

Comment:
**Gzip hides the next archive**

`GzipCarrierStream` reads the rest of the file with `createGunzip`, which does not stop at one gzip member. For a valid initramfs laid out as `gzip(cpio A) + cpio B` without intervening zeros, Node treats the stored header as another gzip header and raises `Z_DATA_ERROR`. The probe can reject the image, and the walk cannot reach archive B.

Read gzip members separately and return their exact end offsets. Cover both compressed-to-stored and stored-to-compressed layouts.

---

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

Comment on lines +749 to +755
if (kind === "file" && header.dialect !== "odc" && header.nlink > 1) {
const inode = `${String(member.segment)}:${String(header.devMajor)}:${String(header.devMinor)}:${String(header.inode)}`;
if (header.fileSize === 0) {
const links = context.pendingLinks.get(inode) ?? [];
links.push({ path });
context.pendingLinks.set(inode, links);
} else context.linkedInodes.add(inode);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Hard links cross archive boundaries

Hard-link groups survive across TRAILER!!!, but their key contains only the segment, device and inode. Two independent archives in one stored stream therefore share a group when their inode numbers match. An empty hard-link group in archive A is removed if archive B reuses that inode for a non-empty group. Valid files then disappear from inventory and extraction.

Scope link groups to each archive and track the exact member being omitted rather than finding it again by path.

Knowledge Base Used: Artifact and application analysis

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/artifacts/cpio/CpioWalk.ts
Line: 749-755

Comment:
**Hard links cross archive boundaries**

Hard-link groups survive across `TRAILER!!!`, but their key contains only the segment, device and inode. Two independent archives in one stored stream therefore share a group when their inode numbers match. An empty hard-link group in archive A is removed if archive B reuses that inode for a non-empty group. Valid files then disappear from inventory and extraction.

Scope link groups to each archive and track the exact member being omitted rather than finding it again by path.

**Knowledge Base Used:** [Artifact and application analysis](https://app.greptile.com/-/switch-tenant?tenant=pre&next=%2Fcustom-context%2Fknowledge-base%2Fmorluto%2Frea%2F-%2Fdocs%2Fartifact-and-application-analysis.md)

---

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

Comment on lines +403 to +413
for (const [inode, links] of pendingLinks) {
if (!linkedInodes.has(inode)) continue;
for (const link of links) {
const index = members.findIndex(
(member) =>
member.path === link.path &&
member.kind === "file" &&
member.size === 0,
);
if (index === -1) continue;
members.splice(index, 1);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Hard links freeze the process

Each pending hard link scans members with findIndex and then shifts the array with splice. An archive with 40,000 ordinary files followed by 40,000 data-less links fits the default metadata allowance but causes roughly 1.6 billion path checks, plus array shifts. This loop never yields, so the CLI or MCP server cannot respond to cancellation.

Resolve links with stored member identities and one linear filter.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/artifacts/cpio/CpioWalk.ts
Line: 403-413

Comment:
**Hard links freeze the process**

Each pending hard link scans `members` with `findIndex` and then shifts the array with `splice`. An archive with 40,000 ordinary files followed by 40,000 data-less links fits the default metadata allowance but causes roughly 1.6 billion path checks, plus array shifts. This loop never yields, so the CLI or MCP server cannot respond to cancellation.

Resolve links with stored member identities and one linear filter.

---

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

Comment on lines +730 to +738
const sourcePath = name;
const path = withoutCurrentDirectoryPrefix(name);
// The archive's own `.` directory carries no occurrence.
if (type === "directory" && /^(?:\.\/?)?$/u.test(name)) return;
context.retained.charge(
MEMBER_OVERHEAD_BYTES +
2 * Buffer.byteLength(path) +
// Each target byte becomes retained text and two UTF-16 hex digits.
6 * (member.linkTarget?.length ?? 0),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 security Names bypass the memory limit

The metadata charge uses the shortened path, but the member also retains the full sourcePath. A name made from thousands of ./ prefixes followed by f costs only 514 bytes here while retaining nearly 64 KiB of text. Repeating such members bypasses artifact_limits.cpio.metadata_bytes and can exhaust memory.

Charge the full retained name before keeping it. This also violates the repository requirement to account for representation growth before allocation.

How this was verified: Archive names lose repeated ./ prefixes before the charge, while each member retains the original name as sourcePath.

Context Used: AGENTS.md (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/artifacts/cpio/CpioWalk.ts
Line: 730-738

Comment:
**Names bypass the memory limit**

The metadata charge uses the shortened `path`, but the member also retains the full `sourcePath`. A name made from thousands of `./` prefixes followed by `f` costs only 514 bytes here while retaining nearly 64 KiB of text. Repeating such members bypasses `artifact_limits.cpio.metadata_bytes` and can exhaust memory.

Charge the full retained name before keeping it. This also violates the repository requirement to account for representation growth before allocation.

> **How this was verified:** Archive names lose repeated `./` prefixes before the charge, while each member retains the original name as `sourcePath`.

**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))

---

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

Comment on lines +221 to +227
const chunk = await input.read(SCAN_CHUNK_BYTES, signal);
if (chunk.length === 0) return null;
const first = chunk.findIndex((byte) => byte !== 0);
if (first === -1) continue;
const rest = chunk.subarray(first);
input.unread(Buffer.from(rest));
return { offset: offset + first, bytes: rest };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Padding hides the next archive

nextNonZero returns only the remainder of its current chunk, which may contain fewer than six bytes of the next header. Inside gzip, the trailer branch treats that short prefix as trailing junk and discards the next archive. For example, a 124-byte newc trailer followed by 65,532 zero bytes leaves only 0707 in the lookahead chunk even when a complete archive follows.

Gather enough bytes to identify the next format before deciding that it is junk.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/artifacts/cpio/CpioWalk.ts
Line: 221-227

Comment:
**Padding hides the next archive**

`nextNonZero` returns only the remainder of its current chunk, which may contain fewer than six bytes of the next header. Inside gzip, the trailer branch treats that short prefix as trailing junk and discards the next archive. For example, a 124-byte newc trailer followed by 65,532 zero bytes leaves only `0707` in the lookahead chunk even when a complete archive follows.

Gather enough bytes to identify the next format before deciding that it is junk.

---

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

Comment on lines +625 to +626
} else if (dialect === "crc" && type === "file") {
const summed = await checksumData(input, size, signal);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Checksums ignore the work limit

The stored crc preparation pass reads and sums every regular file without charging artifact_limits.expanded_bytes. A caller with a small plaintext-work allowance therefore pays for the whole checksum pass before a later member read can refuse it.

Charge these stored-data reads before reading each chunk, without charging gzip output twice.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/artifacts/cpio/CpioWalk.ts
Line: 625-626

Comment:
**Checksums ignore the work limit**

The stored `crc` preparation pass reads and sums every regular file without charging `artifact_limits.expanded_bytes`. A caller with a small plaintext-work allowance therefore pays for the whole checksum pass before a later member read can refuse it.

Charge these stored-data reads before reading each chunk, without charging gzip output twice.

---

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

@TYFSADIK
TYFSADIK marked this pull request as ready for review November 29, 2026 06:14
@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-29T06:21:00.813516Z 132673f 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 chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 132673f425

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +135 to 139
const split = Math.max(start, size - GZIP_TRAILER_BYTES);
if (split > start)
yield* readFileHandleChunks(handle, { start, end: split - 1 });
if (size > split)
yield* readFileHandleChunks(handle, { start: split, end: size - 1 });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Stop gzip reads at the cpio segment boundary

For a valid gzip-compressed cpio archive followed by a plain cpio or unread compressed segment, this generator feeds the entire remaining file to gunzip; Node then reports incorrect header check on the next segment, so walkSegment records a malformed gzip end before the outer loop can inspect carrierEnd and the later archive is never inventoried. Stop at the gzip member boundary and return the unread carrier bytes to segment detection.

AGENTS.md reference: AGENTS.md:L33-L33

Useful? React with 👍 / 👎.

Comment on lines +626 to +627
const summed = await checksumData(input, size, signal);
computedChecksum = summed.sum;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Charge stored CRC payloads during preparation

For an uncompressed crc archive with a regular member larger than the caller's expanded_bytes budget, checksumData consumes the full payload here, but only the gzip stream calls charge; PlainCarrierStream does not, so a caller that only enumerates entries() can scan more plaintext than the selected budget. Charge this read on the stored path too.

AGENTS.md reference: AGENTS.md:L70-L70

Useful? React with 👍 / 👎.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant