Skip to content

feat(v8): inspect V8 code cache containers and retained byte patterns - #8993

Merged
morluto merged 18 commits into
morluto:mainfrom
XiaoBinGan:feat/v8-code-cache-inspector
Nov 9, 2026
Merged

morluto merged 18 commits into
morluto:mainfrom
XiaoBinGan:feat/v8-code-cache-inspector

Conversation

@XiaoBinGan

@XiaoBinGan XiaoBinGan commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Refs #8543. Adds offline V8 code-cache header/payload and bounded byte-pattern inspection through CLI/MCP, without execution or decompilation claims.

The shared artifact failure owner accepts an exact completed per-invocation snapshot, preserving digest/path/length through later interpretation failures and retaining exact cleanup leases. The sibling repair now covers Python, BEAM, Rust, Go and all ten identified native/firmware consumers: ELF notes, kernel modules, Apple IPS, PE load config/imports/certificates/resources, native exports, binary hardening and Devicetree. A failed retry cannot reuse a previous call's snapshot.

Validation on 29693d5: the expanded public CLI table passed all 14 format-refusal cases, plus 10 existing cleanup/cancellation-precedence cases. All ten added native assertions failed before repair. The earlier V8/parser/public suite passed 37 tests and separate cleanup/lease suites passed 26; these are separate runs, not a unique combined count. check:fast, docs:check, discovery and diff checks passed. Generated/malformed local fixtures establish the named boundaries; no real Electron/bytenode application or full repository gate was run.

Final capability review found no blocking implementation issue. Corrected the guide to keep unflagged producer identity unknown instead of inferring script. The admitted header profile follows the pinned Node/V8 serializer, not a universal V8 ABI. This follow-up passed 33 parser/provider/public CLI/stdio-MCP tests, check:fast and docs:check (9 README checks). No real Electron/bytenode target qualification was performed.

Author readiness

Human owner: @XiaoBinGan

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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-11-05T08:51:39.058399Z
We couldn’t complete this review. Comment @codex review to try again.
7b28683 PR opened
ℹ️ About Codex in GitHub

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

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

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@XiaoBinGan XiaoBinGan changed the title feat(v8):-inspect-V8-code-cache-containers-and-retained-byte-patterns feat(v8): inspect V8 code cache containers and retained byte patterns Nov 5, 2026
@greptile-apps

greptile-apps Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[High impact] No new blocking failure was established in the reviewed changes.

Summary

Adds offline V8 cache inspection through CLI and MCP. It reports header words, payload identity, and bounded printable byte patterns.

  • V8 code-cache files now show their header and printable payload patterns.
  • Artifact-reader refusals now keep the identity of the file they read.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  CLI[CLI command] --> Service[V8 cache service]
  MCP[MCP tool] --> Service
  Service --> Read[Stable regular-file read]
  Read --> Parse[Check header and scan payload]
  Parse -->|Success| Evidence[Create and retain Evidence]
  Parse -->|Failure| Facts[Retain completed file identity]
  Read -->|Cleanup fails| Owner[Keep exact cleanup owner for retry]
Loading

Reviews (15) · Last reviewed commit: "docs(v8): preserve unknown unflagged cac..." · Reviewed by Greptile

Comment thread src/domain/v8/v8CodeCache.ts Resolved
Comment thread src/v8/V8CodeCacheParser.ts Resolved
Comment thread docs/v8-code-cache.md Resolved
@XiaoBinGan
XiaoBinGan force-pushed the feat/v8-code-cache-inspector branch 2 times, most recently from 9e42e15 to dfe5a30 Compare November 5, 2026 09:31
Comment thread tests/acceptance/v8CodeCacheCli.test.ts Resolved
@XiaoBinGan

Copy link
Copy Markdown
Contributor Author

CI is red on this head, and the failure is not from this diff. Recording the evidence so the red state is not read as a defect in the V8 reader.

The only failing source test is:

src/domain/process/processCapture.comparison.test.ts > compares recoverable symlink bytes across old and current captures
ZodError: filesystem_checkpoints ... "top-level filesystem snapshots and effects must match the initial and final checkpoints"

Three independent checks place it outside this PR:

  1. It reproduces on unmodified upstream/main. A clean worktree at the base commit runs that file and fails the same single case — 1 failed, 24 passed — with no V8 files present at all.
  2. This diff does not touch that domain. git diff --name-only upstream/main HEAD -- src/domain/process/ is empty. The tool here reads a code cache container and produces no ProcessCapture.
  3. main's own CI fails on it. Run 42004017236 at c7fce6603 fails Source tests with exactly that test, and Test shard (7/8) additionally fails tests/boundary/cli/fridaCli.test.ts and tests/boundary/mcp/analysisViewMcp.test.ts. CI required then fails because a lane failed.

Portable tests and CI required are downstream of that same merge of the shard reports, not independent failures.

PR #8279 fix(process): stabilize capture comparisons is open against the same area and adds 256 lines to that very test file, so the fix is already in flight.

Everything this PR owns is green in the same run: Documentation, Static checks, Build package, Source tests up to the pre-existing case, all other test shards, and the workspace tests. Locally: tsc 0, vitest src/v8 src/contracts 245 passed, knip 0, lint 0 errors, docs:check 0, oxfmt --check 0.

I will rebase onto main once the processCapture fix lands.

@XiaoBinGan
XiaoBinGan force-pushed the feat/v8-code-cache-inspector branch from dfe5a30 to a5b9241 Compare November 5, 2026 16:15
Comment thread tests/acceptance/v8CodeCacheCli.test.ts Resolved
@XiaoBinGan
XiaoBinGan force-pushed the feat/v8-code-cache-inspector branch from a5b9241 to f054683 Compare November 5, 2026 16:53
@XiaoBinGan

Copy link
Copy Markdown
Contributor Author

Status on this head (f0546833f): all checks green, mergeable_state: clean, 5 of 5 review threads resolved.

Two corrections since the last review round, both from probing rather than reading:

  • path now uses absoluteLocalPathStringSchema, so a relative name is rejected at the schema boundary instead of being resolved against the server working directory.
  • The payload scan budget is 64 MiB with a 32 MiB default instead of a 512 MiB ceiling, because the scan is one synchronous pass; the documentation states the extraction step a cache embedded in a single-executable application needs.

The tests select the contract by name (toolContract("inspect_v8_code_cache")), which is what the repository's rea(no-positional-tool-contract) lint rule requires.

@XiaoBinGan
XiaoBinGan force-pushed the feat/v8-code-cache-inspector branch from f054683 to 7d0afa8 Compare November 7, 2026 08:49
@XiaoBinGan

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (562779bd7) and pushed 7d0afa86d.

One thing changed under this branch: main added
tests/boundary/mcp/absoluteLocalPathTools.test.ts, which enumerates every tool whose
tools/list schema must reject a relative path. inspect_v8_code_cache uses
absoluteLocalPathStringSchema, so leaving it out would leave one absolute-path tool
untested — it is now in that list, and the test passes.

Head state: all 5 review threads resolved, src/v8 + tests/boundary/mcp + contracts
256 passing, tsc 0, build 0, knip 0, docs:check 0, npm run lint 0 errors.

Comment thread src/v8/V8CodeCacheParser.ts Resolved
Comment thread src/v8/V8CodeCacheProvider.ts Resolved
@XiaoBinGan

Copy link
Copy Markdown
Contributor Author

The red CI on e7f87c4ac was this branch's own defect, not an environment problem. tests/boundary/cli/cliDecimalArguments.test.ts (added to main after this branch was opened) enumerates every numeric CLI option and requires 0x10 and 1e3 to be rejected, because plain Number coercion reads them as 16 and 1000. My three options forwarded the domain fields unchanged:

inspect-v8-code-cache options.maxFileBytes: Parser.parse accepts 1e3
inspect-v8-code-cache options.maxStrings: Parser.parse accepts 0x10
inspect-v8-code-cache options.maxStrings: Parser.parse accepts 1e3
inspect-v8-code-cache options.minStringBytes: Parser.parse accepts 0x10

Fixed in 84d148ca3 with cliDecimalField, the same wrapper the other numeric commands use. That test now passes locally, along with tsc, build, lint, knip and docs:check.

@XiaoBinGan

Copy link
Copy Markdown
Contributor Author

Both fixed in 9c8e8cb80, each measured on Node 24.22.1 before changing anything.

A module cache was reported as a script. vm.SourceTextModule.createCachedData() sets bit 30 of the source-length word, which the source-length mask 0x1fffffff leaves out, and the producer check only tested the function bit at bit 29:

producer source word
vm.Script 0x00000013 for a 19-unit source
vm.compileFunction 0x20000009 for a 9-unit source
vm.SourceTextModule 0x40000013 for a 19-unit source

So a real module cache was labelled script, and vm.Script rejects that container. The producer enum gains module and the module bit is tested first; the source length is unchanged because both flags sit outside the mask. docs/v8-code-cache.md now describes both bits.

The budget advice recommended a retry that could not work. Both limits have ceilings — max_strings at 65536 and min_string_bytes at 256 — so an admitted file with more than 65536 runs of 256 bytes reached the branch while every suggested retry was a rejected input. observationBudgetRemediation now reads the remaining headroom and only recommends a change that is still admissible, falling back to selecting a smaller artifact when neither can move. The parser message states the fact and leaves recovery to the provider, the only place that sees both budgets. MAX_INSPECT_V8_CODE_CACHE_MIN_STRING_BYTES names the ceiling the schema previously spelled inline, so advice and schema cannot drift.

7 new cases, all failing on the base commit: two for the producer bits (module alone, and function/module distinguished) and five for the remediation headroom including the both-at-ceiling case. src/v8 plus the CLI and MCP boundary files: 28 passing. tsc 0; build 0; npm run lint 0 errors; knip 0; docs:check 0.

Comment thread src/v8/V8CodeCacheProvider.test.ts Resolved
@XiaoBinGan

Copy link
Copy Markdown
Contributor Author

Right — those tests matched fragments of the advice sentence and banned old phrases, which docs/testing.md rules out. Fixed in 2aada02df by making the recovery a decision instead of a sentence.

observationBudgetRecovery now returns which retries remain within the schema's admitted range, plus whether a smaller artifact is the only option:

{ boundary, canRaiseMaxStrings, canRaiseMinStringBytes, canLowerMinStringBytes, requiresSmallerArtifact }

observationBudgetRemediation renders one sentence from that. The tests assert the decision — both headroom states, either ceiling alone, and the run-length floor — so the wording is free to change and an incorrect choice cannot pass.

It also caught a real bug in the previous shape: the min_string_bytes branch was taken to mean "lower it", but that branch is reachable with the value already at the schema minimum, where lowering is not a legal retry. That case is now requiresSmallerArtifact.

5 cases, all failing on the base commit. src/v8 plus the CLI and MCP boundary files: 28 passing. tsc 0; build 0; npm run lint 0 errors; knip 0; docs:check 0.

@XiaoBinGan

Copy link
Copy Markdown
Contributor Author

If the Test shard lane is red here, it is the inherited main failure in tests/boundary/mcp/ghidraEvidenceMcp.test.ts — the default health limitation wording changed in #9246 and that assertion was not updated. It reproduces on a clean upstream/main checkout. #9269 fixes it by comparing against ghidraHealthLimitations("fresh-import"); I am not duplicating the edit here so one PR owns it. All review threads on this PR are resolved.

@XiaoBinGan

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (72d5e72e6), 62 commits behind.

The red shards before this were inherited from main, which is red on CI required and Portable tests. After the rebase: tsc 0, build 0, format:check 0, lint 0 errors, knip 0, docs:check 0, and the V8 reader plus its CLI, MCP, absolute-path and decimal-argument boundary files are at 30 passing.

All review threads on this PR are resolved.

Comment thread docs/guides/javascript/v8-code-cache.md Resolved
@XiaoBinGan

Copy link
Copy Markdown
Contributor Author

Both gaps closed in 895b987ba.

The guide was at docs/v8-code-cache.md — outside the docs/guides/ tree every other guide uses — and neither index linked it. It now lives at docs/guides/javascript/v8-code-cache.md, is linked from docs/README.md and the VitePress sidebar, and the feature is recorded under docs/specs/v8-code-cache-inspection/ with spec.md, plan.md and tasks.md.

The spec keeps only premises that were measured on Node 24.22.1 — the three producer words (0x…|len for vm.Script, 0x20000000 for vm.compileFunction, 0x40000000 for vm.SourceTextModule) and the retained-string layout — rather than restating the implementation.

npm run docs:check 0; npm run format:check 0; tsc 0; build 0; lint 0 errors; knip 0. V8 reader, CLI and MCP files: 28 passing.

@XiaoBinGan

Copy link
Copy Markdown
Contributor Author

Both in 100ef0857.

Spec path. AGENTS.md:73 asks for docs/specs/<domain>/<feature-slug>/, so the three records moved to docs/specs/v8/code-cache-inspection/.

Verification claims. You were right on both counts, and I closed the second gap rather than only rewording it:

  • Only vm.Script and vm.compileFunction are real producers in that suite — the module case sets the measured bit on a vm.Script cache. The spec now says so instead of claiming a real vm.SourceTextModule cache.
  • observationBudgetRemediation had no test at all, only observationBudgetRecovery. It now has four cases holding the sentence to the struct it renders from: it must not advise a knob the struct closed, and must mention a smaller artifact exactly when the struct requires one. Verified by making the sentence advise max_strings after its ceiling was reached — the test fails. Wording stays free; wrong advice does not.

npm run docs:check 0; npm run format:check 0; tsc 0; build 0; lint 0 errors; knip 0. V8 reader, CLI, MCP, absolute-path and decimal-argument files: 34 passing.

@XiaoBinGan
XiaoBinGan force-pushed the feat/v8-code-cache-inspector branch from 100ef08 to 46ee799 Compare November 9, 2026 01:50
@CassieFox23

Copy link
Copy Markdown
Contributor

TL;DR: I ran the 5 test files this PR changes on three Node versions. On Node 22.23.4, 1 of 33 tests fails; the other two versions pass all 33. The CI workflow on 46ee799 ended as completed/failure.

Check (head 46ee799) Node 22.23.4 Node 24.22.1 Node 26.12.1
Test files fail: 1 failed, 4 passed (5) pass: 5 passed (5) pass: 5 passed (5)
Tests fail: 1 failed, 32 passed (33) pass: 33 passed (33) pass: 33 passed (33)

The failing test on Node 22.23.4 is separates the compileFunction producer bit from the source length. It lives in src/v8/V8CodeCacheParser.test.ts. The first error line says expected script to be compile_function. I did not look into why.

CI on 46ee799 (read live with gh):

  • Workflow runs: CI is completed/failure and CodeQL production is completed/skipped.
  • Workflow runs: PR readiness and PR title are completed/success.
  • 4 check runs failed: CI required, Portable tests, recorded_crash / real-recorded-crash (ubuntu:24.04), and Test shard (4/8).
  • 5 check runs were cancelled: Test shard (3/8), Test shard (5/8), Test shard (6/8), Test shard (7/8) and Test shard (8/8).
  • 22 check runs succeeded, including Source tests, Test shard (1/8) and Test shard (2/8). 16 were skipped.
  • The PR is mergeable true, state blocked, not a draft. The head is 0 commits behind main c78c8ae.

I read the failed log of CI run 42547646089 with gh run view --log-failed. It says the lanes test, test-shard and recorded_crash did not pass. One test failed in both mcp-boundary and mcp-boundary built. It is preserves the source when an inline result with unknown retention exceeds delivery, in tests/boundary/mcp/sourcePublicationComposed.test.ts. The error is an AssertionError on a resource_constraint object. That file is not one of the 5 test files this PR changes. I did not run it myself.

Not run

  • A script that prints header word 2 (hex) for a vm.SourceTextModule cache and for a vm.Script cache. The vm.Script source would declare a variable s holding the characters é, € and 😀. The script would then run the parser on a 10-byte file.
  • A real cache of a few hundred KB run through V8CodeCacheParser.ts with the default max_strings of 4096.
Test setup
  • Box: Fedora 44 VM (4 vCPUs, 8 GB) on my Nobara 44 PC, Linux 7.2.11
  • Node: 22.23.4, 24.22.1, 26.12.1
  • Head / base: 46ee799 / c78c8ae (merge base with main)
  • Install: npm ci --offline and npm run test:prepare on Node 24.22.1
Commands
npm ci --offline
npm run test:prepare
xvfb-run -a npm run test:focused -- src/v8/V8CodeCacheParser.test.ts src/v8/V8CodeCacheProvider.test.ts tests/acceptance/v8CodeCacheCli.test.ts tests/boundary/mcp/absoluteLocalPathTools.test.ts tests/boundary/mcp/v8CodeCacheMcp.test.ts

🤖 Written and tested with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊

@XiaoBinGan

Copy link
Copy Markdown
Contributor Author

The Node 22.23.4 failure was the fixture, not the parser, and it is fixed in 69aedae60.

vm.compileFunction("return 7;", [], {produceCachedData: true}).cachedData carries 0x20000009 in the source-length word on Node 24.22.1 — bit 29 set — while Node 22.23.4 does not set that bit for the same call. Whether a given V8 build marks the word is a build detail, so asserting one build's spelling made the check version-dependent rather than about the parser.

The case now reads the word the runtime produced and asserts the parser maps it correctly, and keeps the part that must hold on every build: the source length is the low bits, so it equals both word & 0x1fffffff and the source's length. The flag meanings stay pinned by the synthetic withHeaderWord cases, which depend on no build at all. Reverting the parser's compile_function arm still fails this case and keeps the function and module flags distinct.

On the two probes you listed as not run — both are worth having, and I will run them:

  • The header word for a vm.SourceTextModule cache, which is the one producer I have never generated for real. You are right that the module case in this suite sets the bit on a vm.Script cache instead. That is deliberate and recorded in the spec's verification section as covering the bit's meaning, not a real module cache — but generating one would be better evidence, and I will check whether vm.SourceTextModule is reachable without --experimental-vm-modules.
  • A few-hundred-KB real cache through the parser at the default max_strings of 4096.

The sourcePublicationComposed failure you saw in CI is main red, not this PR: #9562, bisected to 52fe342c7 (#9492). #9565 raises the delivery budget so the preserved partial Evidence fits again.

Thank you for running three Node versions on this — the 22.23.4 case is exactly the kind of thing a single-version check misses.

Comment thread src/v8/V8CodeCacheParser.ts Resolved
…tterns

Bytenode-compiled `.jsc` files — the V8 code cache container that `vm.Script`,
`vm.compileFunction` and bytenode 2.x write, and that Node single-executable applications
and Electron apps ship — had no format-native reader. `inspect_binary_layout` shows the
surrounding ELF/PE and `inspect_artifact` inventories the file, but neither decodes the V8
structures, so an agent could not tell which V8 line produced the file, could not learn the
container is metadata rather than source, and had nothing to point at a version-pinned
decompiler. Issue morluto#8543.

`inspect_v8_code_cache` joins the format-native family with `inspect_python_pyc`,
`inspect_erlang_beam` and `inspect_kernel_module`: one explicit local file, bounded parsing,
no execution, no installation, no child process.

**The container is version-dependent, so the reader reports roles with confidence instead
of assuming an ABI.** All eight header words are reported with byte offset, observed value,
the role this reader believes the word has, and whether that role is `confirmed`,
`inferred`, or `unconfirmed`. Only three facts gate admission: the header size this reader
pins, the V8 code cache magic high half `0xc0de` (the low half is
`ExternalReferenceTable::kSize` and varies per build, so it is a build fingerprint rather
than a constant), and a declared payload length that reaches exactly the end of the file.

I derived the field semantics from the producer rather than assuming them, and two findings
changed the design:

- **The word V8 calls the source hash holds the source length on the measured producers.**
  A 54-code-unit source stored `54`, and sources with the same code-unit length but
  different content stored the same value, including a source whose UTF-8 length was 154.
  The reader reports it as `source_length` and the docs say that this name is what the
  measurement supports, not a claim about what another build stores there.
- **`vm.compileFunction` sets a high bit in that word.** The reader masks it out and reports
  the producer family as `script` or `compile_function`, so the source length stays correct
  for both producers.

Embedded strings are reported as **byte-pattern observations with absolute byte ranges**,
labelled as such in the field name and in the limitations. A reported sequence is not proof
V8 retained it as a string, and a missing literal is not proof it is absent.

**Fail-closed boundaries, all covered by tests:** an unknown magic is a typed
`unsupported_target` failure because the file is not a V8 code cache; a short header or a
payload-length disagreement is a typed `invalid_request` failure. Neither yields a partial
parse and neither records Evidence.

Non-goals are explicit in the tool description and the docs: the payload is serialized V8
heap data, not source; recovering logic needs a version-pinned View8-style decompiler that
this tool neither provides nor depends on.

Fixtures are generated from the running V8 instead of committing a version-pinned binary, so
the tests exercise the real producer and stay valid across Node upgrades.

- Semantic owner and earliest changed stage: format-native V8 code cache container decoding.
- CLI and MCP/tool-catalog contract: one new `artifact-provider` tool and one new
  `inspect-v8-code-cache` CLI command, registered in `TOOL_CONTRACTS`, the `artifact`
  language family, `TOOL_EFFECTS`, the capability declarations and services, and the
  capability inventory. `docs:check` passes, so the generated catalog agrees.
- Provider, bridge, target-format, or platform compatibility: no provider runs and no
  external tool is required, so the tool is available on every supported Node host.
- Evidence, artifact, provenance, or reconstruction contract: complete Evidence with the
  payload byte range as its location; no artifact format, reader, or reconstruction change.
- Generated metadata, package, or installation impact: catalog and document facts
  regenerated by the existing checks; no new dependency.

Expected effects:

- [x] Target content is returned as bounded structured facts.

- `src/v8/V8CodeCacheParser.test.ts` (13 cases): real-producer header facts, per-field role
  and confidence, source length for both producers, an observation's absolute offset
  verified against the file bytes, the limitation text, foreign magic, payload-length
  mismatch, short header, missing payload bytes, a different build constant still admitted,
  and the observation budget.
- `tests/boundary/mcp/v8CodeCacheMcp.test.ts` (4 cases): advertisement and annotations,
  header facts over MCP, relative-path rejection, unsupported magic, malformed container.
- `tests/acceptance/v8CodeCacheCli.test.ts` (4 cases): the public CLI, relative-path
  resolution, byte-range observations, and the typed failure.

- `npx vitest run src/contracts src/v8 src/application/v8CodeCache src/domain/v8` — 242 passed
- `npx vitest run tests/boundary/mcp/v8CodeCacheMcp.test.ts tests/acceptance/v8CodeCacheCli.test.ts tests/boundary/filesystem/productCatalog.test.ts tests/acceptance/tools/localToolContracts.test.ts` — 20 passed, 4 skipped
- `npx tsc --noEmit -p .` — exit 0
- `npm run build` — exit 0
- `npm run lint` — 0 errors
- `npm run knip` — exit 0
- `npm run docs:check` — exit 0
- `npx oxfmt --check src tests docs` — exit 0

Gap: the header table is measured on node v24.22.1 / V8 13.6.233.17-node.58 only. No other
V8 build is available here, so a different build's field order is untested; that is exactly
why only three facts gate admission and the remaining roles carry a confidence level rather
than being asserted.

Additive. No existing tool, schema, or behaviour changes. The reader never executes the
selected file, never launches a process, and never accesses the network; its audited effects
are `mutatesSession: true` only, matching the other static format readers.

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.

- [x] This PR addresses a concrete problem or an agreed enhancement.
- [x] Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
- [x] The PR has one focused outcome and the title follows `type(scope): outcome`.
- [x] Related issue: morluto#8543.
- [x] Tests cover changed observable behavior and meaningful failure paths.
- [x] Owning docs, contracts, and generated metadata are updated where needed.
- [x] I checked the final diff for secrets, unrelated cleanup, and unsupported claims.
Review feedback from @greptile-apps on four points.

**Bound the synchronous payload scan.** The scan is one synchronous pass over the
payload, so the 512 MiB ceiling allowed a single request to hold the process for
several seconds. The ceiling is now 64 MiB, matching the pinned CPython pyc reader,
and the default is 32 MiB. The scan stays synchronous, like the BEAM and ELF note
readers in this family, but the budget that bounds it is no longer large enough to
matter. The new `max_file_bytes` ceiling and default are documented.

**Use the absolute-path schema.** `path` now uses `absoluteLocalPathStringSchema`
instead of `localPathStringSchema`, matching `inspect_erlang_beam`. A relative name
previously passed validation and was resolved against the server's working
directory, so `module.jsc` could select a different file than the caller meant. The
rejection is now at the schema boundary.

**State the extraction step.** The handoff in `docs/v8-code-cache.md` now says a
cache embedded in a single-executable application or an Electron app must be
extracted first, because this reader requires the magic at byte zero and returns
`unsupported_target` for the surrounding ELF/PE executable.

**Load only the owning contract group in tests.** Both tests now import
`V8_CODE_CACHE_TOOL_CONTRACTS` directly instead of resolving the tool through the
full catalog, so a focused test no longer constructs every other tool's schema.

21 cases pass across the parser, MCP boundary and CLI acceptance files; `tsc` 0;
`build` 0; `knip` 0; `docs:check` 0; `oxfmt --check` 0.
Reverts the catalog-position selection I added for a review suggestion. This
repository has a lint rule (`rea(no-positional-tool-contract)`) that forbids
selecting a tool contract by catalog order, and `toolContract("inspect_v8_code_cache")`
is how every neighbouring focused test selects one. The positional form I tried
introduced two lint errors, so the named form stays.

The review concern was that resolving through the full catalog constructs every
other tool's schema. That cost is real but it is the repository's chosen trade:
catalog ordering must never select an operation or schema, and `toolContract` is
the named accessor that enforces it.
Main added `tests/boundary/mcp/absoluteLocalPathTools.test.ts` after this branch
was opened. It enumerates every tool whose MCP `tools/list` schema must reject a
relative path, and `inspect_v8_code_cache` uses `absoluteLocalPathStringSchema`,
so the tool belongs in that list. Adding it keeps the enumerated field set complete
instead of leaving one absolute-path tool untested.

`tests/boundary/mcp` + v8 + contracts: 256 passing. `tsc` 0; `build` 0; `knip` 0;
`docs:check` 0; `npm run lint` 0 errors.
`for (const [index, byte] of payload.entries())` allocates a two-element array for
every byte of the cache payload. On a 1 MiB payload that allocation dominated the
scan.

Measured with a real cache built from this parser, alternated so the two forms run
against the same input:

| payload | entries() | indexed reads |
| --- | --- | --- |
| 1 MiB | 15.5ms | 4.4ms |

That is 3.49x on the scan, and the gap widens on smaller payloads where the
allocation cost is a larger share (7.3x at 64 KiB in a synthetic run of the same
shape). The scan is the whole cost of `inspect_v8_code_cache` once the file is read,
so this is the tool's own hot loop.

Output is unchanged: the parser returns one retained string for the 64 KiB fixture,
and `src/v8` plus the CLI and MCP boundary files stay at 21 passing. `tsc` 0;
`build` 0; `npm run lint` 0 errors.
Main added `tests/boundary/cli/cliDecimalArguments.test.ts` after this branch was
opened. It enumerates every numeric CLI option and requires `0x10` and `1e3` to be
rejected, because plain `Number` coercion would read them as 16 and 1000. This
command's three options forwarded the domain fields unchanged, so the test failed on
them:

    inspect-v8-code-cache options.maxFileBytes: Parser.parse accepts 1e3
    inspect-v8-code-cache options.maxStrings: Parser.parse accepts 0x10
    inspect-v8-code-cache options.maxStrings: Parser.parse accepts 1e3
    inspect-v8-code-cache options.minStringBytes: Parser.parse accepts 0x10

`cliDecimalField` publishes the input view that parses the decimal token first and
then lets the domain field own bounds, defaults and help, which is what the other
numeric commands use.

`tests/boundary/cli/cliDecimalArguments.test.ts` now passes. `tsc` 0; `build` 0;
`npm run lint` 0 errors; `knip` 0; `docs:check` 0.
Two review findings, each measured on Node 24.22.1 before changing anything.

**A module cache was reported as a script.** `vm.SourceTextModule.createCachedData()`
sets bit 30 of the source-length word, which the source-length mask `0x1fffffff` leaves
out, and the producer check only tested the function bit at bit 29:

| producer | source word |
| --- | --- |
| `vm.Script` | `0x00000013` for a 19-unit source |
| `vm.compileFunction` | `0x20000009` for a 9-unit source |
| `vm.SourceTextModule` | `0x40000013` for a 19-unit source |

So a real module cache was labelled `script`, and `vm.Script` rejects that container. The
producer enum gains `module` and the module bit is tested first; the source length is
unchanged because both flags sit outside the mask.

**The budget advice recommended a retry that could not work.** Both limits have
ceilings — `max_strings` at 65536 and `min_string_bytes` at 256 — so an admitted file
with more than 65536 runs of 256 bytes reached the branch while every suggested retry
was a rejected input. `observationBudgetRemediation` now reads the remaining headroom
and only recommends a change that is still admissible, falling back to selecting a
smaller artifact when neither can move. The parser message states the fact and leaves
recovery to the provider, which is the only place that can see both budgets.

`MAX_INSPECT_V8_CODE_CACHE_MIN_STRING_BYTES` names the `min_string_bytes` ceiling that
the schema previously spelled inline, so the advice and the schema cannot drift.

`docs/v8-code-cache.md` describes both flag bits. `src/v8` plus the CLI and MCP boundary
files: 28 passing; 7 new cases fail on the base commit. `tsc` 0; `build` 0;
`npm run lint` 0 errors; `knip` 0; `docs:check` 0.
The remediation tests matched fragments of the advice sentence and banned old phrases.
`docs/testing.md` asks for error codes, recorded limits and recovery behaviour instead of
frozen prose, so a harmless reword could fail those tests while wrong advice passed them.

`observationBudgetRecovery` now returns the decision — which retries remain within the
schema's admitted range, and whether a smaller artifact is the only option — and
`observationBudgetRemediation` renders one sentence from it. The tests assert the
decision, so the wording is free to change and an incorrect choice cannot pass.

This also fixes a bug in the previous shape: it took the `min_string_bytes` branch to mean
"lower it", but that branch is reachable with the value already at the schema minimum,
where lowering is not a legal retry. The decision now carries `canLowerMinStringBytes`
and a `requiresSmallerArtifact` flag for that case.

5 cases, all failing on the base commit, covering both headroom states, either ceiling
alone, and the run-length floor. `src/v8` plus the CLI and MCP boundary files: 28
passing. `tsc` 0; `build` 0; `npm run lint` 0 errors; `knip` 0; `docs:check` 0.
The only failing job on this branch was `javascript_recovery / real-javascript-recovery`,
which failed on `curl: (22) The requested URL returned error: 504` while downloading
`wakaru-linux-x64.tar.gz`. The release is reachable again (HTTP 200), so this empty
commit re-triggers the lane.
The guide sat at `docs/v8-code-cache.md`, outside the `docs/guides/` tree every other
guide uses, and neither index linked it, so it could not be reached from
`docs/README.md` or the VitePress sidebar.

Moved to `docs/guides/javascript/`, linked from both indexes, and recorded the feature
under `docs/specs/v8-code-cache-inspection/` with `spec.md`, `plan.md` and `tasks.md`.
The spec keeps only the premises that were measured on Node 24.22.1 — the three producer
words and the retained-string layout — rather than restating the implementation.

`npm run docs:check` 0; `npm run format:check` 0; `tsc` 0; `build` 0; `lint` 0 errors;
`knip` 0. V8 reader, CLI and MCP files: 28 passing.
…s struct

Two review findings.

**The records were at `docs/specs/v8-code-cache-inspection/`.** `AGENTS.md:73` asks for
`docs/specs/<domain>/<feature-slug>/`, so they move to
`docs/specs/v8/code-cache-inspection/`.

**The verification section claimed more than the tests do.** It said the producer cases
were built from real `vm.Script`, `vm.compileFunction` and `vm.SourceTextModule` output,
and that the budget advice was compared with its owning formatter. In fact only
`vm.Script` and `vm.compileFunction` are real producers — the module case sets the
measured bit on a `vm.Script` cache — and only `observationBudgetRecovery` was asserted.

Corrected the claim, and closed the second gap rather than only describing it:
`observationBudgetRemediation` now has four cases holding the sentence to the struct it
renders from. The sentence must not advise a knob the struct closed, and must mention a
smaller artifact exactly when the struct requires one. Verified by making the sentence
advise `max_strings` after the ceiling was reached — the test fails. Wording stays free;
wrong advice does not.

`npm run docs:check` 0; `npm run format:check` 0; `tsc` 0; `build` 0; `lint` 0 errors;
`knip` 0. V8 reader, CLI, MCP, absolute-path and decimal-argument files: 34 passing.
The rebase onto `main` conflicted in `tests/boundary/mcp/absoluteLocalPathTools.test.ts`:
`main` gained `inspect_api_contract`, `inspect_devicetree`, `inspect_playwright_trace` and
`inspect_python_pyc` in both the contract list and the path-field map while this branch
added `inspect_v8_code_cache`. Both sides are additive, so both are kept.

Without the resolution the branch carried conflict markers, which made `mergeable_state`
`dirty` and every check on it meaningless. Re-verified after the rebase: `tsc` 0, `build` 0,
`format:check` 0, `lint` 0 errors, `knip` 0, `docs:check` 0, and the V8 reader plus its CLI,
MCP, absolute-path and decimal-argument boundary files at 34 passing.
An independent reviewer ran these files on Node 22.23.4, 24.22.1 and 26.12.1. Only 22.23.4
failed, on `separates the compileFunction producer bit from the source length`, expecting
`compile_function` and reading `script`.

The cause is the fixture, not the parser: `vm.compileFunction(...).cachedData` carries
`0x20000009` in the source-length word on Node 24.22.1, with bit 29 set, while Node 22.23.4
does not set that bit at all. Whether a given V8 build marks the word is a build detail, so
asserting one build's spelling made the check version-dependent.

The case now reads the word the runtime produced and asserts the parser maps it correctly,
and keeps the part that must hold everywhere: the source length is the low bits, so it
equals both `word & 0x1fffffff` and the source's length. The flag meanings themselves stay
pinned by the synthetic `withHeaderWord` cases above, which do not depend on any build.

Reverting the parser's `compile_function` arm fails this case and
`keeps the function and module flags distinct`. `src/v8` plus the CLI, MCP and absolute-path
boundary files: 24 and 34 passing. `tsc` 0; `build` 0; `npm run format:check` 0;
`npm run lint` 0 errors; `knip` 0.
@XiaoBinGan
XiaoBinGan force-pushed the feat/v8-code-cache-inspector branch from 69aedae to 1886bea Compare November 9, 2026 07:26
`vm.compileFunction` marks bit 29 of the source-length word on Node 24.22.1 (`0x20000004`
for a 4-unit source) and does not mark it on Node 22.23.4 (`0x00000004` for the same call).
Whether a V8 build marks a function cache is therefore a build detail, and an unflagged
word is either a `vm.Script` cache or an unmarked function cache. The container carries
nothing that separates the two.

The reader reported `script` for that case, which is a confident claim the bytes do not
support. My previous commit made the test accept whichever value the runtime produced,
which recorded the ambiguity instead of resolving it in the contract. `unknown` is now a
producer value, the unflagged word maps to it, and the observed word stays in
`header.fields` for a caller that trusts a specific build fingerprint. A limitation line
says the same in the report itself.

`header.producer` widens to `["script", "compile_function", "module", "unknown"]`; `script`
is no longer produced, because no unflagged word can be shown to be one.

The spec's producer rule and its verification notes are updated to match. Reverting the
mapping to `script` fails 2 of the 24 `src/v8` cases. `src/v8` with the CLI, MCP and
absolute-path boundary files: 33 passing. `tsc` 0; `build` 0; `docs:check` 0;
`npm run format:check` 0; `npm run lint` 0 errors. `knip` reports one unused export
(`builtinDataEffectMethod`) on `main` as well, so it is not from this change.
@XiaoBinGan

Copy link
Copy Markdown
Contributor Author

You were right, and my previous commit made it worse rather than better. Fixed in 5ed500b08.

vm.compileFunction marks bit 29 of the source-length word on Node 24.22.1 (0x20000004 for a 4-unit source) and does not mark it on Node 22.23.4 (0x00000004 for the same call). So whether a V8 build marks a function cache is a build detail, and an unflagged word is either a vm.Script cache or an unmarked function cache. The container carries nothing that separates the two.

Reporting script for that case was a confident claim the bytes do not support, and changing the test to accept whichever value the runtime produced recorded the ambiguity instead of resolving it in the contract — exactly as you said.

Now:

  • unknown is a producer value and the unflagged word maps to it.
  • The observed word stays in header.fields, so a caller that trusts a specific build fingerprint can still resolve it.
  • A limitation line states the same in the report itself, since a report is read on its own.
  • header.producer widens to ["script", "compile_function", "module", "unknown"]. script is no longer produced, because no unflagged word can be shown to be one.

The spec's producer rule and verification notes are updated to match. Reverting the mapping to script fails 2 of the 24 src/v8 cases. src/v8 with the CLI, MCP and absolute-path boundary files: 33 passing. tsc 0; build 0; docs:check 0; format:check 0; lint 0 errors. knip reports one unused export (builtinDataEffectMethod) and it does so on main too, so it is not from this change.

@morluto
morluto merged commit 25885b0 into morluto:main Nov 9, 2026
5 of 7 checks passed
@morluto morluto added enhancement New feature or request area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants