Skip to content

feat(artifacts): inventory and expand Android sparse images offline - #13244

Merged
vincentkoc merged 17 commits into
morluto:mainfrom
mvanhorn:fix/android-sparse-image
Nov 26, 2026
Merged

vincentkoc merged 17 commits into
morluto:mainfrom
mvanhorn:fix/android-sparse-image

Conversation

@mvanhorn

@mvanhorn mvanhorn commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Android factory images and OTA packages ship partitions such as system.img and vendor.img in the Android sparse format. REA does not recognize that format today, so an analyst gets an opaque blob and has to run simg2img outside REA before any further inspection, which breaks Evidence provenance between the shipped file and the expanded partition.

This adds an offline android-sparse-image artifact format. inspect-artifact and extract-artifact (and the MCP inspect_artifact / extract_artifact tools) now read the sparse header and chunk table, report what the image contains, and expand it to one raw partition image child without any host tool. No issue exists for this; it is a format-inspection and ordinary-extraction addition within the supported contribution scope.

Problem and expected behavior

Use case: given a sparse system.img, see its block size, expanded size and chunk layout, then get the raw partition image so REA's existing filesystem readers can continue from it.

Observable outcome:

  • A file with sparse magic 0xed26ff3a and a version 1 header is recognized as android-sparse-image regardless of filename. A readable but unsupported major version is refused as unsupported; a short version 1 header is reported as truncated.
  • The inventory reports header fields, per-type chunk counts (RAW, FILL, DONT_CARE, CRC32), bytes covered per type, distinct FILL patterns, and stored CRC32 values with their file offsets.
  • Extraction streams one expanded raw image: RAW chunks are copied, FILL chunks repeat their 4-byte pattern, DONT_CARE chunks become zeros with a limitation saying the original contents are unknown.
  • Stored image and CRC32 checksums are recorded and never verified (checksums_verified: false).

Change and scope

  • src/domain/firmware/androidSparseImage.ts owns parsing: header validation, chunk table walk with per-chunk size checks against the declared block count, and a safe-integer ceiling for stored RAW sizes. Malformed chunks are reported with the offending field and file offset.
  • src/artifacts/AndroidSparseImageArtifactReader.ts reads the fixed 28-byte header and only its declared extension before admission, then walks and expands through one bounded 64 KiB read window. Small adjacent RAW payloads are served from that window; large RAW runs stream directly. FILL and DONT_CARE output is written into a shared 64 KiB buffer, and the reader yields per 1 MiB of output with a cancellation check between runs.
  • New per-call limit artifact_limits.android_sparse_image.chunk_count (default 1,048,576, range 1..2^31-1) in src/domain/artifactReaderLimits.ts, shared by the CLI --artifact-limits flag and the MCP artifact_limits argument. Expansion size is still governed by artifact_limits.expanded_bytes. Previously recorded inventory Evidence without this group still parses; no value is backfilled for operations that never applied it.
  • Docs: new docs/guides/firmware/android-sparse-image.md, the artifact reader section of docs/reference/limits-and-recovery.md, CLI, firmware-analysis and skill reference updates.

Not included: checksum verification, sparse format version 2 or later, and mounting or interpreting the expanded filesystem (existing readers handle that from the extracted child).

Contract and boundary impact

  • Semantic owner and earliest changed stage: androidSparseImage.ts produces parsed facts; the reader, inventory view and graph consume them without reparsing raw bytes.
  • Contribution scope fit and linked maintainer decision: format inspection and ordinary extraction of a local file; not applicable (no target execution, injection, mutation, or protection recovery).
  • CLI and MCP/tool-catalog contract: one new optional artifact_limits group, android_sparse_image.chunk_count, on the existing artifact tools. effective_limits reports it. No new tools.
  • Provider, bridge, target-format, or platform compatibility: new target format android-sparse-image; existing formats unchanged.
  • Evidence, artifact, provenance, or reconstruction contract: new android-sparse-image metadata shape; the expanded child carries its stored range and SHA-256. Older inventory Evidence remains readable.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): not applicable.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact: none committed; the catalog is regenerated by the build. Authored skill references updated under .agents/skills/reverse-engineer-anything/.

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/domain/firmware/androidSparseImage.test.ts (header and chunk parsing, refusal versus truncation, oversized chunk sizes reported at the chunk field, a 1,048,577-chunk table), AndroidSparseImageArtifactReader.test.ts and .boundaries.test.ts (exact expanded bytes across window boundaries, read counts and read ranges for admission and expansion, chunk-count refusal with required_value and successful retry), tests/acceptance/androidSparseImageCli.test.ts, tests/boundary/mcp/androidSparseImageMcp.test.ts (refusal at chunk_count: 3 with required_value: 4, then success with 4), plus format recognition tests.
  • Base reproduction or other evidence: executed. On the base revision the same file is not recognized as android-sparse-image and the boundary tests fail.
  • User-visible CLI/MCP output (executed, rea inspect-artifact system.img --detail summary --evidence_output system.evidence.json --json, excerpt of root_format_metadata):
{
  "kind": "android-sparse-image",
  "magic": "0xed26ff3a",
  "major_version": 1,
  "block_size": 4096,
  "total_blocks": 64,
  "total_chunks": 4,
  "expanded_size": 262144,
  "checksums_verified": false,
  "chunk_counts": { "raw": 1, "fill": 1, "dont_care": 1, "crc32": 1 },
  "covered_bytes": { "raw": 8192, "fill": 122880, "dont_care": 131072 },
  "fill_patterns": ["deadbeef"],
  "crc32_chunks": [{ "file_offset": 8260, "value": 305441741 }],
  "trailing_bytes": 0
}

with limitations including "DONT_CARE chunks were expanded as zeros; the original block contents are unknown." and "The stored image checksum and CRC32 chunk values were recorded and not verified."

  • Remaining proof gaps: tested against generated fixtures that follow the AOSP sparse layout, not a corpus of vendor factory images.

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.

Demo

Rendered walkthrough of the CLI inspect and extract output above (simulated terminal, values taken from a real run on the generated fixture).

demo

Validation performed

  • Maintainer verification: full-candidate independent P0–P2 review is clean at 081efbca733d831572a88562c83954fbb333dc0f.

  • Required CI passed at that same head, including the rerun of the two affected test shards after the unrelated browser-fixture connection failure.

  • Focused vitest over the sparse image domain, reader, reader boundary and format recognition tests: 62 passed

  • Sparse image CLI acceptance, sparse image MCP boundary, localToolContracts.test.ts, artifactReaderLimitsCli.test.ts, ArtifactOperationFailure.test.ts, ArtifactEmbeddedFormatProbes.test.ts: 53 passed, 1 skipped

  • npm run verify:test-discovery: all 3832 test and spec files discovered exactly once

  • npm run format:check: all matched files use the correct format

Compatibility, safety, and release

  • Breaking changes or migration steps: none. The new limit group is optional and defaults to the previous fixed ceiling.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable; offline parsing only, run on macOS.
  • Package or release metadata impact: new format value and one new optional limit group.
  • Security, privacy, process, or containment review: reads a local file and writes one expanded image only through the existing extraction path. Chunk count, expanded size and per-chunk sizes are bounded before allocation, and reads stay within one 64 KiB window plus one 64 KiB output buffer.

AI was used for assistance.

Author readiness

Human owner: @mvanhorn

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

@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

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

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-26T11:25:51.613073Z
We couldn’t complete this review. Comment @codex review to try again.
081efbc New commits
ℹ️ 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.

@greptile-apps

greptile-apps Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The reviewed update appears safe to merge; the previous finding is fixed and no new issues were found.RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[Medium impact] The reviewed update appears safe to merge; the previous finding is fixed and no new issues were found.

Summary

Adds offline Android sparse image inspection and expansion through the existing CLI and MCP artifact tools.

  • REA recognizes Android sparse images and shows their chunk layout.
  • Sparse partitions expand into one raw child for existing readers.
  • Callers can set a chunk-count cap for sparse images.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Sparse image] --> B[Recognize magic and version]
  B --> C[Read header and apply limits]
  C --> D[Parse chunk table]
  D --> E[Record inventory facts]
  D --> F[Stream expanded image.raw]
  F --> G[Hash and classify child]
Loading

Reviews (14) · Last reviewed commit: "fix(artifacts): keep the chunk_sz offset..." · Reviewed by Greptile

@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: 3f654d97b8

ℹ️ 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".

@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: 588178c1ff

ℹ️ 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".

A large RAW run was streamed through a nested readFileHandleChunks
Readable, which could prefetch a descriptor read while the outer
iterator was idle, so close or cancellation could retire the stream
with that read still running. Read the run directly in the expansion
iterator so every read is pending in the owner that cancellation waits
on, and add held-read close and cancellation regressions.
@morluto morluto added area: evidence Evidence, artifacts, and reconstruction enhancement New feature or request labels Nov 22, 2026
Resolve the split of artifactFormatMetadata into formatMetadata modules by
moving the Android sparse image schema into androidAndSystemMetadata, and
keep the member stream check local to the sparse reader now that the shared
helper is gone.
Release the held RAW read and join the retiring close or cancellation in
finally before restoring the read spy, so a failed assertion cannot leave
reader.close() waiting on a read nobody will finish. Use
awaitAcknowledgement for the held-read start barrier and drop the
per-test five-second timeouts in favor of the shared test deadlines.
@morluto

morluto commented Nov 24, 2026

Copy link
Copy Markdown
Owner

@mvanhorn thanks for the PR — there is 1 open review thread here:

Could you address or reply to this? Once it's resolved and CI is green we can take another look.
cc @gensokyo-dev @dandgabr

@mvanhorn

Copy link
Copy Markdown
Contributor Author

That finding is handled on the current head (59351d2): the outer async stream owns cancellation while backpressured, so close() and caller cancellation both retire an undrained expansion, with a regression in AndroidSparseImageArtifactReader.boundaries.test.ts for an unconsumed stream above the high-water mark. e762cf3 also keeps large RAW reads inside that same stream owner, which is why the thread now shows as outdated. Happy to adjust if you see a remaining gap.

Resolve the regenerated inspect_artifact advertised-schema summary.
Upstream main added the fixed-ceiling registry check. The sparse-image
reader projects the parser's own named ceiling, so register it as
forwarding like the boot-image reader.
@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.

@mvanhorn

Copy link
Copy Markdown
Contributor Author

Quick update since my last note: a0dcbcd registers the sparse-image reader's forwarded ceiling in scripts/verify/fixed-ceiling-registry.json, which the fixed-ceiling check added on upstream main needed, and d4688e6 merges current main. CI on d4688e6 is now green. The remaining open thread is the cancellation finding I answered above, so it should be ready for another look.

Port the sparse-image cancellable chunk stream onto the shared
OwnedAsyncArtifactStreams owner that replaced OwnedAsyncArtifactStream.
@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.

@mvanhorn

Copy link
Copy Markdown
Contributor Author

Typecheck, lint and the reader tests pass locally. npm ci passed. npm run typecheck passed. npm run lint passed. node scripts/run-vitest.mjs src/artifacts/AndroidSparseImageArtifactReader.test.ts src/artifacts/AndroidSparseImageArtifactReader.boundaries.test.ts src/artifacts/UnityFsArtifactReader.test.ts src/artifacts/UnityFsArtifactReader.boundaries.test.ts src/artifacts/WxapkgArtifactReader.test.ts src/artifacts/WxapkgArtifactReader.boundaries.test.ts src/artifacts/tar/TarArtifactReader.test.ts passed.

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

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

@mvanhorn

Copy link
Copy Markdown
Contributor Author

Pushed d9602ad to fix the red Test shard (11/12) run. 59aa02b switched the CLI acceptance test to expect code partial for the chunk budget refusal but missed the same assertion in tests/boundary/mcp/androidSparseImageMcp.test.ts, which still expected truncated. That one-line change is the whole commit. The MCP test and the four CLI acceptance tests pass locally. CI on d9602ad is still running.

Preserve upstream artifact admissions and Android sparse-image support.
Register sparse-image chunk recovery and regenerate the MCP schema snapshots.
@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.

@mvanhorn

Copy link
Copy Markdown
Contributor Author

98c9bbf brings the branch up to date with main as of the merge. On that head, npm run typecheck, npm run lint, npm run verify:advertised-schemas and node scripts/run-vitest.mjs src/artifacts/AndroidSparseImageArtifactReader.test.ts src/artifacts/AndroidSparseImageArtifactReader.boundaries.test.ts src/domain/firmware/androidSparseImage.test.ts src/domain/artifactFormatRecognition.test.ts pass locally. GitHub shows the PR as mergeable, and CI on 98c9bbf is still running.

@vincentkoc

Copy link
Copy Markdown
Collaborator

this overlaps #14395, but full image expansion is useful work beyond physical RAW-slice inspection. keeping it open while we consolidate the parser and separate inspection from the expansion budget; Author readiness is still needed.

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

@mvanhorn

Copy link
Copy Markdown
Contributor Author

Thanks @vincentkoc. The Author readiness boxes are ticked now. If it helps the consolidation with #14395, I can rebase the expansion half onto whichever parser you keep.

@vincentkoc
vincentkoc merged commit 192177f into morluto:main Nov 26, 2026
102 of 106 checks passed
@vincentkoc

Copy link
Copy Markdown
Collaborator

Landed after full review and green CI. Thanks for the format support and the cancellation fixes!

N0zoM1z0 added a commit that referenced this pull request Nov 28, 2026
…al callee (#9095)

* feat(apktool)!: budget decode_android_resources delivery

decode_android_resources returned the complete decode inline. Claude Code
saves an MCP result above about 25,000 tokens to a file, so on VLC 3.7.2
(180,996 bytes) a Claude Code agent limited to REA tools never saw the
strings: in two trials it failed every answer after 20 or more calls and
about 900,000 tokens. Even string_limit 1 returned 77 KB, because the
manifest text is always inline.

decode_android_resources now takes detail and joins the agent result
budget. Omitted, a decode that fits delivery.agent_result_budget_bytes is
inline and a larger one is retained behind its summary. With detail
summary, view returns one android-resources page in the same call, so the
German and Japanese values of one string take one call. The CLI uses the
shared Evidence delivery with --view.

On VLC with real Apktool 3.0.3 the default reply was 3,368 bytes, and the
two-locale strings page 2,695 bytes.

BREAKING CHANGE: a decode_android_resources call that omits detail on a
decode above the agent result budget now returns the retained summary.
Pass detail: "complete" (--detail complete) for the previous shape.

Co-Authored-By: gensokyo-dev <[email protected]>

* docs(apktool): describe decode delivery and resource views

Co-Authored-By: gensokyo-dev <[email protected]>

* feat(analysis-view): page retained Android reference traces

A retained trace_android_references result could only be read back
whole. It lists every using node, so on VLC's PlaybackService it was
76 KB of normalized result beside a 140 KB raw provider reply.

The android-references view pages one retained trace. Facet top-classes
lists distinct top classes with their package and using-node count,
sorted by name; facet references lists using nodes with their index and
only the selected fields. Both filter by exact kinds, packages (the top
class's name before its last dot) and top classes, and every page carries
the trace target, total and direct-invoke coverage.

The summary keeps the target, total and coverage, and counts using nodes
by kind, top class and package, with the 32 most referenced packages.

Co-Authored-By: gensokyo-dev <[email protected]>

* feat(android)!: budget trace_android_references delivery

trace_android_references returned every using node inline. On VLC's
org.videolan.vlc.PlaybackService the MCP result was 214,955 bytes, so
Claude Code saved it to a file a REA-only agent could not read, and
inspect_analysis_view did not support the operation. In two trials asking
which outer classes reference the class, Claude Code answered nothing
after 17 to 20 calls and about 870,000 tokens.

trace_android_references now takes detail and view and joins the agent
result budget. Omitted, a trace that fits delivery.agent_result_budget_bytes
is inline and a larger one is retained behind its summary. With detail
summary, view returns one android-references page in the same call. The
CLI uses the shared Evidence delivery with --view.

With real JADX on VLC the default reply was 5,987 bytes, and the
top-classes page of all 97 top classes 16,724 bytes. In two trials each,
Claude Code then answered correctly with 92,000 to 125,000 tokens, and
Codex with 208,000 to 217,000 tokens instead of 364,000 to 408,000.

BREAKING CHANGE: a trace_android_references call that omits detail on a
trace above the agent result budget now returns the retained summary.
Pass detail: "complete" (--detail complete) for the previous shape.

Co-Authored-By: gensokyo-dev <[email protected]>

* feat(android)!: count class members in summaries and page them

The inspect_android_class summary was the complete normalized class: on
VLC's org.videolan.vlc.PlaybackService, with 302 methods, it was 70,266
bytes, twice the agent result budget it was delivered for. Claude Code
saved it to a file, and REA-only agents read the class back through about
five evidence-json pages.

The class summary now carries the class name, engine, counts of methods,
constructors, overloaded method names, fields, encoded static values and
inner classes, the overloaded method names with their overload counts,
and the mapping's identity and record counts. The android-class view pages
methods (exact names, name prefixes, constructors), fields (exact names,
name prefixes, static values), inner classes and mapping symbols, and
inspect_android_class accepts it with detail summary in the same call.
Method summaries are unchanged and keep their own projector.

With real JADX on VLC the class summary was 4,601 bytes.

BREAKING CHANGE: the inspect_android_class summary, delivered for detail
summary or above the agent result budget, no longer lists methods, fields,
inner classes or mapping symbols. Page them with the android-class view,
or pass detail: "complete".

Co-Authored-By: gensokyo-dev <[email protected]>

* feat(android)!: count components in package summaries

The inspect_android_package summary kept every component declaration.
On VLC 3.7.2 its 60 components made the summary 62,118 bytes, above the
agent result budget it was delivered for, although the component-summary
and components facets already page and count them.

The summary's components now carry the component status, limitations and
counts by kind, exported declaration, exported default and declaration
coverage, computed by the same helper as the component-summary facet.
Component rows page through the components facet.

With real JADX on VLC the package summary was 6,280 bytes.

BREAKING CHANGE: the inspect_android_package summary no longer lists
component declarations. Page them with view {kind: "android", facet:
"components"}, or pass detail: "complete".

Co-Authored-By: gensokyo-dev <[email protected]>

* docs(android): describe budgeted delivery and the class and reference views

Co-Authored-By: gensokyo-dev <[email protected]>

* refactor(android): share boot image parser layout types (#14695)

* fix(artifacts): read the next tar header after header-only members (#14500)

* fix(artifacts): read the next tar header after header-only members

POSIX ustar stores no data blocks for symbolic links, devices,
directories and FIFOs, and a directory's size field may be nonzero by
design. The tar walk skipped the declared size after every header, so
such a header hid the members that followed. When the skipped span
landed on a later header, those members were missing while coverage
stayed complete. Otherwise the walk stopped as malformed.

The stored data length now comes from the header's type, through the
same directory rule that classifies members. Hard links keep their
declared size, because pax interchange archives may store a body.

Fixes #14497

* test(artifacts): cover pax and long-name sizes on header-only tar members

---------

Co-authored-by: Anurag Singh <[email protected]>

* test(fixtures): share literal-only LZ4 blocks across fixture builders (#14696)

* feat(artifacts): inventory and expand Android sparse images offline (#13244)

* feat(artifacts): inventory and expand Android sparse images offline

* chore(schemas): update artifact tool schema summaries for the sparse image limit

* fix(artifacts): retire undrained sparse image streams on cancellation

* fix(artifacts): keep large RAW reads in the sparse stream's owner

A large RAW run was streamed through a nested readFileHandleChunks
Readable, which could prefetch a descriptor read while the outer
iterator was idle, so close or cancellation could retire the stream
with that read still running. Read the run directly in the expansion
iterator so every read is pending in the owner that cancellation waits
on, and add held-read close and cancellation regressions.

* fix(firmware): drop unused ANDROID_SPARSE_MAGIC_BYTES export

* test(artifacts): release held sparse reads before restoring mocks

Release the held RAW read and join the retiring close or cancellation in
finally before restoring the read spy, so a failed assertion cannot leave
reader.close() waiting on a read nobody will finish. Use
awaitAcknowledgement for the held-read start barrier and drop the
per-test five-second timeouts in favor of the shared test deadlines.

* fix(lint): register sparse-image forwarded fixed ceiling

Upstream main added the fixed-ceiling registry check. The sparse-image
reader projects the parser's own named ceiling, so register it as
forwarding like the boot-image reader.

* Address review feedback

* test(android-sparse): expect partial code for chunk budget refusal

* test(android-sparse): expect partial code in MCP chunk budget refusal

* fix(artifacts): keep the chunk_sz offset when a RAW chunk outgrows its header

---------

Co-authored-by: Matt Van Horn <[email protected]>
Co-authored-by: Matt Van Horn <[email protected]>

* ci: resume hosted APT package downloads across bounded attempts

A slow archive connection can still be progressing when the single
download deadline expires, failing the Windows native controls lane
while MinGW archives were mid-transfer. Download within three bounded
attempts instead; APT keeps completed archives and resumes partial ones,
so a later attempt reconnects and continues. Installation still runs
only from the local cache after a successful download.

Co-Authored-By: gensokyo-dev <[email protected]>

* ci: retry transient failures of pinned release downloads

curl --retry covers only timeouts and a few HTTP statuses, so a
connection reset mid-transfer failed the Ghidra SDK acquisition outright.
Retry every transient error for the pinned downloads, as the web network
capture lane already does; each archive is still checked against its
pinned SHA-256 before use.

Co-Authored-By: gensokyo-dev <[email protected]>

* ci: fit the binary layout toolchain download into three attempts

Each hosted APT download attempt now has its own deadline, so the
900-second budget would let three attempts outlast the 25-minute job.
Give each attempt 360 seconds: a resumed second attempt still covers the
slowest observed cold download (657 seconds), and the test asserts that
three attempts leave the job five minutes to build and verify fixtures.

Co-Authored-By: gensokyo-dev <[email protected]>

* fix(setup): normalize win32 paths and trailing backslashes in fxLocation (#14725)

* test(cli): share command results across fresh and shared processes (#14718)

* refactor(parsers): share typed failure handling for Android and ISO images (#14719)

* test(filesystem): release the lease after simulated device changes (#14731)

* fix(tar): read pax values that hdrcharset=BINARY leaves as raw bytes (#14632)

* fix(tar): read pax values that hdrcharset=BINARY leaves as raw bytes

A pax extended header may declare hdrcharset=BINARY, and then its path,
linkpath, uname and gname values are raw bytes rather than UTF-8 (POSIX
pax, "hdrcharset"). Python tarfile and libarchive write exactly this for
a file name that is not UTF-8. parsePaxRecords refused every non-UTF-8
value, so the walk stopped as malformed at that header and no member
from it on was inventoried.

Under hdrcharset=BINARY those four values are now decoded as Latin-1,
with a limitation giving the raw bytes, as header names already are.
Any other non-UTF-8 value still stops the walk.

* fix(tar): charge hdrcharset=BINARY warnings to the metadata allowance

Each Latin-1 warning carries the raw value in hex, twice its size, and a
repeated global header appends a new one while a same-sized replacement
leaves the global map charge unchanged. Charge every warning to
artifact_limits.tar.metadata_bytes before building it.

* fix(tar): refund hdrcharset=BINARY warnings no member keeps

A local pax header's warnings were charged to
artifact_limits.tar.metadata_bytes but never refunded when they were
discarded: by the next local header that replaces them, or by an omitted
member or the archive root, which do not keep them. Repeated binary owner
names on omitted members could exhaust the allowance while the retained
data fit. Refund the charge whenever the warnings are dropped.

* fix(views): validate retained web source metadata against producer rules (#14729)

* fix(environment): release abort listeners when waits settle (#14730)

* refactor(javascript): share the artifact reconstruction cancellation check (#14732)

* fix(apple): preserve unknown CPU subtype in dylib selection (#14706)

* fix(apple): preserve unknown CPU subtype in dylib resolution

* chore: remove unused internal LZMA request type

* chore: mark partial module AST visitor switch explicitly

---------

Co-authored-by: ShuaixinHuang <[email protected]>

* fix(artifacts): keep boot image coverage unknown when layout bytes are not exposed (#14370)

* fix(artifacts): keep boot image coverage unknown when layout bytes are not exposed

Android boot and vendor_boot inventories reported complete coverage while
a limitation said declared layout bytes were not exposed as children: a
vendor_boot v4 section without table entries, table entries that cover
only part of the section, and bytes between the sequential layout and a
v1/v2 recovery_dtbo. The same section bytes already left coverage unknown
when the vendor table failed to parse.

The header and vendor table parsers now report unexposed bytes as typed
facts (unexposedLayoutBytes, unexposedSectionBytes) next to the existing
limitations, and the reader derives coverage from them instead of from
the parse-failure flags alone. The legacy tail's facts are named as the
parse fields they become and are spread into the parse result.

Fixes #14369

* docs(artifacts): separate boot image metadata ranges from children in the coverage rule

---------

Co-authored-by: Anurag Singh <[email protected]>

* fix(firmware): mark ESP flash coverage unknown when bootloader region is omitted (#14285)

When planEspFlashLayout locates a bootloader whose flash address is at or
after the selected partition table, it omits the bootloader region and
records a limitation. finishEspFlashLayout previously checked only
plan.input.bootloader === undefined, so a dump whose partitions covered
the rest of the image could still report coverage: "complete".

Check whether a bootloader region was actually placed in plan.regions
instead of re-deriving presence from plan.input.bootloader, matching
EspFlashImageArtifactReader. Update docs/esp-flash-image.md and add unit,
reader, and CLI regressions.

* fix(har): fall back to postData.params when postData.text is empty or unreadable (#14256)

* fix(native): resolve Objective-C protocol _classProperties via pointer fixups (#14283)

Resolve a protocol_t `_classProperties` slot through `resolvePointer`
instead of `read.pointer(...) !== 0n`, sharing the undecoded class-property
slot check in `AppleObjcProperties.ts` with `AppleObjcCategories.ts`.
A bound slot now counts as present and undecoded, and an unreadable or
unknown-fixup zero slot keeps the protocol record and coverage partial
rather than treating the list as absent.

* fix(verify): bound concurrent file reads in architecture and limit guards (#14720)

* fix(verify): bound concurrent file reads in architecture and limit guards

`scripts/verify/architecture-guards.mjs` reads every `.ts`, `.mts`, `.mjs`,
and `.py` file under `src/`, `tests/`, `scripts/`, and `bridge/` (8,203 files
on current `main`) via unbounded `Promise.all(paths.map(readFile))`. On
Windows, queuing all `open()` calls at once exceeds the UCRT 8,192 file
descriptor ceiling and deterministically fails `npm run verify:architecture-guards`,
`npm run check:fast`, and the pre-push hook with `EMFILE: too many open files`.

Add a zero-dependency JSDoc-typed `mapWithConcurrency` helper in
`scripts/verify/bounded-file-reads.mjs` (default cap 64, registered in
`tsconfig.scripts.json` so it runs before `npm ci`), apply it across all four
bulk `readFile` loops in `scripts/verify/architecture-guards.mjs` and the
sibling `src/` scan in `scripts/verify/rea-numeric-limits.mjs`, and add unit
coverage in `tests/evaluation/boundedFileReads.test.ts`.

* test(verify): copy bounded-file-reads helper in numericLimitGuardPermission fixture

`scripts/verify/rea-numeric-limits.mjs` now imports
`./bounded-file-reads.mjs`. Copy both scripts into the temporary checkout
in `tests/boundary/process/numericLimitGuardPermission.test.ts` so the
copied verifier starts cleanly on non-root Linux/macOS runs instead of
failing with `ERR_MODULE_NOT_FOUND`.

* fix(native): decode Objective-C categories that Swift lists in __objc_catlist2 (#14025)

* fix(native): decode Objective-C categories that Swift lists in __objc_catlist2

Swift lists categories on a class it reaches through a Swift class stub
in __objc_catlist2, and the Objective-C runtime loads that list like
__objc_catlist. inspect_native_dispatch_metadata read only __objc_catlist,
so these categories, their methods and protocols were missing while
objc_properties_categories coverage reported complete.

Read both lists. A stub's first word is a plain value from 1 to 15, as
the runtime's isStubClass checks, and it holds no class_t, so a category
whose class reference is a stub keeps a null class and coverage names
the reference instead of reading unrelated bytes as a class name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(native): version the dispatch reader profile for __objc_catlist2 categories

Reading __objc_catlist2 changes inspect_native_dispatch_metadata results,
but the reader still declared apple-metadata-reader-4, so a snapshot saved
before this change matched the current profile and replayed its empty,
complete category result. Declare reader version and revision 5 so those
snapshots are refused with a binding mismatch and the image is read again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

* test(artifacts): reuse temporary files in Android reader fixtures (#14750)

* fix(artifacts): explain ASAR PE signed-after-packing mismatches (#14702)

* fix(artifacts): explain ASAR PE signed-after-packing mismatches

When an unpacked PE companion fails ASAR integrity only because Authenticode
was applied after packing, record a verifiable signing_explanation on the
SHA-256 contradiction and error details instead of an opaque untrusted
mismatch. Bytes stay observed-untrusted; any other mutation remains an
unexplained contradiction.

Fixes #7212

* fix(artifacts): address signed-after-packing Greptile review

Catch ParseFailureError so unreadable PKCS#7 keeps the digest explanation,
share WIN_CERTIFICATE structural walks, index signer lookups, charge optional
reads to acquisition budgets with reported skips, preserve mismatch details
through cleanup failures, and inherit the shared MCP test deadline.

* fix(pe): walk WIN_CERTIFICATE entries lazily under max_entries

Convert the certificate-table walker into a generator so inspection stops at
the entry budget without materializing every range, and reconstruction can
validate structure with constant memory.

* fix(views): validate Android class rows against the selected facet (#14754)

* fix(android): allow filtering references by the unnamed package (#14752)

* fix(javascript): drop a stream acquisition whose options Node refuses (#9262)

* fix(javascript): drop a stream acquisition whose options Node refuses

`fs.createReadStream` and `fs.createWriteStream` are tracked as acquisitions with
`close`/`destroy` releases, so a wrongly retained one also invents a teardown. Node
validates five option members before it constructs the stream, and the filter
inspected none of them. Measured on Node 24.22.1, seven shapes were wrong:

| call | Node | before |
| --- | --- | --- |
| `createReadStream(p, {start:-1})` | throws | retained |
| `createReadStream(p, {end:-5})` | throws | retained |
| `createReadStream(p, {start:10, end:2})` | throws | retained |
| `createWriteStream(p, {start:-1})` | throws | retained |
| `createReadStream(p, {fd:-1})` | throws | retained |
| `createReadStream(p, {highWaterMark:-1})` | throws | retained |
| `createReadStream(p, {encoding:5})` | throws | retained |

Each member has its own check, so each is decided separately:

- `start` / `end` need a non-negative integer number. A string, `null`, boolean or
  BigInt throws `ERR_INVALID_ARG_TYPE`; `undefined` is absent and `-0` is zero.
- `fd` applies the same number rule but treats `null` as absent.
- `highWaterMark` throws `ERR_INVALID_ARG_VALUE` below zero or for a fraction, and
  treats `null` as absent.
- `encoding` is skipped by Node when falsy, so only a truthy literal is decided and a
  string must be one `Buffer` accepts.
- `start` above `end` throws, so the pair is read together.
- `createWriteStream` has no `end` member at all, so `{end:-1}` still creates a handle.
- `flags`, `mode` and `autoClose` are not validated eagerly and stay undecided.

A decided rejection is only trusted while the constructor it dispatches through is
still Node's own. `Object.prototype`, the stream prototypes, the fs stream
constructors and their shared `Stream` / `EventEmitter` ancestors are all consulted
through `prototypeMutationMayPrecede`, `builtinModuleSlotUnmodified`,
`builtinModuleSubtreeUnmodified` and `builtinSharedPrototypeUnmodified`, so a
replaced constructor or an intercepting prototype keeps the acquisition and reports
`resolution: "partial"` instead of inventing a rejection.

This is a port of the branch onto current `main`. `javascriptSemanticMemberMutations`
was restructured into an `executions` dispatch while the branch sat, so the net change
is applied to one base with the conflict blocks resolved:

- The `Object.defineProperty` analysis moved into `markBuiltinPropertyDefinition`,
  called from the `case "call"/"construction"` branch, and `markInvocation` takes an
  optional `definedTarget` so a discarded result is still stepped over.
- `requiredModuleChanged` keeps main's `allowCandidate` / `ignoreCandidateEffects` /
  `snapshotObjectRoot` parameters and appends `descendantsMatter` /
  `ignoreRootSlotWrite`; the three guards spell every argument because the position
  of `allowCandidate` differs from the branch's.
- A namespace reached through a candidate loader is still the original built-in
  receiver, so the guards pass that allowance and `markBuiltinPropertyDefinition`
  accepts the same single-candidate origin `semanticExpressionModuleOrigin` does.
- `semanticEffectTiming` reads became `prototypeMutationMayPrecede` and
  `ambientPathMayObserveAt`, which the architecture guard requires.
- `isUnmodifiedGlobalReference` imports from `javascriptSemanticGlobalReference.js`;
  both `AmbientWrites` modules lack it.

49 new cases in `javascriptSemanticAnalysis.open_flag_literal.test.ts`, 29 of which
fail on the base commit. With the guards' arguments in the branch's order the file is
10 failed / 298 passed and every failure is a case that must still refuse; now 308
passing. `src/domain/javascript` + `src/application/javascript` — 7 009 passing.
`architecture-guards` passed across 2 818 files. `tsc --noEmit` 0 errors.
`npm run lint` 0 errors.

* fix(javascript): refuse BigInt and import.meta stream option members

* fix(javascript): evaluate a unary BigInt chain before deciding stream truthiness

* fix(javascript): keep an fd supplied through import.meta undecided

* refactor(javascript): route the acquisition coverage through the accumulator

---------

Co-authored-by: 吴佳浩 <[email protected]>

* fix(sqlite): accept the documented sqlite_master spelling of the schema catalog (#10277)

* fix(sqlite): accept the documented sqlite_master spelling of the schema catalog

SQLite's schema-table documentation, "Alternative Names", recognizes four spellings and says
plainly that `sqlite_master` "works anywhere" while the two `sqlite_temp_*` forms only resolve for
the TEMP database. The inspector accepted exactly one of them.

`table: "sqlite_master"` was refused with "Selected ordinary table does not exist with that exact
name: sqlite_master", which is factually wrong for a name the engine resolves:

| same library, same connection | result |
| --- | --- |
| `SELECT count(*) FROM sqlite_master` | 1 |
| `SELECT count(*) FROM sqlite_schema` | 1 |
| `SELECT count(*) FROM pragma_table_list WHERE name = 'sqlite_master'` | **0** |
| `pragma_table_xinfo('sqlite_master', 'main')` | `type, name, tbl_name, rootpage, sql` |

The stored-catalog identity comes from `temp.pragma_table_list` with a `COLLATE BINARY` exact-name
match, and that inventory lists the catalog under its canonical spelling only, so the alias never
reached the row-source facts that already work. All three schema scopes threw.

Both spellings now yield the same rows and order, and the catalog still publishes no invented
declaration:

| spelling | before | after |
| --- | --- | --- |
| `sqlite_schema` | rows, `order: rowid` | unchanged |
| `sqlite_master` | THREW | rows, `order: rowid`, no self-declaration |
| `sqlite_temp_schema`, `sqlite_temp_master`, `SQLITE_MASTER` | THREW | still THREW |
| `absent` | THREW | still THREW |

Only the everywhere-alias is added. The TEMP-only spellings and a case variant stay refused,
because SQLite does not resolve them here either.

The guide now names both spellings instead of promising one exact name.

`tests/boundary/sqlite` and `src/application/sqlite` — 79 passing, 1 skipped, 6 new cases.
Reverting the normalization fails three of them.

* test(sqlite): cover the alias through the service boundary

A review finding on the previous commit: the shared predicate change also alters
`SqliteDatabaseService.matchesSelectedSchema`, which decides CLI and MCP result admission, and
nothing exercised the alias there.

The alias case now runs through the service twice — once against a report whose catalog carries no
self-declaration, which must be admitted, and once against a report that declares the table, which
must stay an output error. Dropping the alias from `sqliteSchemaHasObjectDeclaration` fails it.

* refactor(sqlite): derive the catalog declaration check from its spelling owner

---------

Co-authored-by: 吴佳浩 <[email protected]>
Co-authored-by: morluto <[email protected]>

* fix(adb): list a transport adb reports without a serial number (#10187)

* fix(adb): list a transport adb reports without a serial number

AOSP `transport.cpp append_transport()` substitutes the literal `(no serial number)` in the serial
column when the transport has none to report, which is reachable: `client/usb_linux.cpp` keeps an
empty serial for a device that cannot report one during early bringup (`http://b/20883914`) and
still registers the transport. The long listing pads that column with `%-22s` and the short one
separates it with a tab, so the placeholder carries spaces either way — and `DEVICE_LINE` required
a single `\S+` token.

The consequence was larger than one lost line. `AdbDeviceOperations` rejects any unparsed line
outright, so a single serial-less transport failed the whole `list_adb_devices` call:

| listing | before | after |
| --- | --- | --- |
| two placeholder transports | 0 devices, 2 unparsed | 2 devices, 0 unparsed |
| placeholder in the short form | 0 devices, 1 unparsed | 1 device, 0 unparsed |
| two healthy devices plus one placeholder | 2 devices **and 1 unparsed**, so the call fails and all three are lost | 3 devices, 0 unparsed |

The state, transport identity, USB metadata and inferred kind parse exactly as before; only the
serial column admits the placeholder. `src/adb` — 40 passing, 3 new cases; restoring `\S+` fails
all three.

* fix(adb): model the missing serial instead of the display placeholder

A review finding: the placeholder `(no serial number)` is formatter text, not an identity. Two
transports without a serial became indistinguishable once it was stored as one, and the text cannot
be passed to any device operation, because `deviceSerialSchema` rejects whitespace while the schema
describes the serial as "Device serial exactly as `adb devices` reports it".

The observation now carries `serial: null` with `serial_status: "not_reported"`, which is the shape
this module already uses for a transport ID it was not given (`transport_identity.status` and
`transport_id_status`). The reported value is unchanged for every transport that has a serial, and
`transport_id` still identifies a transport that has none.

Before this change the placeholder line was not parsed at all — `\S+` cannot match text containing
spaces — so it landed in `unparsedLines`, and `AdbDeviceOperations` refuses any unparsed line, which
removed every healthy device from the listing too:

| input | before | after |
| --- | --- | --- |
| placeholder line only | 0 devices, 1 unparsed | 1 device, `serial: null` |
| two placeholder transports | 0 devices | 2 devices, distinct `transport_id` |
| healthy + placeholder | 0 devices, 1 unparsed | 3 devices, one `serial: null` |

`src/adb` and `tests/boundary/cli/adbCli.test.ts` — 189 passing. `tests/boundary/providers/adb`
fails 4, all of which fail on `main` on this Windows host (where it fails 25). `tsc --noEmit`
0 errors, `npm run lint` 0 errors.

* test(adb): give the MCP fixture the serial status the parser reports

A review finding: `adbDeviceObservationSchema.serial_status` is now required, and the fixture in
`tests/boundary/mcp/adbMcp.test.ts` still omitted it, so `projectDeviceList` refused the listing
before the test's success assertion could run:

```
tests/boundary/mcp/adbMcp.test.ts:372
  expect(listed.isError).not.toBe(true);   → expected true not to be true
```

Both fixture devices report a serial, so both take `serial_status: "reported"`.

The reviewer also mentioned three full-object assertions in `AdbProvider.test.ts`; those do not
exist in the tree at this commit — `src/adb` runs 162 passing with the change, and
`git grep serial_status` finds no other fixture that carries a complete device object. I checked
rather than trusting the report.

* test(adb): give the provider device assertions the serial status

A review finding, and the reviewer was right about this file: I had reported it as not containing the
assertions, because `AdbProvider.test.ts:76` is `test.skipIf(process.platform === "win32")`, so all
117 of its tests are skipped on this Windows host and my local run reported 162 passing without ever
executing them. CI runs the adapters lane on Linux, where the three `toEqual` device objects compared
a 9-field observation against an 8-field one:

```
FAIL  src/adb/AdbProvider.test.ts > lists devices with inferred kinds and observed daemon startup
FAIL  src/adb/AdbProvider.test.ts > observes daemon startup when notices are printed to stderr
FAIL  src/adb/AdbProvider.test.ts > lists a USB device adb has no permission to open alongside online devices
  +     "serial_status": "reported",
```

Those are exactly the three, so `serial_status: "reported"` is added to each. Every device in this
file reports a serial, so the value is the same at all three sites.

Correcting my previous message on this PR: the file does carry them. The lesson is the same one that
has bitten this branch twice — `src/adb` passing locally is not evidence about a lane this host
skips.

`tsc --noEmit` 0 errors, `npm run lint` 0 errors.

* refactor(adb): let a null serial carry the not-reported fact

serial_status restated serial === null on every device row. Drop it and
document the null serial at the schema, where transport_identity still
tells two serial-less transports apart.

---------

Co-authored-by: morluto <[email protected]>

* fix(macho): document what a null build platform means (#14128)

* fix(macho): mark a conflicting build platform instead of reporting none

slice.platform is documented as null when no LC_BUILD_VERSION command was
observed, but the reader also writes null when several distinct platforms were
declared. trace_dylib_resolution therefore reported a binary that declares two
contradictory platforms as having no platform at all, which is the absent-versus
-unknown collapse AGENTS.md forbids.

Keep platform null for the conflict case and add platform_conflict so callers can
tell the two apart.

* fix(macho): describe build platform facts without a redundant conflict flag

The slice already records every platform declaration in platforms, so
platform_conflict duplicated that fact. It also labelled the zippered
macOS + macCatalyst pair, which dyld accepts, as a conflict. Drop the
flag, correct the platform and platforms contracts, and cover none,
single, repeated and zippered declarations through the reader.

---------

Co-authored-by: morluto <[email protected]>

* test(ci): require a positive binary-layout download deadline (#14755)

* fix(apple): observe keyed-archive dates when the offset table reaches the trailer (#7166)

* fix(apple): observe keyed-archive dates when the offset table reaches the trailer

inspect_keyed_archive preflights binary plists with decoder bounds, which
admit an offset table that ends anywhere before end of file, including
inside the 32-byte trailer. plist@5 reads such a table. Dates must still
end before the offset table, so the preflight records each reachable date.

The scalar scanner, however, required the table to end before the
trailer. For a table that runs into the trailer it abandoned the whole
file and collected no dates. The precision clamp in
decodeBinaryPlistScalars then saw no unrepresentable date, so a 0.1005 s
instant was reported as the exact timestamp 2001-01-01T00:00:00.100Z with
no unknown-date limitation.

Bound the scanner's offset-table reads by the end of the file, which is
the widest table any preflight admits. Strict preflight already rejects
tables past the trailer before scanning, so strict callers are unchanged.
Object and date bounds still end at the offset table.

* fix(apple): rebuild a complete trailer when cloning plist scalars

Review follow-up. With the scanner observing dates when the offset table
runs into the trailer, a sub-millisecond date that overlaps another object
now reaches cloneBinaryPlistObjects. That rewrite sized its output as
bytes.length plus the growth of a table assumed to end before the trailer.
When the old table overlaps the trailer, those bytes exist only once, so
the buffer came out short and the copied trailer was truncated. plist@5
then failed with "Unsupported int size: 0".

binaryPlistCloneGrowth now computes the bytes a clone rewrite adds,
subtracting only the old table bytes that precede the trailer. The
allocator and both preflight budget estimates use it, so admission and
allocation agree. For tables that end before the trailer the value is
unchanged.

* fix(apple): keep every source byte when cloning plist scalars

Review follow-up (Codex). Decoder bounds admit an offset table that runs
into the trailer and an object stored in the trailer's spare bytes after
it. With dates now observed for that layout, an overlapping
sub-millisecond date reaches cloneBinaryPlistObjects. Since #7820 the
rewrite appends clones and a fresh table, but only after the bytes before
the trailer, so it overwrote such an object and plist@5 failed with
"Unsupported int size: 256".

Copy the whole source buffer and append the clones, the new table and a
new trailer after it. The old table and trailer stay as inert bytes, so
every source offset still names its original record. The offset width and
both preflight estimates now account for the clones starting at the end
of the buffer and for the extra trailer.

* test(apple): match main's limitation assertions in keyed-archive date tests

* fix(apple): observe binary plist dates only when they end before the trailer

---------

Co-authored-by: morluto <[email protected]>

* fix(mcp): refuse stale sessions and serialize initialize handovers (#13195)

* fix(mcp): refuse a stale session id without arming a transport

A request that already carries mcp-session-id went through the slot's
current session even when that id was not live. Initialize skips the
SDK session check, so the stale id opened a transport. A presented id
now gets 404 unless it is the live session, and it never arms one.

* fix(mcp): serialize initialize session handovers

Two sessionless initialize requests could both close the same live
session and then handle on the one transport that replaced it. The
second request was rejected because that server was already initialized.
Each initialize now waits until the previous handover has answered, then
replaces that session with its own.

* fix(mcp): reject an unmatched session id before joining a drain

A presented id that is not the live session waited on transport close.
A drain timeout, or a shutdown that won that wait, answered 503.
Compare the id first and return 404 without joining the drain.
A matching id still waits, then checks that the same id is live.

* test(mcp): read raced initialize results and always release session gates

The replacement race now requires a complete initialize result from each reply.
The stale-session test releases its connect gate, joins the arming request, and closes the slot when an assertion fails.

---------

Co-authored-by: morluto <[email protected]>

* fix(browser): advertise the environment variable names a secret may not use (#10876)

* fix(browser): advertise the environment variable names a secret may not use

`browserScenarioSecretSchema` refuses a name containing `=` or NUL with a `.refine`, which
states the rule where a caller meets it only after sending a request. The published input
schema carried `minLength: 1` alone, so an MCP client validating against `tools/list` accepted
a name the server then refused:

| `environment_variable` | runtime | advertised (before) |
| --- | --- | --- |
| `A=B` | rejected | **accepted** |
| `=A` | rejected | **accepted** |
| `A=` | rejected | **accepted** |
| `A\0B` | rejected | **accepted** |
| `TOKEN`, `PATH` | accepted | accepted |

Both characters break the launched process's environment before any action runs, so the
refusal is one a caller needs before sending, not after. It is now stated as two `not`
patterns in the schema metadata:

```ts
.meta({ allOf: [{ not: { pattern: "=" } }, { not: { pattern: "\\x00" } }] })
```

An unanchored `pattern` under `not` reads as "contains none of", and `\x00` is the escape form
this repository's advertised patterns already use. `src/contracts/jsonSchemaKeywords.ts` lists
`not` and `allOf` among the visited schema positions, so
`tests/boundary/mcp/advertisedPatternsVMode.test.ts` compiles these patterns under the empty
flags, `u` and `v`. No look-around is used.

## Impact

Only discoverability changes: no name the server accepts becomes rejected, and no refused name
becomes accepted. The environment a scenario action runs in is unchanged.

## Evidence

- `src/domain/browserScenarioSecretName.test.ts` — new, one case. It builds a complete
  `capture_browser_scenario` request, asserts three ordinary names pass through both
  `contract.inputSchema.safeParse` and an AJV validate of the advertised document, and that
  `A=B`, `=A`, `A=` and `A\0B` fail through both.
- Reverting only the `.meta({ allOf: ... })` fails it with
  `AssertionError: "A=B": expected true to be false`.
- `browserScenario.test.ts`, `browserScenarioCapture.test.ts`, `browserScenarioMcp.test.ts`,
  `advertisedPatternsVMode.test.ts` and the new file — 27 passing.
- `npx tsc --noEmit -p .` — 0 errors. `npm run lint` — 0 errors.

## Author readiness

Human owner: @XiaoBinGan

- [x] 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.
- [x] I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
- [x] I declare this PR ready for initial maintainer review.

* fix(browser): state the secret name refusal as one anchored pattern

A review finding, and the recorded dialect baseline is the authority: `countAdvertisedDialectViolations`
records the constructs the presentation does not project away, and
`advertisedDialectBaseline.ts` states counts may only shrink. The previous commit wrote the refusal as
`not`/`allOf`/unanchored `pattern`, which raised `input keyword not` from 10 to 12 and `input keyword
allOf` by one, so `tests/boundary/mcp/advertisedDialect.test.ts` failed.

An anchored complement character class states the same refusal with one `pattern` keyword and no new
constructs:

```ts
.meta({ pattern: "^[^=\\x00]+$" })
```

Measured through `advertisedInputDialectViolations` on the same tool, the leaf now reports exactly the
violations it reported before this PR (`input keyword $schema`), where the `not`/`allOf` form reported
seven more.

The class is also what the compact profile keeps: a `not` whose child has no `type` is gateway
incompatible, so the compact presentation reduced the whole input to shallow property types and lost
the name pattern and UUID checks with it. A `pattern` at the leaf survives that reduction.

Equivalence checked exhaustively, not assumed: over 7 381 strings (every string of length 0..4 over
`a`, `=`, NUL, space, newline, `:`, `-`, `é`, `🎉`), `^[^=\x00]+$` and
`!(name.includes("=") || name.includes("\0"))` with `min(1)` agree on every one.

`browserScenarioSecretName.test.ts`, `browserScenario.test.ts`, `browserScenarioMcp.test.ts`,
`advertisedDialect.test.ts` and `advertisedPatternsVMode.test.ts` — pass. `tsc --noEmit` 0 errors,
`npm run lint` 0 errors.

* test(browser): load only the contract family under test

A review finding: the case imports `toolContract`, which pulls the complete catalog, to reach one
browser contract. `BROWSER_SCENARIO_TOOL_CONTRACTS` is the named family a focused test should read,
and selecting `capture_browser_scenario` from it loads nothing else.

`CONTRIBUTING.md` asks focused tests to import their named contract family, so this is the same
requirement the reviewer cited. Behaviour is unchanged: the same request is built, and the same
eight names are checked through both `contract.inputSchema.safeParse` and an AJV validate of the
advertised document.

`advertisedDialect.test.ts`, `advertisedPatternsVMode.test.ts`, `browserScenario.test.ts`,
`browserScenarioMcp.test.ts` and this case — 52 passing. `tsc --noEmit` 0 errors, `npm run lint`
0 errors.

* fix(browser): state the secret name refusal with the check itself

A review finding from the architecture guard: a raw JSON Schema keyword in `.meta()` is refused,
because a Zod `.meta()` carries presentation, not validation. `node scripts/verify/architecture-guards.mjs`
on the previous commit:

```
raw JSON Schema keyword or x-rea marker in Zod .meta() (use a typed annotation from
src/domain/schemaAnnotations, a Zod check, or a src/domain/schemaConstraints helper);
new copies are not allowed:
  src/domain/browserScenarioValues.ts: 1 (baseline 0)
```

The check was the one wrong thing, not the pattern. `environment_variable` is now a plain
`.regex(/^[^=\x00]+$/u, "Environment variable names cannot contain '=' or NUL")`, which

- is a Zod check, so the guard is satisfied and nothing new enters `.meta()`;
- advertises the identical leaf — `{"type":"string","minLength":1,"pattern":"^[^=\\x00]+$"}`,
  measured against the previous commit;
- keeps the compact presentation's leaf, where the earlier `not`/`allOf` form reduced the whole
  input to shallow property types.

Distinct from `declaredByPatterns` in `schemaConstraints.ts`: that helper declares a predicate the
schema cannot state, for predicates JSON Schema *can* express the regex is the check, and adding a
second declaration would be two sources of truth for one rule.

Red side: deleting the `.regex` fails the case with `AssertionError: "A=B": expected true to be false`.

`node scripts/verify/architecture-guards.mjs` — passed across 2 843 source files.
`src/domain/browserScenarioSecretName.test.ts` + `advertisedDialect.test.ts` — 42 passing.
`tsc --noEmit` 0 errors.

---------

Co-authored-by: 吴佳浩 <[email protected]>
Co-authored-by: morluto <[email protected]>

* fix(website): resolve tagged and latest release download links (#9238)

* fix(website): resolve tagged and latest release download links

* fix(website): reuse parsed release asset identity

---------

Co-authored-by: morluto <[email protected]>

* fix(javascript): preserve CommonJS exports through TypeScript wrappers (#4784)

* fix(javascript): preserve CommonJS exports through TypeScript wrappers

* fix(javascript): normalize wrapped CommonJS delete targets

---------

Co-authored-by: Kaoru0822 <[email protected]>

* fix(desktop): retain reader scratch files under its cleanup owner (#9775)

* fix(desktop): keep reader scratch files under the cleanup owner

* test(ci): align callee discovery and invalid model extent expectations

* test(ci): preserve CLI source closure and initialize alias fixture state

* fix(cli): retain capture caller paths in environment builds

* fix(desktop): keep owned reader paths short for Unix sockets

* revert(desktop): restore canonical main before replay for #9775

This reverts commit 10011501e5ef2545a73b05c0a90af3879935a9c9, reversing
changes made to e2585aa7ce31c37866ca46991ec656fdffaa3b90.

* fix(desktop): retain owned reader scratch on current main

* revert(desktop): restore canonical main before replay for #9775

This reverts commit 1e1f6b04f4ff37252a724d1754cf02326ec86065, reversing
changes made to 047d75a498f18a6608f35ee5e36cf1bf0f81ca97.

* fix(desktop): integrate upstream lifecycle CI corrections

* fix(desktop): run a local reader in its caller's folder to keep socket paths short

The runner nested a second realpath'd temporary folder inside the one its
caller already owns. On macOS the default TMPDIR then put a command's
Unix socket at 106+ bytes, past the 104-byte sun_path limit, so Python's
multiprocessing and other socket users could not bind under the private
TMPDIR. Work in the caller's folder directly, write the source under a
fixed name clear of the runner's own folders, and budget the regression
from the canonical root.

---------

Co-authored-by: hhang <[email protected]>
Co-authored-by: morluto <[email protected]>

* fix(call-path): bound inline shortest-path enumeration (#4984)

* fix(call-path): bound inline shortest-path enumeration

build_call_path could allocate every shortest path before response-budget enforcement. Count the exact total with a capped BigInt pass over the distance graph instead, and bound enumeration itself: max_paths (default 64) is a caller-selected count preference while a 2 MiB serialized paths-field budget is the resource bound, checked before each cited path is formed.

The representation accounting measures each string with the rules JSON.stringify applies instead of charging six bytes per code unit, so an ASCII address or Evidence id is no longer billed six times what it writes, and the paths-array brackets the per-path accounting excludes are reserved. A path that serializes to 469,497 bytes is no longer refused as over the budget.

Results report total_shortest_paths, total_shortest_paths_capped, paths_truncated and paths_limited_by_bytes so exact counts, representation limits and completeness stay distinguishable, and a found result whose single path cannot fit still reports the known path with byte-budget truncation.

* fix(call-path): always return the first shortest path and measure cited paths

The byte budget dropped a sole shortest path whose citations exceeded
2 MiB, although that path is linear in the supplied Evidence; only path
count grows exponentially, and max_paths bounds it. Always return the
first path and let the budget bound the paths after it.

Measure each cited path with JSON.stringify instead of a hand-written
estimator that duplicated citePath's shape and JSON escaping (it also
charged U+007F-U+009F as escaped). The found result again requires at
least one path.

* refactor(call-path): measure cited paths from cached parts before assembling

A candidate path was cited and serialized in full before the byte check,
so a rejected path still built its representation. Move citation into
CitedPathParts, which builds each node and edge record once per graph
position with its exact JSON size. Enumeration sums a candidate from
those parts and assembles only an accepted path, which shares the cached
records. The path skeleton is measured from the same record constructor,
so size and output cannot drift.

---------

Co-authored-by: morluto <[email protected]>

* fix(objdump): summarize command output by its size

Since the agent result budget, an over-budget inspect_with_objdump result
is replaced by its summary view, but that summary kept the complete
stdout and stderr. A whole-binary disassemble_all of a small C++ program
delivered 17.7 MB as its "summary", and over MCP exceeded the 10 MiB
stdio response limit, so the default call failed.

The summary now keeps every completion fact and reports available_counts
of stdout and stderr UTF-16 code units, as the GDB summary does for its
console streams; the retained parent keeps the complete output.

Co-Authored-By: gensokyo-dev <[email protected]>

* docs(objdump): describe the command summary output counts

Co-Authored-By: gensokyo-dev <[email protected]>

* refactor(gdb): name the MI stream record rule in the command observation owner

The GDB provider grouped console, target and log text by record prefix.
Name that rule beside the command result schema so the summary view can
select the same records without restating the prefixes.

Co-Authored-By: gensokyo-dev <[email protected]>

* fix(gdb): report console stream records by size in the command summary

The gdb_console summary dropped the console, target and log text but kept
every ordered record, and each stream record repeats that text. An
"info functions" summary of a small C++ program was 857 KB of console
records, so the over-budget delivery was as large as complete Evidence.

The summary now keeps result, asynchronous and unrecognized records in
order and counts the stream records it leaves in the retained parent.

Co-Authored-By: gensokyo-dev <[email protected]>

* fix(electron): trace IPC channels and bridge keys spelled as exact templates (#9538)

* fix(electron): trace IPC channels and bridge keys spelled as exact templates

Electron call-path tracing started only at calls whose first argument
was a quoted string literal, and its symbolic evaluator had no case for
template literals. A template without substitutions, such as
`app:template`, therefore stayed dynamic in the trace while the syntax
pass already reads it as a literal channel through
readExactJavaScriptLiteral. Wrapper registrations on such channels were
missing, direct handlers and contextBridge exposures keyed that way got
no call paths, and exact template switch cases lost their selection
condition.

The seed check, the evaluator and the switch-case label check now read
exact strings through readExactJavaScriptLiteral. Templates with
substitutions stay dynamic.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(electron): declare CommonJS in the exact-template CLI fixture

Since #9477, main counts an Electron finding as proven only in modules
declared CommonJS. The exact-template fixture used .js files without a
package.json, so after merging main the wrapper registrations stayed
unpaired (paired_renderer_transmissions 0) and the wrapper's own call
changed to inferred. The change under test still works: with .cjs files
the original expectations hold.

Name the fixture files .cjs, like the neighbouring fixtures in this file.

Validation: npx vitest run tests/boundary/cli/electronWrappedCallPaths.test.ts
- Tests 27 passed (27) on the built merged tree; npm run test:local on
electronWrappedCallPaths.test.ts and javascriptSymbolicBindings.test.ts -
Tests 326 passed (326).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* refactor(electron): read switch case literals through the exact-literal owner

* fix(electron): keep non-finite numeric switch cases as selection predicates

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: morluto <[email protected]>

* fix: name the violated rule in nested input refusals (#14766)

* fix(browser): name the rule when refusing a request header

A request step that set a browser-controlled header was refused with
"A page's fetch cannot set this header", which named neither the header
nor the rule. The advertised compact schema cannot carry this nested rule,
so the refusal is where an agent learns it. Name the header and say
whether it is browser-controlled or uses the reserved Proxy-/Sec- prefix.

* fix: name the violated rule in browser URL, CDP endpoint and Mach-O selection refusals

Invalid browser URL, Invalid CDP endpoint URL and Invalid Mach-O
container identity named no rule. The compact advertisement drops these
nested constraints, so the refusal is where an agent learns them. Name
the accepted form, without echoing values that may carry secrets, and
record the practice in the tool-design guide.

* chore(deps): update EVMole to 0.10.0 (#14765)

* fix(session): settle snapshot, shutdown, and cleanup-retry races (#14757)

* fix(session): settle snapshot, shutdown, and cleanup-retry races

- Invalidate the analysis snapshot only when an external mutation retires a
  bound engine. Without a target there is no analysis to retire, and the
  lingering flag made the next open discard a snapshot staged meanwhile.
- Let a deferred MCP server's close cancel in-flight runtime startup instead
  of waiting for it to finish before cleanup can run.
- Keep a concurrently confirmed command cleanup owner confirmed when a peer
  retry's stale stop reports it incomplete.
- Re-check provider registry closing after every wait so a selection is never
  admitted while a newer close is in progress.

* fix(session): stop cleanup owners registered while a retry is in flight

retryCleanup visits owners that appear during a stop await and returns
success only when none remain pending. An incomplete stop still cannot
replace an owner a concurrent retry has already confirmed.

* fix(mcp): keep a failed deferred startup failed when close aborts cleanup

The eager result classifies cancellation before its cleanup await. A close
that aborts during that await no longer treats a nonzero startup result as
a cancelled success.

---------

Co-authored-by: Cursor Agent <[email protected]>

* fix(domain): keep worker, SQLite, and sealing invariants owned (#14770)

* fix(domain): keep worker, SQLite, and sealing invariants owned

- Retain a late caller cancellation when SQLite keeps an unresolved worker
  owner instead of finalizing through runOwned.
- Key retained JavaScript static checkpoints by source identity so a
  discovered preload read with another package type releases its entry
  instead of leaking it across parked-worker reuse.
- Keep a parked JavaScript worker owned by its scope until its close
  succeeds.
- Borrow only sealed JSON members that sealing visited, and seal a shared
  subtree once instead of once per path.
- Refuse borrowed Evidence declarations whose resolution depends on the
  union branch their own frame parse selected.

* test(domain): bound shared JSON sealing inspections

A synchronous seal cannot be interrupted by the test timeout, so a lost
visited set would expand every shared path on the worker. Stop descriptor
reads after one per owned edge of this call and assert that count.

Co-authored-by: morluto <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: morluto <[email protected]>

* fix(website): honor validators and restore the implicit design system (#14768)

* fix(website): honor validators and restore the implicit design system

- Route every worker answer that skips Markdown negotiation through the HTML
  fallback, so validators and ranges removed for the probe still apply.
- Replace undefined classes with existing components and remove 27 CSS
  classes no page uses.
- Express article text color as a token so component colors win in both
  themes, and use logical properties for text-flow layout in RTL pages.
- Give an untranslated English fallback notice English direction.
- Start the page navigation closed without JavaScript, dismiss it with Escape
  or an outside click, and keep later copy clicks, failed key imports and
  first animation frames from corrupting demo state.
- Sync the theme bootstrap into the Notes fixture through a declared region.

* fix(website): skip Markdown negotiation for requests with a body

Markdown probing takes ownership of the caller request body. Methods other
than GET and HEAD have no Markdown representation, so they reach the asset
service once with the original body and validators.

Co-authored-by: morluto <[email protected]>

* fix(website): describe the homepage menu's closed start

The disclosure has no open attribute, so without JavaScript it starts
closed and the summary reveals the fragment links. The guide now matches
that, including overlay dismissal.

Co-authored-by: morluto <[email protected]>

* style(website): wrap the worker precondition assertion

oxfmt's 80-column width is what Static checks enforce. The If-Match
comparison in the non-retrieval test exceeded it.

Co-authored-by: morluto <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: morluto <[email protected]>

* fix(desktop): tear down build computers whose reader or run state is uncertain (#14778)

- Close the build computer when every retained reader is uncertain instead of
  returning before teardown, then resolve those readers after the verified
  teardown.
- Record an absent marker when run-cancel claims an unstarted job, so a
  retried cancel answers absent instead of waiting forever.
- Roll back a cancelled capture start without the already-aborted signal.
- Keep an established long-run failure primary over a cancellation that
  arrives during its cancel, as the documented lifecycle rule requires.
- Read the sandbox only after the helper handshake settles, keep a newer stop
  attempt when retrying, clear the report drain timer, and retry a failed
  controller script read.

* fix(cli): reject invalid inline values and honor requested output on terminals (#14763)

* fix(cli): reject invalid inline values and honor requested output on terminals

- Reject inline boolean and empty number values the schema cannot accept
  instead of coercing --skill=yes to false or --limit= to 0.
- Give captured mcp add output the terminal presentation of every other
  command through one shared result destination.
- Show the unapproved setup plan whose remediation asks a terminal reader to
  review it, and open the setup rail once when a scoped run starts at approval.
- Treat --full-output and --token-count as requesting the result document, so
  setup and argument errors no longer add terminal presentation beside it.
- Answer --schema for an unknown command in the selected format, and set the
  exit code instead of exiting so piped stdout drains.

* fix(cli): keep rejected boolean and number literals across repeated flags

Binding stored one scalar value, so a later valid flag replaced an earlier
literal before the schema could reject it. Boolean and number literals the
field rejects now stay bound, including decimal unions and count options,
while repeated valid flags still use the last value. --dry-run keeps its
own error.

* test(cli): assert the terminal full-output failure envelope

The terminal --full-output regression only checked that usage text was
absent. Decode the default document and the --json envelope and require
VALIDATION_ERROR with the skill field's invalid_type error.

* test(cli): accept a counted setup approval prompt

A scoped terminal plan names every eligible action, so a Linux host that
can install Hopper asks "Apply these N changes?" rather than the singular
question. The consent helper now answers either prompt, and the rail test
finds that question before checking the intro was rendered once.

---------

Co-authored-by: Cursor Agent <[email protected]>

* feat(providers): retain native selection provenance in Evidence (#9668)

* feat(providers): retain provider selection provenance with session evidence

The registry records how a deep provider became selected and why every other candidate was rejected, and binary_session exposes those facts for the active route. Evidence already carried provider identity, but nothing recorded which candidates the session evaluated, so a retained record could not explain why this engine produced the observation or what the alternatives were.

Attach provider_selection to Evidence admitted by the session: the selection source and, for each evaluated candidate, its identity and version, selection state, availability and target-support outcome, and the stable rejection codes. The field is optional and excluded from semantic identity, following caller_input_path, so each admitted record stays attributable to the exact provider instance without changing observation identity, evidence IDs or replay.

Copy only stable selection facts. Candidate diagnostics, remediation prose and target content stay in the session status projection instead of being repeated in every record.

* style(domain): reformat the provider-selection assertion

oxfmt --check rejected the three-line expect() call; the formatter's
single-line layout is the canonical one, so Static checks failed only
on formatting.

* fix(evidence): keep a rejected record inside the Result boundary

`recordEvidence` ran `withEvidenceProviderSelection` before handing the record
to the ledger. That helper parses to seal the rebound envelope, so a tampered or
otherwise invalid record threw a `ZodError` from the attribution step and never
reached `EvidenceLedger.record`, which is where the declared `Result` is
produced. `tests/boundary/mcp/processEvidenceIdentityMcp.test.ts:454` asserts
`session.recordEvidence(tampered).ok === false` and fails on the throw.

Authenticate the input first and return the ledger's own rejection for a value
it would refuse anyway; attribution then only ever sees a record its reader
accepts.

* fix(binary): attribute imported records to the recording session

Import replaces a same-ID record's presentation metadata, and
provider_selection is part of that metadata. When runDirectAnalysis imports
the provider's own bundle, the copy it rebuilds carries no selection, so the
import erased the attribution the session had stamped and the caller kept an
unattributed record instead. Attribute at both merge sites, where the session
already authenticates everything it admits.

A refreshed route after a failed switch can bind a different selection than
the one the earlier binding held, so re-derive it there as the initial open
does; spreading the previous binding kept the stale value.

* fix(binary): admit record input before sealing it for attribution

recordEvidence and the two bundle import paths seal Evidence through
withEvidenceProviderSelection before handing it to the ledger. A sealed
value skips the ledger's ordinary-JSON and heap-headroom admission, so a
session with no authentication allowance accepted a mutable record and a
large record was copied and traversed before the guard ran.

Hold the caller's own value to that admission first, then attribute. The
import paths also refuse with a Result instead of falling through to an
unattributed import when admission fails.

* fix(binary): re-attribute a sealed record without traversing it again

recordEvidence now admits the caller's value before attributing it, but a
record returned by evidenceForAnalysis has already been through that
admission and is sealed. Running the ordinary-JSON walk and the
heap-headroom check over it again repeats the work the ledger itself
skips for a sealed value.

Ask the ledger first: a value it holds is the admission it made, so the
check costs one lookup. Only a value the ledger has not seen pays for the
full walk.

* fix(providers): return the recorded Evidence after import

Import re-stamps session provenance onto the Evidence it records, but callers kept the pre-import copy, so retained selection attribution and cache metadata were dropped from what analysis reported. Read the recorded record back after a s…
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.

3 participants