Skip to content

feat(wasm): decode WebAssembly components offline - #2406

Open
all-black-493 wants to merge 16 commits into
morluto:mainfrom
all-black-493:feat/wasm-component-inspection
Open

all-black-493 wants to merge 16 commits into
morluto:mainfrom
all-black-493:feat/wasm-component-inspection

Conversation

@all-black-493

@all-black-493 all-black-493 commented Oct 12, 2026 •

Copy link
Copy Markdown

Summary

Adds inspect_wasm_component / rea inspect-wasm-component, an in-process decoder for WebAssembly component-model binaries. Refs #2350. The proposal and its open questions are in this comment.

Before this change, REA had no route for components. WABT 1.0.42 cannot parse them, and open_binary did not recognize their header.

Problem and expected behavior

A component (preamble 00 61 73 6D 0D 00 01 00) carries its own index spaces, typed imports and exports, embedded core modules and canonical ABI definitions. Treating it as a core module loses that structure.

Expected: given one local component file, REA returns its structure with byte ranges and provenance, and traces how component functions connect to core module exports and imports. It never validates, instantiates or executes anything.

Change and scope

  • Decoder. Written in src/wasm/ and pinned to component-model Binary.md at 06e3db0 (2026-09-23). It admits only version 0xd, layer 1. It reads the file through readStableArtifact and starts no subprocess, writes no temporary file, needs no WABT, and never instantiates or executes. Like the Go build-info reader (feat(go): inspect embedded binary build metadata #1363), it has its own provider identity, wasm-component-binary v1.
  • Result.
    • The file SHA-256 and size, and section payload ranges.
    • Imports and exports with name attributes and extern types.
    • Type definitions. Component, instance and core module type declarations sit in a flat type_scopes list, so neither the JSON nor the advertised schema is recursive.
    • Embedded core modules by range, SHA-256, header version and import/export names.
    • Core and component instances, aliases, canonical definitions with options (including the async, error-context and thread built-ins), start and value sections, the component-name section, custom sections, and nested components linked by parent.
    • Every definition reports the index it defines in its sort.
  • Relationships. lifts trace each canonical lift through the core instance alias to the core export it wraps. lowers trace each lower to its component import and to the core imports it is bound to through inline-export core instances. declared_by_module checks the module's own import or export section, and is null when that interface was not decoded.
  • Coverage. validation is always not_performed. Malformed framing (LEB128, lengths, UTF-8, trailing bytes, truncation) is a target failure (unsupported_target, failure_kind: "malformed") with the file offset, and keeps the file's SHA-256 and size as a partial observation. A well-framed construct that isn't decoded (GC core types, unknown section ids or opcodes, nesting beyond 16 components or 32 type scopes) is listed in coverage.not_decoded with its range. Decoding continues with the next section, and indices that later definitions add to the affected sorts become null, because their positions are unknown. gated_features lists the feature gates of encodings actually present.
  • Routing.
    • open_binary returns the new constraint wasm_component_requires_static_inspection, with a remediation pointing to inspect_wasm_component.
    • inspect_wasm_artifact returns unsupported_target for a component before resolving WABT or running any command. An 8-byte probe routes early; the stable read still decides.
    • Both use a single preamble helper, src/domain/wasm/wasmPreamble.ts, which the core-module check now uses too.
  • Limits. 8 MiB input, 8 MiB inline output, at most 524,288 decoded entries (each charged before it is decoded), and at most 65,536 lower-to-core-import bindings. More bindings fail with the same resource-constraint error before the result is built. File-controlled counts such as start results cost constant memory, relationship tracing is linear, and cancellation is checked between sections. Names keep a leading U+FEFF, and a type that fails partway leaves no scope behind. These allowances have no per-call control; fixed-ceiling-registry.json lists the input, entry and report allowances as pending under [Feature] Give native readers' fixed structural, text and inventory allowances a control or a stated fixed reason #14235.

Not included: validation, the canonical ABI layout, value decoding, tracing through outer aliases or instantiated nested components, and summary delivery (asked about in #2350). The issue asks for spec/plan/tasks under docs/specs/. That directory doesn't exist, and AGENTS.md says not to commit local planning artifacts, so the design is in the issue comment and here, and the user docs are in docs/guides/wasm/wasm-artifacts.md.

Follow the contribution scope. This is read-only static format inspection with no execution or mutation authority. #2350 asks whether a new in-process provider needs a separate maintainer decision; that is still pending.

Contract and boundary impact

  • Semantic owner and earliest changed stage: src/domain/wasm/wasmComponent.ts and wasmComponentTypes.ts (contract), src/wasm/WasmComponent*.ts (decoder), src/domain/wasm/wasmPreamble.ts (header identity).
  • Contribution scope fit and linked maintainer decision: format inspection; the provider question is pending in [Feature] Inspect WebAssembly components and canonical ABI declarations offline #2350.
  • CLI and MCP/tool-catalog contract: one new tool and CLI command; one new BinaryTargetError constraint. inspect_wasm_artifact and open_binary change only for component headers.
  • Provider, bridge, target-format, or platform compatibility: new in-process provider wasm-component-binary v1. No host tools are required.
  • Evidence, artifact, provenance, or reconstruction contract: Evidence subject format file; locations include the artifact path and any undecoded ranges.
  • Target selection, authority, upstream behavior, and cleanup details: one explicitly selected file. Following the read-ownership change on main (b955b82), the stable read and the WABT component probe release their file handles through a provider-owned ArtifactResourceScope. A failed release returns cleanup_incomplete with the primary error, and the handle is retried on the next read or at CLI/MCP shutdown, where the server closes the same WasmComponentService it binds to the tool.
  • Generated metadata, package, or installation impact: the product catalog adds the tool under the artifact surface with its own provider identity. The skill gets one entry and a reference line, with no version bump, following recent feature PRs.

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/wasm/WasmComponentDecoder.test.ts: index spaces across interleaved sections, lift/lower tracing, instance types with resources, names, gated encodings, nesting and its bound, partial coverage with null indices, an invalid name section, a non-core embedded module, malformed framing, unadmitted preambles and cancellation.
    • tests/acceptance/wasmComponentCli.test.ts and tests/boundary/mcp/wasmComponentMcp.test.ts: public CLI and MCP calls. They validate the advertised input and output JSON Schemas with Ajv 2020 after SDK conversion, and cover availability without an active target, session Evidence, typed errors and partial coverage.
    • Resource and fidelity regressions from review: a start section with 4,294,967,295 results, 20,000 lifts with 20,000 exports, 90,000 multiplicative lower bindings (typed failure), a name with a leading U+FEFF, and a type that fails after opening its scope.
    • tests/boundary/filesystem/targetDiagnostics.test.ts (open_binary routing) and src/wasm/WabtArtifactProvider.test.ts (WABT pre-check: no command runs and no workspace is created, with and without WABT configured).
    • Fixtures are original, encoded in memory by src/wasm/WasmComponentBinary.fixture.ts; no binary is committed.
  • Base reproduction: on main, open_binary does not recognize a component header, and inspect_wasm_artifact passes component bytes to WABT, which cannot decode them.

  • Real-producer cross-check (manual, not a CI lane): @bytecodealliance/jco 1.35.0, which bundles wasm-tools, run in an isolated directory.

    • jco print parses all three fixtures, with the same index numbering the decoder reports.
    • A component encoded by jco parse from WAT (records, variants, enums, flags, options, results, tuples, resource.new/drop/rep, a component-typed import, instantiation, inline-export instances, a module type and an outer alias) decodes to the same indices as jco print shows.
    • A real WASI 0.2 command component made by jco new --wasi-command (17,552 bytes) decodes completely. It has 8 imports, 4 core modules, 15 core instances, 13 lowers, 1 lift and 4 resource.drop, matching jco print. All 13 lowers trace to their WASI imports and adapter-module imports with declared_by_module: true. The lift traces to wasi:cli/[email protected]#run.
  • User-visible CLI/MCP output, from the WASI command component above (trimmed; ranges omitted, one entry per list shown):

    {
      "operation": "inspect_wasm_component",
      "normalized_result": {
        "validation": "not_performed",
        "coverage": { "status": "complete", "not_decoded": [] },
        "components": [{
          "imports": [
            { "name": "wasi:io/[email protected]", "attributes": [], "type": { "sort": "instance", "type": 0 }, "defines": { "sort": "instance", "index": 0 } },
            "… 7 more: wasi:io/streams, wasi:cli/stdin|stdout|stderr, wasi:clocks/wall-clock, wasi:filesystem/types|preopens"
          ],
          "exports": [
            { "name": "wasi:cli/[email protected]", "attributes": [], "target": { "sort": "instance", "index": 8 }, "type": null, "defines": { "sort": "instance", "index": 9 } }
          ],
          "lowers": [{
            "canon": 4, "func": 0, "core_func": 16,
            "component_source": { "kind": "instance-export", "instance": 4, "name": "get-stderr", "instance_import": "wasi:cli/[email protected]" },
            "satisfies": [{ "core_instance": 12, "core_module": 1, "import_module": "wasi:cli/[email protected]", "import_name": "get-stderr", "declared_by_module": true }]
          }],
          "lifts": [{
            "canon": 17, "func": 13, "core_func": 31, "type": 21,
            "core_source": { "core_instance": 12, "name": "wasi:cli/[email protected]#run", "core_module": 1, "declared_by_module": true },
            "exported_as": []
          }]
        }]
      }
    }
  • Remaining proof gaps:

    • The real-producer checks were run once by hand and are not an automated lane.
    • No component from a full language toolchain (Rust cargo component, componentize-py) was decoded.
    • Async, thread and map encodings are covered only by original fixtures and jco print parsing, not by producer output.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Validation performed

  • npm run check:
    • Typecheck, lint (0 errors), knip, metadata:check and architecture guards pass.
    • format:check flagged only untracked local build output outside this diff; oxfmt --check on the changed files passes.
    • The new modules add no lint warnings. In touched existing files, the new registration function's five parameters match registerGoTools.
  • npm run docs:check: passes.
  • New and affected source tests: 50 pass (decoder, WABT provider, effects, capability inventory, advertised examples). After both rounds of review fixes (head e1e9960db), the decoder and WABT provider suites pass (32 tests), as do the component CLI/MCP, WASM artifact MCP and target diagnostics suites (31 tests) and check:fast. Both real-producer components decode with identical output.
  • New and affected boundary/acceptance tests: 75 pass across 10 files (component CLI/MCP, WASM artifact MCP, target diagnostics, product catalog, CLI tool coverage, tool schema validity, local tool contracts, compact input schemas, setup skill).
  • After rebasing onto main at 11f8b7625 (head c103ec369):
    • check:fast, docs:check, knip and jscpd pass (2.99% duplicated lines, threshold 3.5%).
    • Source tests: 55 pass across the WASM suites and tool effects.
    • Boundary/acceptance: 42 pass across component CLI/MCP, WASM artifact MCP, target diagnostics, serverLifecycleMcp and artifactReadCleanupRetry. The last two are upstream's ownership tests, extended to the component provider and service. With the scope removed from the provider, the retry case fails with cancelled instead of cleanup_incomplete.
  • After merging main at 299c592b6 (merge c6e02f105, head fb8f71aec):
    • Conflicts are resolved onto main's current contract, capability, port, resource, parse-failure and target-failure owners. check:fast passes on the head. knip and docs:check pass on the merge. verify:advertised-schemas shows no schema difference on the head (its optional Rust and C++ engines are not installed here). Typed lint on the 49 changed files has 0 errors.
    • CI first failed on c6e02f105: moving the service to the shared executor had dropped its absolute-path check, which cliContractCommandParity caught. fb8f71aec declares the rule on the input schema and adds a relative-path regression.
    • Before that fix, 63 affected test files ran: 1,203 tests, 1 intermittent failure. localToolContracts "captures real process choices … untruncated" exceeded the MCP input-element allowance once, then passed on two reruns; it does not involve components. After it, 49 CLI, schema and path test files pass (1,667 tests).
    • Not run: full-repository lint:typed (it did not finish on this host) and the manual real-producer comparison, so the real-component results above predate this merge.
  • A wider run of 54 affected files before the rebase: 1 failure, tests/boundary/mcp/firmwareMcp.test.ts ("Unsupported tool version 26.6.4"). It fails the same way on the unmodified base on this host.

Compatibility, safety, and release

  • Breaking changes or migration steps: none. Core-module behavior is unchanged.
  • Real Hopper/Ghidra, browser, or OS coverage: Linux x64, Node 24.14.0. The decoder uses no host tools.
  • Package or release metadata impact: the product catalog gains one tool; no package or skill version changes.
  • Agent and analysis cost:
    • Measured before the merge with main and not repeated; main now omits output schemas from tools/list by default. tools/list grew by 33,919 bytes (about 1.35% of 2,516,115). Of that, 32,440 bytes is the typed output schema, 3rd largest of 188 tools (median 8,445), in the range of inspect_web_page and analyze_javascript_application. Tokens were not measured; at about 4 bytes per token that is roughly 8.5k tokens, an estimate.
    • The WASI command component returns 52,179 bytes of CLI JSON.
    • Decoding takes about 10–13 ms. The CLI run takes 1.6–1.8 s elapsed, about 2.4 s CPU and about 317 MB peak RSS, which matches the CLI's own startup cost on a missing file (1.6–1.8 s, about 2.4 s, about 315 MB).
    • Summary delivery or schema compaction could follow if wanted.
  • Security, privacy, process, or containment review:
    • Read-only parsing of one selected file, with bounded input and output, LEB128 width checks, vector counts limited by the remaining bytes, and bounded nesting. Nothing is executed or fetched.
    • Component names and strings are treated as target content, which is the default.

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.

Refs #2350

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

@matbrgz

matbrgz commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Review & Verification Summary

Verdict: LGTM (Approved) 🚀

1. Architecture & Design Alignment

  • Strict In-Process Isolation: Implements an offline parser in src/wasm/ pinned to the component-model specification (00 61 73 6D 0D 00 01 00), avoiding external subprocess spawning, WABT dependencies, or target execution side effects.
  • Epistemic Integrity & Limits:
    • Flat type_scopes prevents cyclic JSON serialization and recursive schema bloat.
    • Undecoded constructs (e.g. GC core types or depth > 16) are recorded in coverage.not_decoded rather than masked as absent.
    • Rejections fail closed with explicit offsets on malformed framing or truncated preambles.
  • Routing: Correctly adds wasm_component_requires_static_inspection in open_binary and guards inspect_wasm_artifact against feeding component preambles to WABT.

2. Local Verification

  • npm run test:local -- src/wasm/WasmComponentDecoder.test.ts passed (15/15 unit tests).
  • npm run check:fast (Turbo typecheck and lint) passed cleanly across all workspaces.

@morluto

morluto commented Oct 13, 2026

Copy link
Copy Markdown
Owner

@greptileai review

@greptile-apps

greptile-apps Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5 Tier: plus

[Medium impact] The PR adds component-file inspection and changes routing for component headers in existing WebAssembly workflows.

Not ready to merge: exported instances still hide known function sources, and the WABT probe still ignores cancellation.

Findings

  1. P1 Exported instances hide sources ▶
  2. P2 Earlier decoded names disappear ▶
  3. P2 Skipped names look complete ▶
  4. P2 Re-exported modules lose known checks ▶
  5. P2 Probe ignores cancellation ▶
Fix with agent prompt
### Issue 1
src/wasm/WasmComponentRelationships.ts:77-80
`inlineExportLookup` reads the instance's immediate origin without following its export chain. Import function `f`, put it in inline instance 0 as `g`, export that instance to define instance 1, then alias `g` from instance 1 and lower it. Instance 1 has an `export` origin, so this lookup misses instance 0. The lower reports `instance-export` with `instance_import: null` instead of import `f`, losing a known source despite complete decoding.

Resolve the instance's defining index before looking up its members.

### Issue 2
src/wasm/WasmCoreModuleInterface.ts:137-140
A failure late in a core import or export section discards the entries already decoded from that section. `decodeImports` and `decodeExports` return their local arrays only after the whole section succeeds, so the catch retains none of its earlier entries. `component-name` maps have the same problem.

This loses useful names from damaged components, contrary to the promise to keep names read before a failure. The reported missing range also starts after those lost names. Append each completed entry to the retained result before reading the next one.

### Issue 3
src/wasm/WasmComponentNames.ts:undefined-22
A `component-name` subsection with an ID other than `0` or `1` is silently skipped. No failure reaches the decoder, so `names.status` remains `"decoded"` and `coverage.status` can remain `"complete"` despite unread content. Callers cannot see which bytes were skipped. Record an `unsupported` gap for the skipped subsection, as the documented coverage contract promises.

### Issue 4
src/wasm/WasmComponentRelationships.ts:247-248
`coreSource` looks up a module's decoded interface using its new export index rather than its original index. If embedded module 0 exports `run`, is re-exported as module 1, and is then instantiated, a lift from that instance reports `declared_by_module: null` despite the fully decoded interface. Lower bindings have the same problem.

This loses a useful check against the module's declared imports and exports. Follow the module's export chain before looking up its interface.

### Issue 5
src/wasm/WabtComponentRouting.ts:undefined-58
`rejectWasmComponent` passes no cancellation signal to `withArtifactRegularFile`. If the caller cancels while the header is read or a recently written Windows file settles, the probe keeps waiting and can return a component refusal instead of cancellation. The provider's final cancellation check runs only after a runtime exists, which this early route never creates.

`AGENTS.md` requires cancellation to survive reads and cleanup. Before merging, forward the caller's signal through the probe and preserve its typed cancellation rather than swallowing it.

---

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

Summary

Adds offline WebAssembly component inspection through CLI and MCP. The latest update requires absolute paths in the shared contract and strengthens relative-path error checks.

  • Selected component files now produce a structural report with links to core-module interfaces.
  • CLI and MCP callers can inspect a selected component through one shared tool contract.
  • Component headers now route to static inspection instead of core-module handling.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  CLI["CLI selected path"] --> Resolve["Make caller path absolute"]
  Resolve --> Input["Check shared input contract"]
  MCP["MCP absolute path"] --> Input
  Input --> Read["Read stable file snapshot"]
  Read --> Decode["Decode component structure"]
  Decode --> Trace["Trace lifts and lowers"]
  Trace --> Evidence["Return Evidence with identity and coverage"]
Loading

Reviews (13) · Last reviewed commit: "fix(wasm): require an absolute component..." · Reviewed by Greptile

Comment thread src/wasm/WasmComponentDefinitions.ts Resolved
Comment thread src/wasm/WasmComponentRelationships.ts Resolved
Comment thread src/wasm/WasmComponentReader.ts Resolved
Comment thread src/wasm/WasmComponentTypeContext.ts Resolved
@greptile-apps

greptile-apps Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Comments Outside Diff

These findings could not be posted inline.

  • P2 Component guidance arrives too late src/wasm/WabtArtifactProvider.ts:209 ▶

    The component precheck runs after WABT configuration checks and all three --version commands. With WABT absent or mismatched, inspect_wasm_artifact never reaches the new component error or its remediation. With WABT installed, it still launches commands before rejecting the component, contrary to the documented route.

    Read and check the selected artifact before resolving or launching WABT.

@all-black-493

Copy link
Copy Markdown
Author

Addressed the Greptile review in ff49c1c15. All five findings were valid:

  1. Start results allocate per entry. Index spaces now store counts, with origins only for traceable entries. A start section declaring 4,294,967,295 results now decodes in constant time, and a following value gets index 4,294,967,295 (regression test).
  2. Tracing is quadratic. Lifts and lowers now use lookup tables built once (exports by defining function, inline exports by core function, instantiations by argument instance, per-module import/export sets), so tracing is linear. Lower-to-core-import bindings can still multiply, so one decode-wide budget fails with the output-budget resource error past 65,536 bindings, before anything is materialized. Tests: 20,000 lifts with 20,000 exports, and 90,000 multiplicative bindings.
  3. Leading U+FEFF stripped. The name decoder now uses ignoreBOM: true; a test distinguishes run from run.
  4. Partial scopes. Each top-level component or core type decodes atomically, and a failure drops every scope it registered. Your 01 42 02 01 7f ff example now leaves no scope and one not_decoded entry.
  5. WABT ordering. inspect_wasm_artifact probes the selected file's first 8 bytes before resolving WABT, so a component gets unsupported_target with no command launched and no workspace created, whether or not WABT is configured. The check after the stable read stays as the authoritative guard against replacement.

check:fast, the decoder and WABT suites (32 tests) and the component CLI/MCP, WASM artifact MCP and target diagnostics suites (31 tests) pass. The jco-encoded rich component and the real WASI command component decode with identical output. The docs now describe the binding limit and linear tracing.

Comment thread src/wasm/WasmComponentProvider.ts Resolved
Comment thread src/wasm/WasmCoreModuleInterface.ts Resolved
Comment thread src/wasm/WasmComponentRelationships.ts Resolved
Comment thread src/wasm/WasmComponentRelationships.ts Resolved
@all-black-493

Copy link
Copy Markdown
Author

Addressed Greptile's second review (head e1e9960db). Each finding is fixed in ab1ed7d4c, has a regression test, and its thread is resolved with details:

  • Memory amplification: one decode-wide budget charges every decoded entry and section before decoding (524,288 maximum, typed resource error).
  • Core exports overflow: loops replace the spread push; 150,000 exports now decode.
  • Aliases hide lower bindings: core functions resolve through inline-export aliases to their defining index.
  • Long export chains: a memoized, cycle-guarded walk replaces the 64-hop cap.

check:fast, the decoder and WABT suites (36 tests), and the component CLI/MCP, WASM artifact MCP and target diagnostics suites (31 tests) pass. Both real-producer components decode with identical output. The docs describe the entry budget (e1e9960db).

Add inspect_wasm_component / rea inspect-wasm-component, an in-process
decoder for component-model binaries (version 0xd, layer 1) pinned to
component-model Binary.md at 06e3db0. It reports the file SHA-256,
section ranges, typed imports and exports with name attributes, type
definitions in flat declaration scopes, embedded core modules by range,
SHA-256 and import/export names, instances, aliases, canonical
definitions, nested components and the component-name section.
Canonical lifts are traced to the core exports they wrap, and lowers to
their component imports and the core imports they are bound to.

Decoding is structural only: validation is never claimed, and the
component and its modules are never instantiated or executed.
Unsupported constructs are recorded with their ranges, decoding continues
with the next section, and indices that later definitions add to the
affected sorts become null. Malformed framing fails with its offset.

open_binary and inspect_wasm_artifact now route component headers to the
new tool instead of treating them as unknown or core binaries.

Refs morluto#2350
Address review findings on component decoding:

- Count start-section results in constant time instead of allocating
  one index-space entry per file-controlled result.
- Trace canonical lifts and lowers through lookup tables built once,
  so tracing is linear, and fail with the output-budget resource error
  when more than 65,536 lower bindings would be materialized.
- Keep a leading U+FEFF in length-prefixed names.
- Drop every scope registered by a type that fails partway, so no
  partial scope with a provisional range is reported.
- Route a component in inspect_wasm_artifact before any WABT
  configuration or command; the stable read still decides.

Refs morluto#2350
Address the second review of component decoding:

- Charge every decoded vector entry and section against one decode-wide
  budget before decoding it; past 524,288 entries the decode fails with
  a resource-constraint error instead of building an oversized result.
- Append embedded core module imports and exports in loops, so modules
  with very many entries no longer overflow call arguments.
- Resolve core functions re-exported through inline-export aliases to
  the function that defines them, so lowered functions keep their core
  import bindings.
- Replace the fixed export-chain hop limit with a memoized walk that
  guards against cycles, so long valid chains keep their sources.

Refs morluto#2350
Adopt the stable-read ownership pattern from b955b82 for
inspect_wasm_component and the WABT component pre-check.

- WasmComponentProvider reads through an ArtifactResourceScope, reports a
  failed descriptor release as cleanup_incomplete with the primary error,
  and retries that owner on close() or the next read.
- WasmComponentService exposes close(); MCP binds and closes one shared
  instance at shutdown, and the CLI finishes through finishAnalysisCommand.
- The WABT component probe moves to WabtComponentRouting and releases its
  handle through the provider scope instead of closing it directly.

Validation: check:fast, docs:check, knip; artifactReadCleanupRetry and
serverLifecycleMcp extended to the component provider and service, plus
component CLI/MCP, WASM artifact MCP, target diagnostics, capture cleanup,
decoder and WABT provider suites.
@all-black-493
all-black-493 force-pushed the feat/wasm-component-inspection branch from e1e9960 to c103ec3 Compare October 13, 2026 08:23
@all-black-493

Copy link
Copy Markdown
Author

Rebased onto main at 11f8b7625 to resolve the conflict with b955b82. Head is now c103ec369.

  • Conflict. WabtArtifactProvider.ts: kept main's #resources.run / #inspect structure and placed the component pre-check before WABT configuration, as before.
  • Ownership (c103ec369). The component tool now follows the same read-ownership pattern:
    • WasmComponentProvider reads through its own ArtifactResourceScope. A failed descriptor release returns cleanup_incomplete with the primary error, and that handle is retried on close() or the next read.
    • WasmComponentService.close() is called at MCP shutdown on the instance bound to the tool. The CLI finishes through finishAnalysisCommand.
    • The WABT component probe moved to WabtComponentRouting.ts and releases its handle through the provider scope.
  • Tests.
    • artifactReadCleanupRetry and serverLifecycleMcp now include the component provider and service. Without the scope, the retry case fails (cancelled instead of cleanup_incomplete).
    • check:fast, docs:check, knip and jscpd (2.99%) pass, along with 55 source tests and 42 boundary/acceptance tests.

Comment thread src/wasm/WasmComponentProvider.ts Resolved
Comment thread src/wasm/WasmComponentDefinitions.ts Resolved
Comment thread src/wasm/WasmComponentIndexSpaces.ts Resolved
Comment thread src/wasm/WasmCoreModuleInterface.ts Resolved
- Relationship facts repeat names, so one long import name could expand
  multiplicatively before the post-build size check. Each lift, lower and
  core binding is now charged by serialized size as it is traced, against
  the same 8 MiB inline budget, which replaces the binding count. Both
  output-limit paths map to one transport resource-constraint error.
- Component inline-export instances recorded no origin, so a function
  aliased out of one lost its import source. Core and component instances
  share one inline-exports origin and lookup, and tracing follows both.
- An undecoded section hid every index of its sorts. Index spaces keep the
  known prefix; only indices defined after the gap are unknown.
- Embedded core module interface and component-name failures did not
  reach coverage. The decoder records every gap through one function, and
  not_decoded entries say whether content is malformed or unsupported.

Validation: check:fast, docs:check, knip, jscpd; decoder tests for each
case fail on the previous source; component CLI/MCP (oversized result),
schema validity, WASM artifact, routing, lifecycle and cleanup suites.
Real jco components decode to identical output.
@morluto morluto added enhancement New feature or request area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior area: cli CLI adapter and one-shot commands area: server Server layer and tool wiring P2: medium Medium priority issue labels Oct 13, 2026
Comment thread src/cli/wasmCommands.ts Resolved
Comment on lines +79 to +82
const origin = spaces.origin(instanceSort, instance);
byInstance.set(
instance,
origin?.kind === "inline-exports"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Exported instances hide sources

inlineExportLookup reads the instance's immediate origin without following its export chain. Import function f, put it in inline instance 0 as g, export that instance to define instance 1, then alias g from instance 1 and lower it. Instance 1 has an export origin, so this lookup misses instance 0. The lower reports instance-export with instance_import: null instead of import f, losing a known source despite complete decoding.

Resolve the instance's defining index before looking up its members.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/wasm/WasmComponentRelationships.ts
Line: 79-82

Comment:
**Exported instances hide sources**

`inlineExportLookup` reads the instance's immediate origin without following its export chain. Import function `f`, put it in inline instance 0 as `g`, export that instance to define instance 1, then alias `g` from instance 1 and lower it. Instance 1 has an `export` origin, so this lookup misses instance 0. The lower reports `instance-export` with `instance_import: null` instead of import `f`, losing a known source despite complete decoding.

Resolve the instance's defining index before looking up its members.

---

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

Comment on lines +137 to +140
if (id === IMPORT_SECTION)
for (const entry of decodeImports(section)) imports.push(entry);
else if (id === EXPORT_SECTION)
for (const entry of decodeExports(section)) exports.push(entry);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Earlier decoded names disappear

A failure late in a core import or export section discards the entries already decoded from that section. decodeImports and decodeExports return their local arrays only after the whole section succeeds, so the catch retains none of its earlier entries. component-name maps have the same problem.

This loses useful names from damaged components, contrary to the promise to keep names read before a failure. The reported missing range also starts after those lost names. Append each completed entry to the retained result before reading the next one.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/wasm/WasmCoreModuleInterface.ts
Line: 137-140

Comment:
**Earlier decoded names disappear**

A failure late in a core import or export section discards the entries already decoded from that section. `decodeImports` and `decodeExports` return their local arrays only after the whole section succeeds, so the catch retains none of its earlier entries. `component-name` maps have the same problem.

This loses useful names from damaged components, contrary to the promise to keep names read before a failure. The reported missing range also starts after those lost names. Append each completed entry to the retained result before reading the next one.

---

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

@CassieFox23

CassieFox23 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Edit: new results on head f10cbea are in #2406 (comment).

TL;DR: The new rea inspect-wasm-component command works on head b2523d7 on Node 22, 24 and 26. It also stops inspect-wasm-artifact from starting WABT on a component. One open review finding still reproduces, and head now conflicts with main.

I tested head b2523d7 as pushed. GitHub says it conflicts with main b7dcf78. For "before", I used main b7dcf78, which has no component command.

Results

Check Node 22.23.1 Node 24.18.0 Node 26.11.1
Seven PR test files, head (63 tests) 61 pass, 2 skipped 63 pass 63 pass

The 2 skipped tests are SQLite tests that skip unless the Node SQLite object has a limits property. Node 22.23.1 skips them. The PR did not add them.

Before and after, Node 24.18.0, on a 302-byte component from the PR's own fixture builder:

Check Main Head
Decode a component unknown command works, exit 0
Inspect a component, no WABT set tool missing error refused, points to the new tool
Same, with stand-in WABT scripts 6 commands started 0 commands started
A core module, same scripts 6 commands started 6 commands started
Open it as a binary refused as unknown format refused, points to the new tool

On head, the decode lists two imports, log and the WASI filesystem types. It traces the lift of run. It traces the lower of log to the core import host.log. On head, both refusals name inspect_wasm_component. The tool missing error comes from the unset WABT folder.

The stand-in scripts are mine. They print 1.0.42 and write one line per call. They are not real WABT.

More head checks (Node 24.18.0)
  • An old version number is refused.
  • A file cut inside a section fails with invalid_request at offset 10.
  • A nested component with gated encodings decodes. Component 1 has parent 0. It reports five gated features. They include async, map and a version suffix.
  • Three decodes took 0.77 s each. User CPU was 0.86 to 0.91 s, and peak memory was 319 to 330 MB. A missing file took 0.74 to 0.75 s and 320 MB. The PR body says about 317 MB, which is close. It says 1.6 to 1.8 s, which this box beat.
  • To build the open finding: import f, put it in an inline instance as g, and export that instance. Alias g from the new instance and lower it.

One open finding reproduces. Greptile's open P1 says an exported instance hides where a lowered function came from. In my build of that case, head reports instance_import: null, while coverage says complete.

CI. Four lanes fail on head: web_runtime, web_source_map, the Windows lane and CI required. The Windows lane fails in a step about native inspection failure ownership. That is near this PR's read cleanup work. I did not confirm a link. Earlier pushes have no finished Windows run to compare. The latest CI run on main passes.

Not run

  • Real producer output. jco and wasm-tools are not installed here.
  • Real WABT. I used stand-in scripts.
  • Head merged onto main. A text-level three-way diff shows one clash in each of four files. They are the target resolver, the capability list, the server setup and the WABT test. That is not a real git merge.
  • The target diagnostics test file, because it calls the doctor host.
  • Windows, macOS, and the rest of the test suite.

Thanks, all-black-493, for the decoder and for fixtures built in memory.

Another job ran on this box. Load average (busy tasks over 1 minute, on 24 threads) was 2.3 to 4.3.

Test setup
  • Box: Nobara 44 (Fedora 44 base), Linux 7.2.9
  • CPU: AMD Ryzen 9 5900X, 12 cores / 24 threads
  • RAM: 32 GB DDR4-3600
  • Node: 22.23.1, 24.18.0, 26.11.1
  • Head: b2523d7
  • Base: 2895a18
  • Other: main b7dcf78; GNU time 1.9; fixtures from the PR's fixture builder
Commands
npm ci && npm run build && npm run test:prepare
node scripts/run-development-tests.mjs focused src/wasm/WasmComponentDecoder.test.ts src/wasm/WabtArtifactProvider.test.ts src/contracts/toolEffects.test.ts tests/acceptance/wasmComponentCli.test.ts tests/boundary/mcp/wasmComponentMcp.test.ts tests/boundary/mcp/serverLifecycleMcp.test.ts tests/boundary/providers/artifactReadCleanupRetry.test.ts
node scripts/rea.mjs inspect-wasm-component <component> --json
node scripts/rea.mjs inspect-wasm-artifact <component or core module> --json
node scripts/rea.mjs inspect <component or core module> --json
/usr/bin/time -f "elapsed=%e user=%U maxrss_kb=%M" node scripts/rea.mjs inspect-wasm-component <component> --json

Each run sat under systemd-run --user --scope -p MemoryMax=6G. The stand-in folder held three small scripts. Each one took the name of a real WABT tool. REA_WABT_BIN_DIRECTORY pointed at it.

🤖 Generated with Claude Code (Sonnet 5.5, verified by Opus 5.5) 🦊

# Conflicts:
#	src/application/BinaryTargetResolver.ts
#	src/application/CapabilityInventory.ts
#	src/server/createServer.ts
#	src/wasm/WabtArtifactProvider.test.ts
@kaoru0822-kitauji

Copy link
Copy Markdown
Collaborator

Merged latest main into this branch to resolve four conflicts. No rebase or force-push was used.

  • BinaryTargetResolver.ts: kept this PR's readWasmPreamble, isCoreWasmModule and isWasmComponent checks. They cover main's inline Wasm v1 check and add the component refusal. Main's 4096-byte magic read is unchanged.
  • CapabilityInventory.ts: inspect_wasm_component is now listed as always available alongside main's inspect_go_binary, inspect_rust_binary and inspect_electron_fuses.
  • createServer.ts: kept both the wasmComponent service and main's providerEnvironment.
  • WabtArtifactProvider.test.ts: kept main's new output-limit tests and this PR's "routes a selected component before any WABT configuration or command" test.

Validation:

  • WabtArtifactProvider, WasmComponentDecoder and toolEffects tests: 53 passed;
  • wasmComponentCli acceptance, targetDiagnostics and serverLifecycleMcp tests: 42 passed;
  • wasmComponentMcp and artifactReadCleanupRetry boundary tests: 5 passed;
  • typecheck and lint, via the pre-push hook.

@greptile-apps

greptile-apps Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Want your agent to iterate on Greptile's feedback? Try greploops.

@CassieFox23

CassieFox23 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

TL;DR: My earlier result still holds on the new head f10cbea. The rea inspect-wasm-component command works, and inspect-wasm-artifact still starts no WABT command on a component. One open review finding still reproduces. My earlier head was b2523d7.

Edit: I retested on head 2ed3b71. The open finding still reproduces. New results are here.

This follows my earlier result on head b2523d7. Head is now f10cbea, a merge of main by Kaoru0822. The author's note says the merge fixed four conflicts. The merge-base with today's main 9d6651e is 6fcfc5b. GitHub now reports a conflict with today's main. I did not check that myself.

Check Node 22.23.1 Node 24.18.0 Node 26.11.1
Seven PR test files, head 68 pass, 2 skipped 70 pass 70 pass

Last time the seven files held 63 tests. Main's new tests came in with the merge, so the count is higher. The 2 skipped tests are the same SQLite tests as before, which Node 22.23.1 skips.

Node 24.18.0, on the same 302-byte component from the PR's fixture builder:

Check Head f10cbea Same as on b2523d7?
Decode a component works, exit 0 yes
Inspect a component, no WABT set refused, names the new tool yes
Same, with stand-in WABT scripts 0 commands started yes
A core module, same scripts 6 commands started yes
Open it as a binary refused, names the new tool yes
Old version number refused yes
File cut inside a section invalid_request at offset 10 yes
A nested component decodes, exit 0 yes

The decode lists the import log and the WASI filesystem import. The stand-in scripts are mine. They print 1.0.42 and write one line per call. They are not real WABT.

The open finding still reproduces. An open Greptile note says an exported instance hides a function's source. I built the same case as before. Head reports instance_import: null there, yet coverage says complete.

Speed. Three decodes took 0.99 to 1.07 s and used 325 to 327 MB at peak. The box was busier this time, with a load average of about 6, so my earlier 0.77 s is not a fair comparison.

Not run

  • Real producer output. jco and wasm-tools are not installed here.
  • Real WABT. I used stand-in scripts.
  • Head merged onto today's main.
  • The target diagnostics test file, because it calls the doctor host.
  • Windows, macOS, and the rest of the test suite.
  • The tests on main as a "before". They import files that main does not have.
  • CI. A check of GitHub's status list shows no failing check among 40, but I did not read the logs.

Thanks, all-black-493, for the decoder. Thanks, Kaoru0822, for the merge.

The box was shared with other test jobs. Timings are not benchmarks.

Test setup
  • Box: Nobara 44 (Fedora 44 base), Linux 7.2.9
  • CPU: AMD Ryzen 9 5900X, 12 cores / 24 threads
  • RAM: 32 GB DDR4-3600
  • Node: 22.23.1, 24.18.0, 26.11.1
  • Head: f10cbea
  • Base: 6fcfc5b
  • Other: GNU time 1.9; fixtures from the PR's fixture builder
Commands
npm ci && npm run build && npm run test:prepare
node scripts/run-development-tests.mjs focused src/wasm/WasmComponentDecoder.test.ts src/wasm/WabtArtifactProvider.test.ts src/contracts/toolEffects.test.ts tests/acceptance/wasmComponentCli.test.ts tests/boundary/mcp/wasmComponentMcp.test.ts tests/boundary/mcp/serverLifecycleMcp.test.ts tests/boundary/providers/artifactReadCleanupRetry.test.ts
node scripts/rea.mjs inspect-wasm-component <component> --json
node scripts/rea.mjs inspect-wasm-artifact <component or core module> --json
node scripts/rea.mjs inspect <component or core module> --json
/usr/bin/time -f "elapsed=%e user=%U maxrss_kb=%M" node scripts/rea.mjs inspect-wasm-component <component> --json

Each test run sat under systemd-run --user --scope -p MemoryMax=8G. The stand-in folder held three small scripts. Each one took the name of a real WABT tool. The setting REA_WABT_BIN_DIRECTORY pointed at it. The trees share one node_modules from npm ci, since the lockfiles match.

🤖 Generated with Claude Code (Sonnet 5.5, verified by Opus 5.5) 🦊

Resolve the conflicts with main at 32f0e51. No rebase or force-push.

- src/cli/wasmCommands.ts: keep the component command and take main's
  absoluteCallerPath (morluto#4067). The component path now uses it too, instead
  of path.resolve, so `link/../file` selects the file the filesystem
  names. Pass the command signal to finishAnalysisCommand, which main now
  requires (279c590).
- src/server/createServer.ts: keep main's rustBinary service and this
  PR's wasmComponent service in construction, shutdown and the tool
  context.
- tests/boundary/mcp/serverLifecycleMcp.test.ts: keep main's scenario
  capture service and this PR's component service in the shutdown test.
- src/wasm/WabtComponentRouting.ts: the component probe reads its header
  through main's withArtifactFileHandle, so a failed close is retained as
  a lease and its error resolves on retry, as main's WABT descriptor-retry
  test requires.
- tests/boundary/cli/callerPathSymlinkParentCli.test.ts: cover
  inspect-wasm-component through a symlink and `..`; it fails with
  path.resolve.
Main now gives every stable read one descriptor owner,
withArtifactFileHandle. A failed close throws ArtifactFileCleanupFailure
with a cleanup lease, and providers bind that lease to the error they
return, so the error resolves once a later close succeeds.

- WasmComponentProvider classifies the physical primary failure inside
  ArtifactFileCleanupFailure, binds its lease to the returned error and
  to close() failures, and runs the whole operation inside its scope,
  as main's Go, Rust and PE providers do.
- Cancellation is the decoder's exact abort reason. Previously any
  failure seen with an aborted signal became cancelled, so a read denied
  or over the size limit was misreported when cancellation arrived
  during close.
- File-size refusals name selected-input recovery, as in main.

Validation: main's stableArtifactConsumers cases now include the
component provider (the two read-failure cases failed before this fix);
check:fast, docs:check, knip and jscpd; 115 source and 134 boundary,
acceptance and process-global tests.
Comment thread src/wasm/WabtComponentRouting.ts Resolved
sub.expectEnd("component name subsection");
return;
}
if (id !== 1) return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Skipped names look complete

A component-name subsection with an ID other than 0 or 1 is silently skipped. No failure reaches the decoder, so names.status remains "decoded" and coverage.status can remain "complete" despite unread content. Callers cannot see which bytes were skipped. Record an unsupported gap for the skipped subsection, as the documented coverage contract promises.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/wasm/WasmComponentNames.ts
Line: 21

Comment:
**Skipped names look complete**

A `component-name` subsection with an ID other than `0` or `1` is silently skipped. No failure reaches the decoder, so `names.status` remains `"decoded"` and `coverage.status` can remain `"complete"` despite unread content. Callers cannot see which bytes were skipped. Record an `unsupported` gap for the skipped subsection, as the documented coverage contract promises.

---

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

Pick up main's plist and UI finalization test alignment (d1adc60),
which the keyed-archive date and number tests on this branch's previous
base need.
CI shard 2 failed when a cli-boundary worker reached its 384 MiB heap
limit. Every test passed; the worker aborted. Those workers reuse one
module graph, and this PR added about 3 MiB to it at CLI startup.

Two static paths loaded the component code into every CLI process:
composition/wasm.ts imported the component service and decoder, and
wasmToolContracts.ts built the component result schema, both pulled in
just to register inspect-wasm-artifact.

- Component composition moves to composition/wasmComponent.ts, which
  the component command loads on demand, as main's deferred commands
  do (a4dd4e8). MCP still composes it at server start.
- The component contract moves to wasmComponentToolContracts.ts, read
  by the tool catalog and the catalog scripts. Main already keeps that
  catalog out of CLI startup.
- cliStartupImports lists the component composition, decoder and
  schema, so `rea --help` must not resolve them.

Measured in a cli-boundary worker against main at a80575c (3 runs
each): module graph before the first command 185.2 MiB vs 185.6 MiB on
main, previously 187.7 MiB. After a command that loads the tool catalog,
219.8 MiB vs 217.8 MiB; that 2 MiB is this tool's schema in the catalog.
The startup bundle no longer contains the decoder.
@all-black-493

Copy link
Copy Markdown
Author

CI on 8d8c0983e: every test passed. Shard 2 failed when a cli-boundary worker hit its 384 MiB heap limit (FATAL ERROR: Reached heap limit, SIGABRT during cliIntegerArguments.test.ts). Shards 1, 4 and 5 were then cancelled by fail-fast, and the portable merge reported the same crash.

Head is now 2ed3b7152:

  • 14f641411 merges main at a80575c73, including d1adc6079. That commit fixes the keyed-archive tests that fail on this branch's previous base.

  • 2ed3b7152 stops the component code loading at CLI startup. Those workers reuse one module graph, and this PR added about 3 MiB to it through two static paths:

    • composition/wasm.ts imported the component service and decoder.
    • wasmToolContracts.ts built the component result schema.

    Both were loaded just to register inspect-wasm-artifact. Component composition now lives in composition/wasmComponent.ts, loaded on demand like main's deferred commands (a4dd4e8). The contract now lives in wasmComponentToolContracts.ts, read only by the tool catalog and the catalog scripts. cliStartupImports lists the new modules.

Measured in a cli-boundary worker against main at a80575c73 (3 runs each):

Retained heap main Before After
Before the first command 185.6 MiB 187.7 MiB 185.2 MiB
After a command that loads the tool catalog 217.8 MiB 219.8 MiB 219.8 MiB

The remaining 2 MiB is this tool's schema in the catalog, which every catalog consumer needs. The startup bundle no longer contains the decoder.

The crashed worker still had about 356–379 MiB live after a full collection. This PR now adds at most 2 MiB of that, so main itself is close to the limit in this project. I could not reproduce the crash locally: CI orders shards by recorded test timings, so the worker mix differs. Raising the 384 MiB budget is a separate decision, so I have not changed it.

Validation: check:fast, docs:check and knip; 90 source tests; 110 boundary and acceptance tests across 13 files, including cliStartupImports, the component CLI/MCP tests, tool schemas, the catalog and keyed-archive tests.

Comment on lines +249 to +250
const module = instance?.kind === "core-instantiate" ? instance.module : null;
const declared = module === null ? undefined : interfaces.exports.get(module);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Re-exported modules lose known checks

coreSource looks up a module's decoded interface using its new export index rather than its original index. If embedded module 0 exports run, is re-exported as module 1, and is then instantiated, a lift from that instance reports declared_by_module: null despite the fully decoded interface. Lower bindings have the same problem.

This loses a useful check against the module's declared imports and exports. Follow the module's export chain before looking up its interface.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/wasm/WasmComponentRelationships.ts
Line: 249-250

Comment:
**Re-exported modules lose known checks**

`coreSource` looks up a module's decoded interface using its new export index rather than its original index. If embedded module 0 exports `run`, is re-exported as module 1, and is then instantiated, a lift from that instance reports `declared_by_module: null` despite the fully decoded interface. Lower bindings have the same problem.

This loses a useful check against the module's declared imports and exports. Follow the module's export chain before looking up its interface.

---

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

@CassieFox23

Copy link
Copy Markdown
Contributor

TL;DR: My earlier results still hold on the new head, 2ed3b71. The command rea inspect-wasm-component works. The command inspect-wasm-artifact still starts no WABT command on a component. The one open finding I reported before still reproduces. The four other open Greptile threads are real too.

This follows my earlier result on head f10cbea. Since then the branch got two merges of main. It also got two commits by the author. They are 8d8c098 (read cleanup) and 2ed3b71 (load the decoder only when used). I tested head 2ed3b71 as pushed. Its base with main is a80575c. Today's main is 974487f, and I did not test main.

My earlier checks

I used the same 302-byte component from the PR's fixture builder. I used the same stand-in WABT scripts. Results were the same on Node 22.23.1, 24.18.0 and 26.11.1.

Check At f10cbea (Node 24) At 2ed3b71
Decode a component works, exit 0 works, exit 0. Two imports, one lift, two lowers, coverage complete
Inspect a component, no WABT set refused, names the new tool still refused, names the new tool
Same, with stand-in WABT scripts 0 commands started still 0 commands started
A core module, same scripts 6 commands started still 6 commands started
Open it as a binary refused, names the new tool still refused, names the new tool
Old version number refused still refused
File cut inside a section invalid_request at offset 10 still invalid_request at offset 10
A nested component with gated encodings decodes, exit 0 decodes, exit 0. Two components, parent 0, five gated features
Test files, my earlier list of seven plus three the PR now touches 70 pass on Node 24 (seven files) 10 files, 112 tests pass on Node 24 and 26. On Node 22, 110 pass and 2 skip in serverLifecycleMcp.test.ts. More tests than before, because the list grew from seven files to ten.

The decode is the real test of 2ed3b71, since that commit moved the component code to load on demand.

Open review finding

Still reproduces. The thread is Exported instances hide sources. Head still reports instance_import: null for a lowered function that comes from an exported instance. The coverage says it is complete. The code for this is byte for byte the same as at f10cbea.

Bot threads at 2ed3b71

There are 5 open threads, all from Greptile. I built a small case for each.

Thread Result
Exported instances hide sources Real, as above
Earlier decoded names disappear Real. A core import section cut after one good entry reports no imports at all
Probe reads device paths Real. A trace of inspect-wasm-artifact /dev/null shows the probe reading the file before any regular-file check
Skipped names look complete Real. A component-name section with an unknown subsection id decodes as complete
Re-exported modules lose known checks Real. A module exported and then instantiated gives declared_by_module: null
Details for each thread
  • Exported instances hide sources: import f and put it in an inline instance as g. Export that instance, alias g from the export, and lower it. The lower reports instance-export with instance_import: null, not import f. Same on Node 22, 24 and 26.
  • Earlier decoded names disappear: a core module with a good import host.log and then a cut second entry. The module interface is not_decoded with imports: []. I did not run the component-name map half, so that half is a read of the code only.
  • Probe reads device paths: the new header probe in the WABT routing file opens the path and reads 8 bytes. For /dev/null, the trace shows an open and a pread64 on the same descriptor and no file-type check. This only ran on /dev/null, which reads as empty.
  • Skipped names look complete: subsection id 2 is skipped with no gap, so names stay decoded and coverage stays complete.
  • Re-exported modules lose known checks: module 0 exports run. It is exported as module 1 and is instantiated. A lift of run reports core_module: 1 and declared_by_module: null. The core module list holds only index 0.

Not run

  • Real producer output. jco and wasm-tools are not installed here.
  • Real WABT. I used stand-in scripts.
  • Head merged onto today's main.
  • The target diagnostics test file, because it calls the doctor host.
  • Windows, macOS, and the rest of the test suite.
  • The author's own numbers: the heap sizes, the check:fast, docs:check and knip runs, and the CI crash. I did not run them and cannot say they are right or wrong.
  • CI. I did not read any logs.

Thanks, all-black-493, for the quick work on the startup load and the read cleanup.

Test setup
  • Box: Nobara 44 (Fedora 44 base), Linux 7.2.9
  • CPU: AMD Ryzen 9 5900X, 12 cores / 24 threads
  • RAM: 32 GB DDR4-3600
  • Node: 22.23.1, 24.18.0, 26.11.1
  • Head / base: 2ed3b71 / a80575c
  • Other: main 974487f; strace for the device-path check; fixtures from the PR's fixture builder; the box was shared with other test jobs
Commands
npm ci --ignore-scripts && npm run build:cached && npm run test:prepare
npm run test:focused -- src/wasm/WasmComponentDecoder.test.ts src/wasm/WabtArtifactProvider.test.ts src/contracts/toolEffects.test.ts tests/acceptance/wasmComponentCli.test.ts tests/boundary/mcp/wasmComponentMcp.test.ts tests/boundary/mcp/serverLifecycleMcp.test.ts tests/boundary/providers/artifactReadCleanupRetry.test.ts tests/boundary/cli/callerPathSymlinkParentCli.test.ts tests/boundary/cli/cliStartupImports.test.ts tests/process-global/stableArtifactConsumers.test.ts
node scripts/rea.mjs inspect-wasm-component <component> --json
node scripts/rea.mjs inspect-wasm-artifact <component or core module> --json
node scripts/rea.mjs inspect <component> --json
strace -f -e trace=openat,pread64,fstat,statx -o <log> node scripts/rea.mjs inspect-wasm-artifact /dev/null --json
npm run test:focused -- <my probe file>

The probe file builds five small components with the PR's fixture helpers and asserts the correct behaviour, so a failing probe means the thread is real. The stand-in folder held three small scripts named like the real WABT tools. Each printed 1.0.42 and wrote one line per call. REA_WABT_BIN_DIRECTORY pointed at it. Every build and test run sat under systemd-run --user --scope -p MemoryMax=8G.

None of the ten test files runs the doctor command. cliStartupImports names doctor modules only to check they do not load.

🤖 Generated with Claude Code (Sonnet 5.5, verified by Opus 5.5) 🦊

Comment thread src/wasm/WasmComponentProvider.ts Outdated
);
const report = {
artifact: {
path: input.path,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] Retain the completed file identity after component decoding fails

A task-owned 10-byte component (0061736d0d0001000a05) passes the verified read with SHA256 bea22b525205cfb7749116a24459824d91fb9932c175d7ca0088205c48859cb1. The production decoder then refuses the section extent, and both WasmComponentProvider.inspect and the shared service return AnalysisInputError with no partial observation/digest/byte count (cause: section extends past its enclosing range at offset10). The successful snapshot lives only inside #inspect, while outer inspect maps only the cause/path, so an already completed observation is lost before CLI/MCP delivery. Retain successful verified-read facts in the owning failure representation through decoder refusal and post-read cancellation, following the existing artifact-failure pattern, and add those regressions. The public result should still report decoding failure, with the known source identity accessible. This was a bounded production provider/service probe at2ed3b7152c; no component was instantiated or executed and no compiled adapter behavior is claimed.

@morluto

morluto commented Nov 24, 2026

Copy link
Copy Markdown
Owner

@all-black-493 thanks for the PR — there are 6 open review threads here:

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

@morluto

morluto commented Nov 24, 2026

Copy link
Copy Markdown
Owner

@all-black-493 also, this branch has merge conflicts with main — please resolve those along with the open threads.

Resolve conflicts by expressing the component tool on main's current owners:

- Registration moves to the contract, capability, tool-family, CLI and MCP
  binding declarations; the removed cliCommandNames, registerWasmTools and
  per-tool effect tables are not restored.
- The port moves to src/ports. The service uses executeArtifactInspection,
  and the provider uses the shared failure classifier and stable artifact
  projection, which keep the completed file identity on later failures.
- The decoder uses the shared parse-failure, LEB128, UTF-8, SHA-256, budget
  and coverage owners. Malformed components are now target refusals
  (unsupported_target, failure_kind malformed), as for other readers on main.
- The WABT component probe admits only regular files.
- The fixed input, entry and report allowances are registered as pending a
  control (morluto#14235).
- The component guide moves to docs/guides/wasm/wasm-artifacts.md.
@all-black-493

all-black-493 commented Nov 25, 2026 •

Copy link
Copy Markdown
Author

Merge conflicts are resolved. Head is now fb8f71aec: c6e02f105 merges main at 299c592b6, and fb8f71aec restores the absolute-path check that the merge dropped (caught by cliContractCommandParity in CI; a relative-path regression is added).

  • Structure. The component tool is expressed on main's current owners: contract, capability, tool-family and CLI/MCP binding declarations; src/ports; executeArtifactInspection; the shared failure classifier and stable-artifact projection; and the shared parse-failure, LEB128, UTF-8, SHA-256, budget and coverage code.
  • Behavior change. A malformed component is now a target failure (unsupported_target, failure_kind: "malformed") instead of invalid_request, as for other readers on main.
  • Limits. The fixed input, entry and report allowances are registered as pending under [Feature] Give native readers' fixed structural, text and inventory allowances a control or a stated fixed reason #14235. Please say if you would rather have per-call controls in this PR.
  • Review threads. The WABT probe now admits only regular files, and a decode failure keeps the completed file identity (asserted in wasmComponentMcp.test.ts). The other four threads are not addressed yet.

Validation: CI passes on fb8f71aec. Locally, check:fast passes, typed lint on the 49 changed files has 0 errors, and 49 CLI, schema and path test files pass after the fix (1,667 tests). Before it, 63 affected files ran (1,203 tests) with 1 intermittent localToolContracts failure that passed on two reruns and does not involve components. The real-component comparison was not repeated. Both new commits are unsigned.

component = await withArtifactRegularFile(
path,
scope,
undefined,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Probe ignores cancellation

rejectWasmComponent passes no cancellation signal to withArtifactRegularFile. If the caller cancels while the header is read or a recently written Windows file settles, the probe keeps waiting and can return a component refusal instead of cancellation. The provider's final cancellation check runs only after a runtime exists, which this early route never creates.

AGENTS.md requires cancellation to survive reads and cleanup. Before merging, forward the caller's signal through the probe and preserve its typed cancellation rather than swallowing it.

Context Used: AGENTS.md (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/wasm/WabtComponentRouting.ts
Line: 58

Comment:
**Probe ignores cancellation**

`rejectWasmComponent` passes no cancellation signal to `withArtifactRegularFile`. If the caller cancels while the header is read or a recently written Windows file settles, the probe keeps waiting and can return a component refusal instead of cancellation. The provider's final cancellation check runs only after a runtime exists, which this early route never creates.

`AGENTS.md` requires cancellation to survive reads and cleanup. Before merging, forward the caller's signal through the probe and preserve its typed cancellation rather than swallowing it.

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

---

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

The service checked isAbsolute itself before it moved to the shared artifact
inspection executor. Its schema still admitted relative paths, so the merge
dropped that refusal. Declare it on the input schema, as sibling tools do.

This branch has not been deployed

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

Labels

area: cli CLI adapter and one-shot commands area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior area: server Server layer and tool wiring enhancement New feature or request P2: medium Medium priority issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants