Compare commits

...
Author SHA1 Message Date
Kaoru0822andClaude Opus 5.5 92fddf3176 fix(adb): share host configuration refusals with apktool
The ADB provider, which the apktool provider mirrors, had the same two
defects: a relative REA_ADB_PATH escaped as UNKNOWN because selection
ran before the try that maps configuration failures, and a missing adb
binary projected generic target advice instead of its reason.

Move the configuration-failure-to-refusal mapping into one
providerConfigurationRefusal helper used by both providers, resolve the
ADB selection inside the mapped try, and share the CLI refusal assertion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 20:05:33 +00:00
Kaoru0822andClaude Opus 5.5 9655845bbc fix(apktool): name host requirements in configuration refusals
A missing apktool launcher projected the generic "unavailable for the
current target" message and remediation, leaving the actual reason only
in details.reason. A relative REA_APKTOOL_COMMAND escaped as UNKNOWN
because command selection ran before the try that maps configuration
failures.

Resolve the selection inside that try for both execution and
availability, and pass the refusal reason as userMessage, as JADX and
the adapters fixed in #1224 do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 19:35:57 +00:00
12ee785e5e feat(website): follow the system dark mode and fix small-screen text (#1894)
* fix(website): keep text inside small screens and tidy small type and spacing

From a layout audit of the built pages:

- Long terminal prompts and code-header buttons wrap instead of being cut
  off at 320px (WCAG 1.4.10).
- Headings and table cells break long words, so the 1.4.12 text-spacing
  test no longer widens pages past 320px.
- Header and footer links get a 24px minimum height (2.5.8).
- Labels that rendered under 12px now render at 12px or more, and inline
  code never drops under 0.75rem.
- The home page's hero and definition rows share one column gap and align
  on the first baseline, and stacked boxes share one corner size.
- Highlight chips get room around the text, and the active run in a step
  listing is one band instead of a box per line.

Colors are unchanged.

🤖 Generated with Claude Code (Sonnet 5.5) 🦊

* feat(website): follow the system dark mode

The site was light only, so a reader with a dark system still got a white
page. Add one prefers-color-scheme: dark block to the stylesheet that swaps
the six color variables to Catppuccin Mocha (MIT) and overrides the fixed
colors that would break on a dark page: selection, buttons, tinted
highlights, flow nodes and arrows, and a visible border on the agent
terminal.

Add a dark theme-color tag beside the light one in the page template and
the 17 pages, and a Dark column to the style guide's color table.

Light colors are unchanged. The SVG figures follow in the next commit; the
blog page's inline strokes, the dinosaur game and the social card are left
as they are.

🤖 Generated with Claude Code (Sonnet 5.5) 🦊

* feat(website): give the five SVG figures a dark scheme

Pages load the figures with <img>, so page CSS cannot reach inside them.
Each figure now carries its own @media (prefers-color-scheme: dark) block
of attribute-selector overrides that map every light color to a Catppuccin
Mocha color, with one shared map across all five. No markup, labels,
shapes or positions change, and nothing uses !important.

Four figures also paint a mantle canvas so "Open figure" works on its own;
analyst-thinking.svg stays transparent, since it sits on the page rather
than in a figure box.

🤖 Generated with Claude Code (Sonnet 5.5) 🦊

* chore(website): refresh translation source references

The theme-color tags move the page lines that the catalogs cite, so
python3 scripts/website.py translations extract rewrites the source
references in messages.pot and the 18 PO files. No message text changes.
The same run moves the "Main navigation" entry to its new position in each
catalog.

🤖 Generated with Claude Code (Sonnet 5.5) 🦊

* fix(website): keep inline step highlights inline

The full-width band for the active step now applies only to code-step
blocks. The inline parameter highlights in the dx-ball and th04
signatures stay inline again.

🤖 Generated with Claude Code (Opus 5.5) 🦊

* test(website): check every page offers light and dark theme colors

Each authored reading page, and its built copy in every language,
must carry one theme-color tag for light and one for dark. The
stylesheet must keep its dark color scheme block. On the commit before
dark mode, this test fails on every page.

🤖 Generated with Claude Code (Opus 5.5) 🦊

* fix(website): draw the dinosaur game in the page colors

In dark mode the game box turned dark, but the game still drew with
its light colors, so the dinosaur, cacti and text fell to about 2:1
contrast. The canvas now reads five colors from CSS variables on
.dino-stage. Light values are the old ones, so light mode draws the
same pixels. Dark values are Catppuccin Mocha: 8.3:1 for the
dinosaur, 7.9:1 for cacti and text, 7.6:1 for the crash color.

The moved lines in dino-demo.js shift the translation catalog
references, so the catalogs are refreshed too (reference comments
only).

🤖 Generated with Claude Code (Opus 5.5) 🦊

* fix(website): recolor the Touhou flywheel arrows in dark mode

The inline flywheel SVG on the Touhou article hard-codes its stroke
colors, so on the dark page its connectors fell to about 2:1. Two
dark-only rules map those strokes to the page accent and muted colors
(7.8:1 and 7.4:1). Light mode is unchanged.

🤖 Generated with Claude Code (Opus 5.5) 🦊

* fix(website): redraw the dinosaur game when the system theme changes

The canvas reads its colors only when it draws, so an idle, paused or
crashed game kept the old palette after a theme switch. Each demo now
redraws on a prefers-color-scheme change.

The added lines shift the translation catalog references, so the
catalogs are refreshed too (reference comments only).

🤖 Generated with Claude Code (Opus 5.5) 🦊

---------

Co-authored-by: Claude Sonnet 5.5 <sonnet@cassie-pc>
Co-authored-by: Claude Opus 5.5 <opus@cassie-pc>
2026-10-12 03:17:49 +08:00
e59db2f5de fix(session): verify retained client liveness on open fast path
Verify retained provider operation health before reusing the same target and profile. Retire failed Hopper clients through existing owned cleanup, preserve healthy reuse and cancellation, and start replacement children lazily on the next query.

Refs #1719. Actual headless Linux Hopper child-death/reopen recovery and 85 related tests passed against the current-main merge tree; Ghidra/IDA liveness and the historical snapshot report remain outside this verification.

Co-authored-by: sx4im <sx4im@users.noreply.github.com>
Co-authored-by: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
2026-10-12 03:16:13 +08:00
Lluís Ariño d802304c54 fix(install): describe automatic setup and guard truncated downloads (#1902)
* fix(install): describe automatic setup and guard truncated downloads

The help text said the installer only installs the CLI and that
`rea setup` must be run separately, but the installer starts
`rea setup` interactively whenever a terminal is available. Describe
that behaviour and the --no-setup/--no-prompt opt-out.

Wrap the installer body in `main` and call it on the last line, so a
truncated `curl | bash` download fails to parse instead of executing a
partial script. Behaviour is otherwise unchanged.

Add an installer scenario that runs a copy truncated right after the
npm install line and requires that it prints nothing and never invokes
npm; it fails against the previous script.

Validation: bash -n, shellcheck 0.10.0, installScript boundary tests.

* fix(install): require the closing token before running main

Wrapping the installer in main() kept a truncated download from running
a partial body, but the last line was a bare `main "$@"`. If the piped
download stopped right after `main` (or `main `), bash saw a complete
command at EOF and ran main with no positional parameters. Under the
documented `curl ... | bash -s -- --dry-run` (or --version / --no-setup)
path that silently dropped the caller's flags, so a dry run could resolve
the latest release, run npm, and start setup.

The call now sits in a brace group:

  {
    main "$@"
    exit $?
  }

Bash does not run the group until it has read the closing brace, so
every truncation inside it is a syntax error and nothing executes; a
truncation before the group leaves only function definitions. A comment
in install.sh records why the bare call is not enough.

Validation: a new boundary test pipes install.sh to `bash -s --
--dry-run` truncated at every byte offset from the end of main() to EOF
and asserts that npm and the rea binary are never invoked; offsets
inside the group must exit non-zero with a bash parse error and no
stdout, offsets before it must print nothing, and the complete group
must finish the dry run. Reproduced the original bug by cutting the old
script after `main`: the dry run invoked npm install. `bash -n` and
shellcheck 0.11.0 are clean.

* fix(install): wrap the whole script in the truncation guard

The previous guard only wrapped the final `main "$@"` invocation, so the
preamble streamed on the `curl ... | bash` path before any incomplete
compound command was open. A download cut off right after the bytes
`set` reached EOF with a complete, argument-less `set`, which prints every
shell variable, so inherited tokens could reach stdout.

The brace group now opens on line 2, directly after the shebang, and
closes on the last line, enclosing `set -euo pipefail`, the constants, the
functions and the final `main "$@"` / `exit $?`. Bash must therefore read
the whole file before running anything; any earlier cut is a syntax error
at EOF. `set -euo pipefail` still applies inside the group (checked
manually for `false`, an unbound variable, and a failing function body),
and shellcheck 0.11.0 and `bash -n` are clean.

The truncation test now pipes every prefix of install.sh, from byte 0 to
EOF (about 6,100 cuts, run 16 at a time with a minimal environment that
includes a sentinel variable), into `bash -s -- --dry-run`. Before the
group opens it must exit quietly; inside the group it must fail with a
syntax error; in every case stdout stays empty and neither npm nor rea is
invoked. Only the complete script performs the dry run.
2026-10-12 02:47:31 +08:00
YsopwnableandKaoru0822 0f4992fb9e perf(ghidra): compile bundle activator with bridge scripts (#1931)
Include the no-op OSGi lifecycle class in the packaged source bundle so
Ghidra does not generate and compile an extra activator afterward.
Check the selected activator in the real packaged Windows verifier.

Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
2026-10-12 02:46:32 +08:00
Kaoru0822andClaude Opus 5.5 72489a9445 fix(javascript): report available parent result budget in coverage limits (#1915)
* fix(javascript): size the future static reserve by remaining sources

The parent reserved 80% of its result budget for future static facts
whenever any source remained, so one tiny later file could discard an
earlier file's completed semantic graph. Reserve at most one bounded
static checkpoint's retained size per remaining source, within the same
shared pool, so many remaining sources keep the previous protection.
Parent-budget rejections now report the effective admission budget and
explain that the CLI/MCP process heap, not max_heap_mb, bounds them.

Refs #1911

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(javascript): make parent budget remediation and its test runtime-aware

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(javascript): suggest a concrete parent heap size in remediation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(javascript): let parent budget rejections state their retained facts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 02:43:31 +08:00
morluto b6651cb99f fix(javascript): retain completed facts through cancellation (#1934) 2026-10-12 02:39:52 +08:00
morluto 0b2aa69531 Merge remote-tracking branch 'origin/main' into codex/pr-1899-remove-duplicate-schema-test 2026-10-12 02:38:57 +08:00
morluto b5b73019f9 test(web): remove duplicate path schema cases 2026-10-12 02:38:16 +08:00
Lluís Ariño d0edeec100 test(native): skip the inaccessible-directory diagnostic as root (#1900)
The artifact directory diagnostic makes a bundle member unreadable with
mode 000 and expects inventory_artifact to report its path and EACCES.
Root ignores the mode, so the read succeeds and the test fails when the
suite runs as uid 0 (for example in a container). Skip it there with the
same process.getuid?.() === 0 condition the DMG EACCES diagnostic uses.
2026-10-12 02:35:31 +08:00
morluto 3b490a743f test(apple): consolidate keyed archive integer verification (#1933) 2026-10-12 02:34:24 +08:00
morluto 3298219d8c docs(readme): remove CI badges from translations 2026-10-12 02:33:29 +08:00
morluto b07e54a10e docs(readme): remove CI status badge 2026-10-12 02:32:41 +08:00
fb43dd9716 fix(managed): honor metadata ExtraData before table decoding (#1893)
Co-authored-by: LouisChen <3361008+chqcjq@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-10-12 02:28:22 +08:00
Ysopwnablefactory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>Kaoru0822
0485cd3bce fix(javascript): preserve graphs within parent capacity (#1921)
Reserve the next sequential static checkpoint using its protocol size and
existing retained-expansion accounting instead of 80% of the parent budget.
Preserve total/live heap protections and explain parent admission failures
with effective capacity, retention estimates and usable retained facts.

Fixes #1911

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
2026-10-12 02:17:38 +08:00
pablodiazjorgeandClaude Opus 5.5 c32d84622f test(clients): verify native Claude Code integration on Windows (#1926)
The Claude Code client lane asserted POSIX, although nothing in it depends
on it. Remove the assertion, tell Windows users to select claude.exe when
the default command cannot be spawned (npm installs put only a claude.cmd
shim on PATH), and record 2.1.296 as verified on native Windows in
docs/testing.md.

Fixes #1923

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 02:14:55 +08:00
morluto 601814ed0e fix(hopper): preserve observed process failures across requests (#1927)
* fix(hopper): preserve observed process failures across requests

* test(hopper): consolidate retained cleanup and recover failed helper fixtures

* docs(hopper): clarify first-use demo prompt and startup recovery
2026-10-12 02:13:53 +08:00
Ysopwnablefactory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>Kaoru0822morluto
dfe31172ca fix(test): audit static Wasm and Harmony tool wording (#1917)
Account for explicit nonexecution wording in the existing tool-effects audit.
WABT validates and decompiles the module; Harmony projects inventory Evidence.
Retain declared effects and stale-exception checks.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-10-12 01:49:33 +08:00
morluto 6407718f30 test(managed): use the current attribute fixture contract 2026-10-12 01:42:02 +08:00
morluto f8513a42dc fix(javascript): keep TypeScript substitution out of runtime paths 2026-10-12 01:41:23 +08:00
LouisChenandLouisChen a95795c6ed fix(managed): resolve member ownership through pointer tables (#1886)
Co-authored-by: LouisChen <3361008+chqcjq@users.noreply.github.com>
2026-10-12 01:40:48 +08:00
morluto 369cd3dfdc fix(javascript): normalize package URLs before array selection (#1916) 2026-10-12 01:36:42 +08:00
morluto 2976fac30d test(architecture): consolidate import boundary verification 2026-10-12 01:31:33 +08:00
morluto f598bab488 fix(apple): preserve ARM64E X1 architecture identity 2026-10-12 01:31:33 +08:00
morluto bb508134ef fix(setup): verify independently selected skill destinations 2026-10-12 01:31:32 +08:00
morluto 1dfb933e47 fix(javascript): share TypeScript emitted import resolution 2026-10-12 01:31:32 +08:00
morluto 486b56724c fix(browser): compare only observed HTTP response facts 2026-10-12 01:31:23 +08:00
DeryFerd 499ac18011 fix(web): reject NUL bytes in web tool local path inputs
Four web tools accepted caller-selected local paths as plain strings, so
a NUL byte passed contract validation and reached filesystem calls. The
services only checked isAbsolute, and isAbsolute admits a NUL, so the
failure surfaced later as a raw ERR_INVALID_ARG_VALUE instead of a named
input constraint. Every other local-input tool already refuses NUL through
the shared local-path schema, and the existing OS-invalid-local-input
harness covers those but not these web tools.

inspect_web_network_capture.capture_path, export_web_scripts.capture_path
and output_directory, trace_web_source_location.manifest_path and
source_map.path, and trace_web_module_imports.manifest_path and
import_map.path now use localPathStringSchema. Each field already required
a nonempty string, so the advertised pattern and minLength stay the same
and only the NUL refusal is added.

Validation: a new schema test rejects NUL in all seven fields while
accepting ordinary absolute paths; the four tools are added to the
OS-invalid-local-input harness and reject NUL through the real advertised
MCP contracts; typecheck, oxlint, oxfmt, and toolSchemaValidity with a
regenerated catalog. Two webScriptExport boundary cases fail identically
with and without this change on this Windows host (symlink EPERM and
private-runtime-root authority), so they are environmental.
2026-10-11 23:32:52 +07:00
152 changed files with 36724 additions and 33230 deletions
+3 -2
View File
@@ -9,7 +9,6 @@
**See a feature you like. Understand how it works, down to the binary level.**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#what-you-can-analyze)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
@@ -245,7 +244,9 @@ Ghidra and IDA use your existing installations. See [provider setup](docs/instal
<summary><strong>Do I need to start Hopper first?</strong></summary>
REA starts Hopper when an operation needs it. On macOS, a first-run dialog may
ask you to choose demo mode or activate your license. See
ask you to choose demo mode or activate your license. Complete that prompt in the
same user session before your first CLI/MCP operation or unattended job. Open
Hopper manually if needed. See
[Hopper startup and troubleshooting](docs/installation.md#launcher-paths-and-troubleshooting).
</details>
-1
View File
@@ -9,7 +9,6 @@
**وجدت ميزة تعجبك؟ افهم طريقة عملها حتى مستوى الشيفرة الثنائية.**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**Eine Funktion gefällt dir? Verstehe, wie sie funktioniert – bis hinunter auf die Binärebene.**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**¿Ves una función que te gusta? Entiende cómo funciona, hasta el nivel binario.**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**قابلیتی دیده‌اید که دوستش دارید؟ سازوکارش را تا سطح باینری درک کنید.**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**Repérez une fonctionnalité qui vous plaît. Comprenez son fonctionnement, jusqu'au niveau du binaire.**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**Melihat fitur yang Anda sukai. Pahami cara kerjanya hingga ke tingkat biner.**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**Vedi una funzionalità che ti piace. Capisci come funziona, fino al livello binario.**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#cosa-puoi-analizzare)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**気に入った機能を見つけたら、その仕組みをバイナリのレベルまで理解する。**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**마음에 드는 기능을 발견했다면, 바이너리 수준까지 작동 원리를 이해하세요.**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**Widzisz funkcję, która Ci się podoba? Dowiedz się, jak działa, aż do poziomu kodu binarnego.**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**Viu uma funcionalidade de que gostou? Entenda como ela funciona, até o nível binário.**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**Нашли интересную функцию? Разберитесь, как она работает, вплоть до двоичного кода.**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**เห็นฟีเจอร์ที่ชอบแล้วอยากรู้ว่าทำงานอย่างไร? เข้าใจได้ลึกถึงระดับไบนารี**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**Beğendiğiniz bir özellik mi gördünüz? İkili kod düzeyine kadar nasıl çalıştığını anlayın.**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**Побачили цікаву функцію? Зрозумійте, як вона працює, аж до рівня двійкового коду.**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**Thấy một tính năng bạn thích? Hiểu cách nó hoạt động, đến tận mức mã nhị phân.**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**看到喜歡的功能,弄清它的工作原理,深入到二進位層面。**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
-1
View File
@@ -9,7 +9,6 @@
**看到喜欢的功能,弄清它的工作原理,深入到二进制层面。**
[![npm version](https://img.shields.io/npm/v/rea-agents?style=flat-square&color=cb3837)](https://www.npmjs.com/package/rea-agents)
[![CI](https://img.shields.io/github/actions/workflow/status/morluto/rea/ci.yml?branch=main&style=flat-square&label=CI)](https://github.com/morluto/rea/actions/workflows/ci.yml)
[![MCP tool catalog](https://img.shields.io/badge/MCP-tool_catalog-5c4ee5?style=flat-square)](docs/mcp-contracts.md#generated-catalog)
[![Node.js requirements](https://img.shields.io/badge/Node.js-requirements-339933?style=flat-square&logo=nodedotjs&logoColor=white)](#current-status)
[![skills.sh](https://skills.sh/b/morluto/rea?style=flat-square)](https://skills.sh/morluto/rea/reverse-engineer-anything)
@@ -0,0 +1,14 @@
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
// Compile the no-op activator with REA's scripts. Otherwise Ghidra generates
// one afterward and opens a second Java compiler and file manager.
public final class ReaGhidraBundleActivator implements BundleActivator {
@Override
public void start(BundleContext context) {
}
@Override
public void stop(BundleContext context) {
}
}
+18 -2
View File
@@ -352,6 +352,12 @@ Other integrations, including Qwen Code, use `~/.agents/skills`.
A mixed selection plans each distinct destination. Selecting the skill without a client uses the shared
directory. Setup leaves existing skill copies in other locations untouched.
`rea setup --skill-client claude_code --yes --json` refreshes and verifies the
selected skill destination independently of MCP registration selection. The
final `doctor.scope.skill_clients` records which skill destinations were
checked; `doctor.scope.clients` continues to describe required registrations.
An unselected shared skill does not affect a client-only refresh.
`doctor --skill --json` verifies the selected copies against the bundled
instructions and references. Consumers should use `identity.skill.state`,
`installed_version`, and `installed_tool_count` for skill readiness. The
@@ -561,8 +567,13 @@ need Xvfb, Python 3, X11 and XTEST; approved setup installs those dependencies
on supported distributions. Add the curl installer's reported executable
directory, commonly `~/.local/bin`, to your shell `PATH` if needed.
REA starts Hopper when needed. On macOS, its launcher can bring a window or
first-run dialog forward; choose demo mode or activate your existing license.
REA starts Hopper when needed. On macOS, complete its demo or license prompt in
the same user session before the first CLI/MCP operation or unattended job. Open
Hopper manually if needed; its launcher can also bring the dialog forward.
If startup reports `Cannot launch Hopper! Connection is invalid.` or waits for
bridge readiness, check Hopper for a pending demo, license, or loader dialog.
Complete the dialog and retry. If REA reports `cleanup_incomplete`, follow the
retained-resource guidance below before reopening the target.
Hopper serializes analysis requests. Cancelling a wait can leave provider work
running, which the session reports. Successful decompilation is cached until
a relevant rename or comment changes it.
@@ -591,6 +602,11 @@ if document closure is unconfirmed, REA retains the backing image and reports
MCP-exit behavior.
Startup deadlines report missing bridge readiness and preserve the launcher
outcome; a successful helper exit does not prove that a loader dialog completed.
If an owned provider process exits, request failures preserve its observed exit
code or signal and bounded output in `details.launcher`. An exit can precede
output-stream closure; `output_closed: false` keeps that uncertainty explicit.
Later requests retain the known exit instead of reducing it to socket loss.
An external GUI's helper exit does not establish that the GUI itself exited.
Cursor navigation returns the observed object start when Hopper snaps an interior
address; adjacent-object navigation rejects unmapped inputs and document ends.
Native API text rejects NUL characters and unpaired Unicode surrogates before
+16 -5
View File
@@ -159,9 +159,11 @@ completed partial Evidence. MCP failure details return
after recording succeeds, so `inspect_analysis_view` can open that analysis
directly without serializing the entire partial graph into the error response.
CLI failure output retains the complete partial Evidence.
Cancellation after source analysis begins likewise
retains completed facts; an SDK client may reject its cancelled request before
receiving that reply. On the same MCP connection, inspect the Evidence bundle
Cancellation after source analysis begins likewise retains completed facts,
including cancellation during analyzer cleanup, graph construction, or Evidence
sealing. REA finishes projecting those owned facts cooperatively to return partial
Evidence. An SDK client may reject its cancelled request before receiving that
reply. On the same MCP connection, inspect the Evidence bundle
and use the retained analysis ID with `inspect_analysis_view`. Owned analyzer
cleanup is verified before its private files are released. Cleanup uncertainty
is reported separately and retains ownership for retry.
@@ -231,6 +233,11 @@ unknown instead of silently treating them as absent or verified.
Plain `.ts` artifact sources use TypeScript syntax without JSX, including
angle-bracket type assertions. `.tsx` and `.jsx` retain JSX parsing.
Relative TypeScript imports can name their emitted `.js`, `.mjs`, or `.cjs`
counterparts while resolving to inventoried source files. This substitution
requires import or require semantics. Literal Electron preload, renderer, and
utility-process runtime paths retain the runtime filename selected by the caller.
Selected bounded text is then parsed as inert data to recover:
- `package.json` metadata and declared main or renderer entrypoints;
@@ -482,8 +489,12 @@ and one percent-decoding pass. CommonJS relative paths and legacy package main
fields retain literal filename punctuation. Exports targets must start with
`./` and exclude `.`, `..`, and `node_modules` path segments, including their
encoded forms, before URL normalization. Arrays skip invalid exports targets
in declared order; URL decoding and file lookup failures for a selected target
do not select a later entry. Rejected references retain the package metadata
in declared order, including URLs that escape the package root after normalization.
Selected package targets use the normalized URL path for lookup; tabs and
newlines in the URL text are removed by the URL parser. CommonJS package targets
reject encoded separators anywhere in the selected URL; ESM checks its pathname.
URL decoding and file lookup failures for a selected target do not select a
later entry. Rejected references retain the package metadata
path, original target, failed constraint, and importing source location.
HTML script references resolve to exact inventoried files after applying the
+18
View File
@@ -126,6 +126,24 @@ Member inspection binds build-local tokens, signatures, row offsets, method
bodies, and decoded relationships to that artifact and MVID. Missing or malformed
facts remain explicit in coverage and per-member status.
Metadata table streams may carry the CLR-compatible `ExtraData` extension
(`HeapSizes` flag `0x40`), which Microsoft readers honor although it is not
specified by ECMA-335. REA skips its fixed four-byte word after the row counts
before decoding table rows; the word's value is not a length. An incomplete
word is reported as a metadata coverage failure at its file offset, without
reading beyond the declared table stream.
For unoptimized `#-` metadata, nonempty `FieldPtr` and `MethodPtr` tables
translate TypeDef list positions to physical member definitions. REA resolves
these indirections for member ownership and local attribute-constructor types;
field and method tokens still identify the original definition rows.
`field_list` and `method_list` retain the metadata's list coordinates, which
refer to the pointer table when present rather than necessarily contiguous
definition rows. Malformed or ambiguous pointers leave the owner unknown with
partial coverage while preserving readable member and attribute facts.
The retained inverse indexes are admitted against the existing representation
budget before allocation.
`exported_types` reports ExportedType rows as declared. Facade assemblies such
as .NET `System.Runtime.dll` provide their types this way: `forwarder: true`
marks a type forwarder, and `implementation_token` names the AssemblyRef, File,
+13 -8
View File
@@ -139,8 +139,11 @@ directory, so default OS-home discovery remains unverified. Live model APIs and
native Windows are also unverified.
`verify:claude-client` requires installed Claude Code (verified with
`@anthropic-ai/claude-code@2.1.296`); select it with `REA_VERIFY_CLAUDE_COMMAND`.
The optional POSIX lane uses native `CLAUDE_CONFIG_DIR` discovery, an independent
`@anthropic-ai/claude-code@2.1.296` on POSIX and native Windows); select it
with `REA_VERIFY_CLAUDE_COMMAND`. On Windows, select
`claude.exe`: npm installs put only a `claude.cmd` shim on `PATH`, and the real
executable is under `node_modules/@anthropic-ai/claude-code/bin`.
The optional lane uses native `CLAUDE_CONFIG_DIR` discovery, an independent
Git workspace, user settings and default built-in tools. It preserves caller
preferences and backups, checks idempotent setup, waits through the native
`WaitForMcpServers` tool when discovery is pending, and validates the complete
@@ -149,8 +152,8 @@ native `Skill`, checks its full body and verifies named-schema JavaScript Eviden
for a Unicode path. Use `-- chat` for ordinary chat with REA enabled, or
`REA_VERIFY_RUNTIME_ROOT` for a production-only installed package. The local
Anthropic Messages/SSE fixture preserves native resource-hint envelopes in its
request artifacts. Usage is synthetic; live Anthropic API, native Windows and
bare-mode personal-skill activation remain unverified by this lane.
request artifacts. Usage is synthetic; live Anthropic API and bare-mode
personal-skill activation remain unverified by this lane.
`verify:copilot-client` requires installed GitHub Copilot CLI (verified with
`@github/copilot@1.0.95`); select it with `REA_VERIFY_COPILOT_COMMAND`.
@@ -279,10 +282,12 @@ establish live DeepSeek API or native Windows coverage. Receipts include
request artifacts, result digests and owned-process lineage.
Full E2E tests invoke the production command dispatcher and real providers,
without fake launchers, runners or responses. `verify:keyed-archive` writes an
actual Foundation binary archive, runs the CLI and a separate stdio MCP
subprocess, checks parity and pagination, rejects an escaping path and checks
an XML graph golden. `verify:asset-catalog` compiles source-owned colors with
without fake launchers, runners or responses. `verify:keyed-archive` writes
Foundation binary, XML, and integer archives using one run-owned Swift module
cache. It checks CLI and separate stdio MCP parity, pagination, escaping-path
rejection, an XML graph golden, and numeric meaning for safe controls, unsafe
integers, boxed numbers, and integral-valued reals. `verify:asset-catalog`
compiles source-owned colors with
`actool`, invokes real `assetutil`, then checks CLI/MCP results, exact catalog
digest, every raw metadata field, pagination and malformed input rejection.
Neither artifact workflow requires Hopper or launches it. Both run in macOS CI.
+104 -88
View File
@@ -1,4 +1,12 @@
#!/bin/bash
{
# Truncation guard: this brace group opens on line 2 and closes on the last
# line, so bash must read the entire file before it runs any command. On the
# `curl ... | bash` path, a download cut off anywhere before the final `}` is
# an unterminated compound command, which bash reports as a syntax error at
# EOF without running anything. Without the guard, a cut right after `set`
# would run the bare builtin and print every shell variable, and a cut right
# after `main` would run the installer without the caller's flags.
set -euo pipefail
PACKAGE="rea-agents"
@@ -21,104 +29,112 @@ usage() {
cat <<'EOF'
Usage: install.sh [--version VERSION] [--dry-run] [--no-setup] [--no-prompt] [--verbose]
Installs only the REA CLI. Run `rea setup` separately to configure Hopper and agents.
Installs the REA CLI, then starts `rea setup` interactively to configure Hopper
and agents when a terminal is available. Pass --no-setup (or --no-prompt) to
skip setup and run `rea setup` later.
EOF
}
while (($# > 0)); do
case "$1" in
--version)
(($# >= 2)) || fail "--version requires a value."
version="$2"
shift 2
;;
--dry-run)
dry_run=true
shift
;;
--no-setup|--no-prompt)
start_setup=false
shift
;;
--verbose)
verbose=true
shift
;;
--help|-h)
usage
exit 0
;;
*) fail "unknown option: $1" ;;
esac
done
main() {
while (($# > 0)); do
case "$1" in
--version)
(($# >= 2)) || fail "--version requires a value."
version="$2"
shift 2
;;
--dry-run)
dry_run=true
shift
;;
--no-setup|--no-prompt)
start_setup=false
shift
;;
--verbose)
verbose=true
shift
;;
--help|-h)
usage
exit 0
;;
*) fail "unknown option: $1" ;;
esac
done
if [[ "$verbose" == true ]]; then
set -x
fi
if [[ "$verbose" == true ]]; then
set -x
fi
platform="$(uname -s)"
[[ "$platform" == "Darwin" || "$platform" == "Linux" ]] || fail "REA supports macOS and selected 64-bit Linux distributions."
command -v curl >/dev/null 2>&1 || fail "curl is required. Install curl, then rerun this installer."
command -v node >/dev/null 2>&1 || fail "Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+ is required; install it from https://nodejs.org and retry."
command -v npm >/dev/null 2>&1 || fail "npm is required; install it with Node.js and retry."
platform="$(uname -s)"
[[ "$platform" == "Darwin" || "$platform" == "Linux" ]] || fail "REA supports macOS and selected 64-bit Linux distributions."
command -v curl >/dev/null 2>&1 || fail "curl is required. Install curl, then rerun this installer."
command -v node >/dev/null 2>&1 || fail "Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+ is required; install it from https://nodejs.org and retry."
command -v npm >/dev/null 2>&1 || fail "npm is required; install it with Node.js and retry."
node_version="$(node -p 'process.versions.node' 2>/dev/null || true)"
IFS=. read -r node_major node_minor _node_patch <<<"$node_version"
[[ "$node_major" =~ ^[0-9]+$ && "$node_minor" =~ ^[0-9]+$ ]] || fail "the active Node.js version could not be read. Check that node works and is on PATH, then retry."
if ! [[ "$_node_patch" =~ ^[0-9]+(\+[0-9A-Za-z.-]+)?$ ]] ||
! ((node_major == 22 && node_minor >= 19 || node_major == 24 && node_minor >= 11 || node_major >= 26)); then
fail "Node.js $node_version is unsupported; use Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+."
fi
node_version="$(node -p 'process.versions.node' 2>/dev/null || true)"
IFS=. read -r node_major node_minor _node_patch <<<"$node_version"
[[ "$node_major" =~ ^[0-9]+$ && "$node_minor" =~ ^[0-9]+$ ]] || fail "the active Node.js version could not be read. Check that node works and is on PATH, then retry."
if ! [[ "$_node_patch" =~ ^[0-9]+(\+[0-9A-Za-z.-]+)?$ ]] ||
! ((node_major == 22 && node_minor >= 19 || node_major == 24 && node_minor >= 11 || node_major >= 26)); then
fail "Node.js $node_version is unsupported; use Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+."
fi
if [[ -n "$version" ]]; then
[[ "$version" =~ ^${version_pattern}$ ]] || fail "version must be an exact semantic version."
else
release_json="$(curl -fsSL --proto '=https' --tlsv1.2 --retry 3 -H 'Accept: application/vnd.github+json' "https://api.github.com/repos/$REPOSITORY/releases/latest")" || fail "the latest REA release could not be resolved. Check network access or pass --version VERSION, then retry."
tag="$(printf '%s' "$release_json" | node -e 'let s="";process.stdin.on("data",c=>s+=c).on("end",()=>{const v=JSON.parse(s).tag_name;if(typeof v!=="string")process.exit(1);process.stdout.write(v)})' 2>/dev/null)" || fail "the release response was invalid. Retry later or pass --version VERSION."
[[ "$tag" =~ ^rea-agents-(${version_pattern})$ ]] || fail "the latest release tag was invalid. Retry later or pass --version VERSION."
version="${BASH_REMATCH[1]}"
fi
if [[ -n "$version" ]]; then
[[ "$version" =~ ^${version_pattern}$ ]] || fail "version must be an exact semantic version."
else
release_json="$(curl -fsSL --proto '=https' --tlsv1.2 --retry 3 -H 'Accept: application/vnd.github+json' "https://api.github.com/repos/$REPOSITORY/releases/latest")" || fail "the latest REA release could not be resolved. Check network access or pass --version VERSION, then retry."
tag="$(printf '%s' "$release_json" | node -e 'let s="";process.stdin.on("data",c=>s+=c).on("end",()=>{const v=JSON.parse(s).tag_name;if(typeof v!=="string")process.exit(1);process.stdout.write(v)})' 2>/dev/null)" || fail "the release response was invalid. Retry later or pass --version VERSION."
[[ "$tag" =~ ^rea-agents-(${version_pattern})$ ]] || fail "the latest release tag was invalid. Retry later or pass --version VERSION."
version="${BASH_REMATCH[1]}"
fi
# npm's exact-version resolver cleans build metadata from the requested version,
# so it may install the base release and make the post-install identity check fail.
if [[ "$version" =~ \+ ]]; then
fail "npm cannot install an exact version with build metadata. Pass a version without build metadata, then retry."
fi
# npm's exact-version resolver cleans build metadata from the requested version,
# so it may install the base release and make the post-install identity check fail.
if [[ "$version" =~ \+ ]]; then
fail "npm cannot install an exact version with build metadata. Pass a version without build metadata, then retry."
fi
install_args=(install --global)
if [[ "$platform" == "Linux" ]]; then
install_args+=(--prefix "$HOME/.local")
install_bin="$HOME/.local/bin/rea"
else
npm_prefix="$(npm prefix --global)" || fail "the npm global prefix could not be read. Repair the npm configuration, then retry."
install_bin="$npm_prefix/bin/rea"
fi
install_args+=("$PACKAGE@$version")
install_args=(install --global)
if [[ "$platform" == "Linux" ]]; then
install_args+=(--prefix "$HOME/.local")
install_bin="$HOME/.local/bin/rea"
else
npm_prefix="$(npm prefix --global)" || fail "the npm global prefix could not be read. Repair the npm configuration, then retry."
install_bin="$npm_prefix/bin/rea"
fi
install_args+=("$PACKAGE@$version")
printf 'REA install plan\n'
printf ' Version: %s\n' "$version"
printf ' Runtime: Node.js %s\n' "$node_version"
printf ' Command:'
printf ' %q' npm "${install_args[@]}"
printf '\n'
printf ' Binary: %s\n' "$install_bin"
printf ' Setup: %s\n' "$([[ "$start_setup" == true ]] && printf 'start when a terminal is available' || printf 'skipped')"
printf 'REA install plan\n'
printf ' Version: %s\n' "$version"
printf ' Runtime: Node.js %s\n' "$node_version"
printf ' Command:'
printf ' %q' npm "${install_args[@]}"
printf '\n'
printf ' Binary: %s\n' "$install_bin"
printf ' Setup: %s\n' "$([[ "$start_setup" == true ]] && printf 'start when a terminal is available' || printf 'skipped')"
if [[ "$dry_run" == true ]]; then
printf 'Dry run complete; no changes made.\n'
exit 0
fi
if [[ "$dry_run" == true ]]; then
printf 'Dry run complete; no changes made.\n'
exit 0
fi
printf 'Installing %s@%s...\n' "$PACKAGE" "$version"
npm "${install_args[@]}" || fail "npm could not install REA. Check registry access and npm permissions, then retry."
[[ -x "$install_bin" ]] || fail "npm completed without installing the rea command. Check the npm global bin directory and PATH, then retry."
installed_version="$("$install_bin" --version 2>/dev/null | tr -d '[:space:]')" || fail "the installed REA version could not be read. Reinstall the requested version, then retry."
[[ "$installed_version" == "$version" ]] || fail "installed version $installed_version does not match $version. Reinstall the requested version, then retry."
printf 'Installing %s@%s...\n' "$PACKAGE" "$version"
npm "${install_args[@]}" || fail "npm could not install REA. Check registry access and npm permissions, then retry."
[[ -x "$install_bin" ]] || fail "npm completed without installing the rea command. Check the npm global bin directory and PATH, then retry."
installed_version="$("$install_bin" --version 2>/dev/null | tr -d '[:space:]')" || fail "the installed REA version could not be read. Reinstall the requested version, then retry."
[[ "$installed_version" == "$version" ]] || fail "installed version $installed_version does not match $version. Reinstall the requested version, then retry."
printf 'REA %s is installed.\n' "$version"
if [[ "$start_setup" == true && -r /dev/tty && -w /dev/tty && -t 1 ]]; then
printf 'Starting REA setup...\n'
"$install_bin" setup </dev/tty >/dev/tty
else
printf 'Run %s setup to configure Hopper and agents.\n' "$install_bin"
fi
printf 'REA %s is installed.\n' "$version"
if [[ "$start_setup" == true && -r /dev/tty && -w /dev/tty && -t 1 ]]; then
printf 'Starting REA setup...\n'
"$install_bin" setup </dev/tty >/dev/tty
else
printf 'Run %s setup to configure Hopper and agents.\n' "$install_bin"
fi
}
main "$@"
exit $?
}
+1
View File
@@ -51,6 +51,7 @@
"bridge/process/ProcessRunTokenReader.swift",
"bridge/process/ProcessRunTokenReaderMain.swift",
"bridge/ghidra/ReaGhidraBridge.java",
"bridge/ghidra/ReaGhidraBundleActivator.java",
"bridge/ghidra/ReaGhidraExtensions.java",
"bridge/ghidra/ReaGhidraPrepareCom.java",
"bridge/ghidra/ReaGhidraApplySeeds.java",
+16
View File
@@ -401,6 +401,22 @@ class WebsiteTranslationChecks(unittest.TestCase):
server.shutdown()
worker.join()
def test_every_reading_page_offers_light_and_dark_theme_colors(self):
site = ROOT / "website/_site"
english_pages = reading_pages(ROOT / "website/public")
self.assertTrue(english_pages)
for language in languages(ROOT):
code = language["code"]
for original in english_pages:
relative = original.relative_to(ROOT / "website/public")
for path in {original, site / relative if code == "en" else site / code / relative}:
with self.subTest(language=code, page=str(path.relative_to(ROOT))):
doc = Document(path.read_text())
media = sorted(node.attrs.get("media") for node in doc.nodes if node.tag == "meta" and node.attrs.get("name") == "theme-color")
self.assertEqual(media, ["(prefers-color-scheme: dark)", "(prefers-color-scheme: light)"])
styles = (ROOT / "website/public/assets/styles.css").read_text()
self.assertTrue("@media (prefers-color-scheme: dark)" in styles, "styles.css has no dark color scheme block")
if __name__ == "__main__":
unittest.main()
+6 -5
View File
@@ -13,10 +13,6 @@ import { exec } from "./lib/verify-package-core.mjs";
import { createVerifierRun, completeVerifierRun } from "./lib/verifier-run.mjs";
import { createAnthropicModelFixture } from "./verify/clients/anthropic-model-fixture.mjs";
assert(
process.platform !== "win32",
"Native Claude Code verifier requires POSIX; Windows is unverified",
);
const repo = fileURLToPath(new URL("..", import.meta.url));
const runtimeRoot = process.env.REA_VERIFY_RUNTIME_ROOT ?? repo;
const command = process.env.REA_VERIFY_CLAUDE_COMMAND ?? "claude";
@@ -46,8 +42,13 @@ try {
await exec(command, ["--version"], { env: environment, timeout: 30_000 })
).stdout.trim();
} catch (cause) {
// npm installs put only a claude.cmd shim on PATH, which Node does not spawn without a shell.
const windowsHint =
process.platform === "win32"
? " On Windows, select claude.exe; npm installs provide it under node_modules/@anthropic-ai/claude-code/bin."
: "";
throw new Error(
`Claude Code preflight failed for ${command}; install Claude Code or set REA_VERIFY_CLAUDE_COMMAND. ${String(cause)}`,
`Claude Code preflight failed for ${command}; install Claude Code or set REA_VERIFY_CLAUDE_COMMAND.${windowsHint} ${String(cause)}`,
);
}
const target = join(lab, "fixture α测试");
+18 -1
View File
@@ -14,7 +14,7 @@ import {
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { basename, dirname, join, resolve } from "node:path";
import { promisify } from "node:util";
import { fileURLToPath, pathToFileURL } from "node:url";
@@ -291,6 +291,23 @@ try {
await client.connect(transport);
await call("open_binary", { path: target });
await call("binary_overview", {});
const activators = (
await readdir(runtimeParent, { recursive: true })
).filter((path) => basename(path) === "ReaGhidraBundleActivator.class");
assert.equal(activators.length, 1);
const [activator] = activators;
assert.ok(activator !== undefined);
const bundleDirectory = dirname(join(runtimeParent, activator));
const manifest = await readFile(
join(bundleDirectory, "META-INF", "MANIFEST.MF"),
"utf8",
);
assert.match(manifest, /^Bundle-Activator: ReaGhidraBundleActivator\r?$/mu);
await assert.rejects(
readFile(join(bundleDirectory, "GeneratedActivator.class")),
{ code: "ENOENT" },
);
report.bundleActivator = "ReaGhidraBundleActivator";
assert.equal((await call("list_documents", {})).length, 1);
await call("list_names", {});
const procedures = await call("list_procedures", {});
+7 -1
View File
@@ -5,10 +5,16 @@ import { promisify } from "node:util";
const exec = promisify(execFile);
const packedHopperBridge = "package/bridge/hopper_bridge.py";
const packedGhidraBridge = "package/bridge/ghidra/ReaGhidraBridge.java";
const packedGhidraActivator =
"package/bridge/ghidra/ReaGhidraBundleActivator.java";
/** Check shipped bridge files; real-provider lanes verify runtime behavior. */
export async function verifyPackedBridge({ workspace, tarball, packedFiles }) {
for (const path of [packedHopperBridge, packedGhidraBridge]) {
for (const path of [
packedHopperBridge,
packedGhidraBridge,
packedGhidraActivator,
]) {
if (!packedFiles.includes(path)) throw new Error(`package omitted ${path}`);
}
await exec("tar", ["-xf", tarball, "-C", workspace]);
@@ -0,0 +1,147 @@
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { z } from "zod";
import { keyedArchiveResultSchema } from "../../../dist/domain/apple/keyedArchive.js";
const rowSchema = z.object({
container: z.enum(["roots", "objects"]),
root: z.string(),
objectId: z.number().int().nonnegative().optional(),
path: z.array(z.union([z.string(), z.number().int().nonnegative()])),
kind: z.enum(["integer", "real"]),
literal: z.string(),
});
const archiveSchema = z.object({
filename: z.string(),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
rows: z.array(rowSchema),
});
const oracleSchema = z.object({ xml: archiveSchema, binary: archiveSchema });
const formats = ["xml", "binary"];
const requiredRows = [
{ root: "unsafeSigned", kind: "integer", literal: "9007199254740993" },
{
root: "unsafeNegative",
kind: "integer",
literal: "-9223372036854775808",
},
{ root: "safeInteger", kind: "integer", literal: "9007199254740991" },
{ root: "safeNegative", kind: "integer", literal: "-42" },
{ root: "integralReal", kind: "real", literal: "9007199254740992" },
{
root: "boxedUnsigned",
kind: "integer",
literal: "9007199254740993",
container: "objects",
},
{
root: "boxedReal",
kind: "real",
literal: "9007199254740992",
container: "objects",
},
];
const valueAt = (value, path) => {
for (const key of path) {
if (value === null || typeof value !== "object") return undefined;
value = value[key];
}
return value;
};
const isUnsafeInteger = (row) =>
row.kind === "integer" &&
(BigInt(row.literal) > BigInt(Number.MAX_SAFE_INTEGER) ||
BigInt(row.literal) < BigInt(Number.MIN_SAFE_INTEGER));
/** Verify the actual Foundation output and the production CLI/MCP result. */
export async function verifyKeyedArchiveIntegerArchives(root) {
const oracle = oracleSchema.parse(
JSON.parse(await readFile(join(root, "oracle.json"), "utf8")),
);
const archives = [];
for (const format of formats) {
const archive = oracle[format];
for (const required of requiredRows) {
assert.ok(
archive.rows.some(
(row) =>
row.root === required.root &&
row.kind === required.kind &&
row.literal === required.literal &&
(required.container === undefined ||
row.container === required.container),
),
`${format} Foundation oracle omitted ${required.root} ${required.literal}`,
);
}
const archivePath = join(root, archive.filename);
const digest = createHash("sha256")
.update(await readFile(archivePath))
.digest("hex");
assert.equal(digest, archive.sha256, `${format} archive digest`);
archives.push({ format, archive, archivePath, digest });
}
return archives;
}
/** Check every oracle numeric slot, preserving object-table identity lookups. */
export function assertKeyedArchiveIntegerResult(
result,
format,
digest,
oracle,
) {
const parsed = keyedArchiveResultSchema.parse(result);
assert.equal(parsed.archive_sha256, digest);
assert.equal(parsed.target_sha256, digest);
assert.equal(
parsed.archive_format,
format === "xml" ? "xml-plist" : "binary-plist",
);
for (const row of oracle.rows) {
const unsafe = isUnsafeInteger(row);
const source =
row.container === "roots"
? parsed.roots
: parsed.objects.find((object) => object.id === row.objectId)?.value;
const value = valueAt(source, row.path);
assert.notEqual(
value,
undefined,
`${row.root} numeric slot remains present`,
);
if (unsafe) {
const exact =
typeof value === "object" &&
value !== null &&
value.$plist_type === "integer" &&
value.decimal === BigInt(row.literal).toString();
const disclosed = parsed.limitations.some(
(reason) =>
/integer|number/iu.test(reason) &&
/precision|exact range|rounded/iu.test(reason),
);
assert.ok(
exact || disclosed,
`${row.root} ${row.literal} must be exact or disclose numeric loss`,
);
} else {
assert.equal(
typeof value,
"number",
`${row.root} retains its numeric type`,
);
assert.equal(value, Number(row.literal), `${row.root} numeric value`);
}
}
return parsed;
}
+40 -22
View File
@@ -1,5 +1,5 @@
import { execFile, spawnSync } from "node:child_process";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { execFile } from "node:child_process";
import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -11,6 +11,10 @@ import {
artifactMcpResult,
withArtifactMcp,
} from "../../lib/artifact-e2e.mjs";
import {
assertKeyedArchiveIntegerResult,
verifyKeyedArchiveIntegerArchives,
} from "./keyed-archive-integers.mjs";
if (process.platform !== "darwin")
throw new Error(
@@ -170,26 +174,37 @@ try {
);
});
}
const numericTests = spawnSync(
"npm",
[
"run",
"test:focused",
"--",
"tests/boundary/filesystem/keyedArchiveNativeIntegers.test.ts",
],
{
cwd: fileURLToPath(new URL("../../../", import.meta.url)),
stdio: "inherit",
timeout: 240_000,
},
);
if (numericTests.error) throw numericTests.error;
assert.equal(
numericTests.status,
0,
"Native Foundation integer cases failed",
);
const integers = join(root, "integers");
await mkdir(integers);
await promisify(execFile)("/usr/bin/xcrun", [
"swift",
"-module-cache-path",
join(root, "modules"),
fileURLToPath(
new URL(
"../../../tests/conformance/native/keyed-archive-integers.swift",
import.meta.url,
),
),
integers,
]);
for (const fixture of await verifyKeyedArchiveIntegerArchives(integers)) {
const cliResult = assertKeyedArchiveIntegerResult(
await artifactCli("inspect-keyed-archive", fixture.archivePath),
fixture.format,
fixture.digest,
fixture.archive,
);
await withArtifactMcp(fixture.archivePath, async (client) => {
const mcpResult = assertKeyedArchiveIntegerResult(
await artifactMcpResult(client, "inspect_keyed_archive"),
fixture.format,
fixture.digest,
fixture.archive,
);
assert.deepEqual(mcpResult, cliResult);
});
}
report = {
ok: true,
mocked: false,
@@ -197,6 +212,9 @@ try {
stdio_mcp: true,
xml_golden: true,
uid_named_root: true,
numeric_formats: ["xml", "binary"],
numeric_cli: true,
numeric_stdio_mcp: true,
format: graph.archive_format,
objects: graph.total_objects,
references: graph.total_references,
+6 -8
View File
@@ -10,12 +10,12 @@ import type {
} from "../application/AnalysisProvider.js";
import {
createAnalysisExecution,
providerConfigurationRefusal,
type AnalysisExecution,
} from "../application/AnalysisProvider.js";
import type { AdbRequest } from "../domain/adb/adbDeviceAnalysis.js";
import {
AnalysisArtifactChangedError,
AnalysisCapabilityUnavailableError,
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
@@ -417,8 +417,8 @@ export class AdbProvider {
async inspectAvailability(
signal?: AbortSignal,
): Promise<ProviderAvailability> {
const selection = this.selection();
try {
const selection = this.selection();
await inspectAdbClient(selection, signal);
return {
status: "available",
@@ -555,21 +555,19 @@ export class AdbProvider {
const signal = options?.signal;
if (signal?.aborted === true)
return err(new AnalysisCancelledError(request.operation));
const selection = this.selection();
let selection: AdbBinarySelection;
let identity: AdbClientIdentity;
try {
selection = this.selection();
identity = await inspectAdbClient(selection, signal);
} catch (cause) {
if (cause instanceof AnalysisCancelledError) return err(cause);
if (cause instanceof AdbConfigurationFailure)
return err(
new AnalysisCapabilityUnavailableError(
providerConfigurationRefusal(
ADB_PROVIDER_IDENTITY.id,
request.operation,
typeof cause.diagnostics.remediation === "string"
? `${cause.message} ${cause.diagnostics.remediation}`
: cause.message,
{ cause },
cause,
),
);
return err(
+9 -9
View File
@@ -22,6 +22,7 @@ import type {
} from "../application/AnalysisProvider.js";
import {
createAnalysisExecution,
providerConfigurationRefusal,
type AnalysisExecution,
} from "../application/AnalysisProvider.js";
import type { ApktoolRequest } from "../domain/apktool/apktoolResourceAnalysis.js";
@@ -153,12 +154,13 @@ const runApktool = async (
invocation = apktoolInvocation(selection, arguments_, hostEnvironment);
} catch (cause) {
if (!(cause instanceof WindowsBatchCommandError)) throw cause;
const reason = `The apktool batch launcher cannot receive REA's decode paths through cmd.exe: ${cause.message}`;
return err(
new AnalysisCapabilityUnavailableError(
APKTOOL_PROVIDER_IDENTITY.id,
operation,
`The apktool batch launcher cannot receive REA's decode paths through cmd.exe: ${cause.message}`,
{ cause },
reason,
{ cause, userMessage: reason },
),
);
}
@@ -345,8 +347,8 @@ export class ApktoolProvider {
async #inspectAvailability(
signal: AbortSignal,
): Promise<ProviderAvailability> {
const selection = this.selection();
try {
const selection = this.selection();
await inspectApktoolClient(selection, signal, this.environment);
throwIfCancelled("inspect_apktool_client", signal);
return {
@@ -397,9 +399,10 @@ export class ApktoolProvider {
): Promise<Result<AnalysisExecution, AnalysisError>> {
if (signal?.aborted === true)
return err(new AnalysisCancelledError(request.operation));
const selection = this.selection();
let selection: ApktoolCommandSelection;
let identity: ApktoolClientIdentity;
try {
selection = this.selection();
identity = await inspectApktoolClient(
selection,
signal,
@@ -409,13 +412,10 @@ export class ApktoolProvider {
if (cause instanceof AnalysisCancelledError) return err(cause);
if (cause instanceof ApktoolConfigurationFailure)
return err(
new AnalysisCapabilityUnavailableError(
providerConfigurationRefusal(
APKTOOL_PROVIDER_IDENTITY.id,
request.operation,
typeof cause.diagnostics.remediation === "string"
? `${cause.message} ${cause.diagnostics.remediation}`
: cause.message,
{ cause },
cause,
),
);
return err(
+26
View File
@@ -5,6 +5,7 @@ import type { NativeToolName } from "../contracts/native/nativeToolContracts.js"
import type { ArtifactAnalysisOperation } from "../contracts/artifactToolContracts.js";
import type { ManagedToolName } from "../contracts/managed/managedToolContracts.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { Result } from "../domain/result.js";
@@ -210,6 +211,31 @@ export type ProviderAvailability =
readonly diagnostics: Readonly<Record<string, JsonValue>>;
};
/** A host tool configuration failure observed before any target work. */
export interface ProviderConfigurationFailure extends Error {
readonly diagnostics: Readonly<Record<string, JsonValue>>;
}
/**
* Refuse an operation because the host tool is misconfigured. The reason,
* not the generic target advice, tells the caller what to change.
*/
export const providerConfigurationRefusal = (
providerId: string,
operation: string,
failure: ProviderConfigurationFailure,
): AnalysisCapabilityUnavailableError => {
const remediation = failure.diagnostics.remediation;
const reason =
typeof remediation === "string"
? `${failure.message}. ${remediation}.`
: `${failure.message}.`;
return new AnalysisCapabilityUnavailableError(providerId, operation, reason, {
cause: failure,
userMessage: reason,
});
};
/** Provider-owned target support observation before profile resolution. */
export type ProviderTargetSupport =
| {
+36
View File
@@ -281,6 +281,42 @@ describe("doctor installation identity", () => {
});
describe("doctor scoped readiness", () => {
it("checks explicitly selected skill destinations independently of registrations", async () => {
const selected: (readonly string[] | undefined)[] = [];
const result = await runDoctor(
undefined,
host({
clientRegistrations: () => Promise.resolve([]),
installedSkillIdentity: (clients) => {
selected.push(clients);
return Promise.resolve({
version: "stale",
toolCount: 0,
canonical: false,
});
},
}),
{
clients: [],
skillClients: ["claude_code", "claude_code"],
skill: true,
},
);
expect(selected).toEqual([["claude_code"]]);
expect(result.scope).toMatchObject({
mode: "explicit",
clients: [],
skill_clients: ["claude_code"],
skill: true,
});
expect(result.healthy).toBe(false);
expect(result.scope_checks.map(({ name }) => name)).toEqual([
"node",
"skill:identity",
]);
});
it("scopes effective readiness to selected clients without hiding drift", async () => {
const registrations: readonly ClientRegistrationStatus[] = [
{
+4 -2
View File
@@ -120,6 +120,7 @@ export interface DoctorReport {
/** Caller-selected readiness boundary; omitted values retain audit semantics. */
export interface DoctorScope {
readonly clients?: readonly string[];
readonly skillClients?: readonly string[];
readonly providers?: readonly string[];
readonly skill?: boolean;
}
@@ -206,9 +207,10 @@ const collectDoctorIdentity = async (
const installationPaths = (await host.installationPaths?.()) ?? [];
const registrations = (await host.clientRegistrations?.()) ?? [];
const skillClientIds =
scope.mode === "audit-wide"
scope.skill_clients ??
(scope.mode === "audit-wide"
? registrations.map(({ client }) => client)
: scope.clients;
: scope.clients);
const installedSkillIdentity =
await host.installedSkillIdentity?.(skillClientIds);
const skillAligned = skillIdentityAligned(installedSkillIdentity);
+4
View File
@@ -14,6 +14,7 @@ import type {
export interface DoctorScopeReport {
readonly mode: "audit-wide" | "explicit";
readonly clients: readonly string[];
readonly skill_clients?: readonly string[];
readonly providers: readonly string[];
readonly skill: boolean;
readonly target: string | null;
@@ -40,6 +41,9 @@ export const normalizeDoctorScope = (
): DoctorScopeReport => ({
mode: requested === undefined ? "audit-wide" : "explicit",
clients: uniqueSorted(requested?.clients ?? []),
...(requested?.skillClients === undefined
? {}
: { skill_clients: uniqueSorted(requested.skillClients) }),
providers: uniqueSorted(requested?.providers ?? []),
skill: requested?.skill === true,
target: target ?? null,
@@ -18,6 +18,7 @@ import type {
ReferenceSourceRead,
} from "../reference/ReferenceSourceReaderTypes.js";
import { PARSEABLE_REFERENCE_SOURCE_LANGUAGES } from "./ReferenceSourceImportTypes.js";
import { typescriptEmittedSourceCandidates } from "./TypeScriptEmittedSourceCandidates.js";
export interface ParsedReferenceSourceEntries {
readonly entries: HistoricalSourceGraphInput["entries"];
@@ -99,22 +100,9 @@ const resolveInternalSpecifier = (
`${normalized}${suffix}`,
`${normalized}/index${suffix}`,
]);
// TypeScript source commonly names the extension emitted for NodeNext.
// Retain present runtime files first; substitute only a missing counterpart.
// Counterparts cover explicit filenames, not directory/index resolution.
if (/\.(?:ts|tsx|mts|cts)$/u.test(fromPath)) {
const sourceSuffixes = normalized.endsWith(".js")
? [".ts", ".tsx", ".d.ts"]
: normalized.endsWith(".mjs")
? [".mts", ".d.mts"]
: normalized.endsWith(".cjs")
? [".cts", ".d.cts"]
: normalized.endsWith(".jsx")
? [".tsx", ".d.ts"]
: [];
const stem = normalized.slice(0, -posix.extname(normalized).length);
candidates.push(...sourceSuffixes.map((suffix) => `${stem}${suffix}`));
}
candidates.push(...typescriptEmittedSourceCandidates(fromPath, normalized));
const match = lookupPath.resolveCandidates(candidates);
return match === undefined
? { to: normalized, resolution: "unresolved" }
+4
View File
@@ -159,6 +159,7 @@ export class FakeSetupHost implements SetupHost {
scope === undefined
? environmentHealthy
: (scope.clients?.length ?? 0) === 0 &&
(scope.skillClients?.length ?? 0) === 0 &&
(scope.providers?.length ?? 0) === 0 &&
scope.skill !== true
? true
@@ -169,6 +170,9 @@ export class FakeSetupHost implements SetupHost {
scope: {
mode: scope === undefined ? "audit-wide" : "explicit",
clients: scope?.clients ?? [],
...(scope?.skillClients === undefined
? {}
: { skill_clients: scope.skillClients }),
providers: scope?.providers ?? [],
skill: scope?.skill === true,
target: null,
+1
View File
@@ -232,6 +232,7 @@ describe("setup scoped readiness", () => {
clients: ["codex"],
providers: [],
skill: true,
skillClients: ["codex"],
});
});
+9 -1
View File
@@ -125,7 +125,10 @@ const runSetupWorkflow = async (
: (options.clientIds ??
options.readinessScope?.clients ??
discovery.defaultClientIds);
let selectedSkillClientIds = options.skillClientIds ?? selectedClientIds;
let selectedSkillClientIds =
options.skillClientIds ??
options.readinessScope?.skillClients ??
selectedClientIds;
let skillNeedsInstall = await host.skillNeedsInstall(selectedSkillClientIds);
let skillSelected =
options.installSkill === true ||
@@ -220,6 +223,7 @@ const runSetupWorkflow = async (
installHopper: planDiscovery.installHopper,
installSkill,
skillSelected,
selectedSkillClientIds,
selectedClients: planned.selectedClients,
clientsToConfigure: planned.clientsToConfigure,
};
@@ -519,6 +523,7 @@ const resolvedReadinessScope = (
readonly selectedClients: readonly SetupClient[];
readonly installHopper: boolean;
readonly skillSelected?: boolean;
readonly selectedSkillClientIds: readonly string[];
},
): DoctorScope => ({
clients: selection.selectedClients.map(({ name }) => name),
@@ -526,6 +531,9 @@ const resolvedReadinessScope = (
? ["hopper"]
: (requested?.providers ?? []),
skill: selection.skillSelected === true || requested?.skill === true,
...(selection.skillSelected === true || requested?.skill === true
? { skillClients: selection.selectedSkillClientIds }
: {}),
});
const summarizeDoctor = (report: DoctorReport): SetupDoctorSummary => ({
@@ -0,0 +1,29 @@
/** Emitted NodeNext suffixes and the TypeScript source counterparts they name. */
const EMITTED_SUFFIXES: ReadonlyArray<
readonly [suffix: string, sourceSuffixes: readonly string[]]
> = [
[".js", [".ts", ".tsx", ".d.ts"]],
[".mjs", [".mts", ".d.mts"]],
[".cjs", [".cts", ".d.cts"]],
[".jsx", [".tsx", ".d.ts"]],
];
/**
* Return TypeScript source counterparts for an explicit emitted filename.
* Callers retain exact runtime-file precedence and must not use these for
* directory/index, URL, HTML, or package target resolution.
*/
export const typescriptEmittedSourceCandidates = (
sourcePath: string,
candidate: string,
): readonly string[] => {
if (!/\.(?:ts|tsx|mts|cts)$/u.test(sourcePath)) return [];
const emitted = EMITTED_SUFFIXES.find(([suffix]) =>
candidate.endsWith(suffix),
);
if (emitted === undefined) return [];
// Strip the matched suffix by length. posix.extname would miss dotfile
// names such as ".js", whose whole basename is the emitted suffix itself.
const stem = candidate.slice(0, candidate.length - emitted[0].length);
return emitted[1].map((suffix) => `${stem}${suffix}`);
};
+62 -6
View File
@@ -98,6 +98,30 @@ export class BinarySession
this.#providerRouter = providerRouter;
}
/**
* Fast-path liveness gate (#1719): short-circuit only when the retained
* client is genuinely alive. The probe reads the child's operation health
* rather than the composite's unconditionally-ok `health`, so a dead child
* falls through and a real client is started; an aborted caller leaves the
* session untouched. Returns the fast-path result, or undefined to fall
* through to the slow path.
*/
async #tryRetainedFastPath(
retained: SessionBinding,
target: BinaryTarget,
options: Pick<BinarySessionOpenOptions, "signal" | "snapshot">,
): Promise<Result<BinaryTarget, AnalysisError> | undefined> {
const live = await this.#retainedClientLive(retained.client, options);
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
if (!live) return undefined;
if (options.snapshot !== undefined) {
const imported = this.importAnalysisSnapshot(options.snapshot);
if (!imported.ok) return imported;
}
return ok(target);
}
/** Identify the provider producing evidence for this session. */
providerIdentity(operation?: AnalysisOperation): ProviderIdentity {
const route = this.#currentRoute();
@@ -247,12 +271,14 @@ export class BinarySession
if (!pendingClosed.ok) return pendingClosed;
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
if (sameTarget && sameProfile) {
if (options.snapshot !== undefined) {
const imported = this.importAnalysisSnapshot(options.snapshot);
if (!imported.ok) return imported;
}
return ok(target);
const retained = sameTarget && sameProfile ? this.#active : undefined;
if (retained !== undefined) {
const fastPath = await this.#tryRetainedFastPath(
retained,
target,
options,
);
if (fastPath !== undefined) return fastPath;
}
const previous = this.#active;
this.#active = undefined;
@@ -703,6 +729,36 @@ export class BinarySession
);
}
/**
* Probe whether a retained provider client is still live.
*
* On production routes the client is a CompositeProvider whose `health`
* answers unconditionally ok without touching a child, so `health` alone
* cannot see a dead child. `operationHealthSnapshot` reaches the
* instantiated children instead. Only the known-live states allow the
* fast path: `exited`/`unreachable` are dead, `unknown` is never
* evidence of health (it is what a recorded but uncharacterized failure
* reports), and `not_started` is a startup that never completed — in the
* Hopper timeout case the client holds retained resources that block the
* next `start()` until `close()` retries cleanup, so treating it as live
* would skip the retire path and hand the wedged client to subsequent
* analysis. The gate fails closed: without a snapshot signal, fall back
* to the `health` admission probe.
*/
async #retainedClientLive(
client: AnalysisClient,
options: Pick<BinarySessionOpenOptions, "signal">,
): Promise<boolean> {
const snapshot = client.operationHealthSnapshot?.();
if (snapshot !== undefined)
return snapshot.state === "idle" || snapshot.state === "busy";
try {
return (await client.execute("health", {}, options)).ok;
} catch {
return false;
}
}
async #restore(
previous: SessionBinding | undefined,
): Promise<Result<null, AnalysisError>> {
@@ -0,0 +1,338 @@
import { describe, expect, it } from "vitest";
import {
createAnalysisExecution,
type AnalysisClient,
type AnalysisOperation,
type AnalysisProvider,
type AnalysisProviderCandidate,
type CapabilityDescriptor,
type ProviderAvailability,
type ProviderIdentity,
type ProviderTargetSupport,
} from "../AnalysisProvider.js";
import { createAnalysisProfile } from "../../domain/analysisProfile.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import type { ProviderOperationHealth } from "../../domain/providerOperationHealth.js";
import { err, ok } from "../../domain/result.js";
import { InvestigationRecords } from "../investigation/InvestigationRecords.js";
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
import { BinarySession } from "./BinarySession.js";
import { SessionProviderRouter } from "./SessionProviderRouter.js";
/**
* Regression coverage for https://github.com/morluto/rea/issues/1719:
* `BinarySession#open` must not short-circuit on the `sameTarget &&
* sameProfile` fast path when the retained provider client is dead. It must
* start a fresh client instead.
*
* The fixtures are production-composed: a deep provider plus an auxiliary
* provider, so `SessionProviderRouter` wraps them in a real
* `CompositeProvider` exactly like `src/composition/binary.ts` does for the
* CLI/MCP runtime. The composite's `health` answers unconditionally ok
* without touching a child, so a probe that only calls `health` cannot see a
* dead child — the liveness signal must reach the actual child through
* `operationHealthSnapshot`, the way `HopperClient.operationHealth` reports a
* recorded process exit.
*/
describe("BinarySession open liveness", () => {
it("reuses the retained client while the child stays live", async () => {
const { session, deep } = openSession();
expect((await session.open(process.execPath)).ok).toBe(true);
// Instantiate the deep child inside the composite, like a real query would.
expect((await session.execute("address_name", {})).ok).toBe(true);
expect(deep.created).toHaveLength(1);
const second = await session.open(process.execPath);
expect(second.ok).toBe(true);
// Still the same composite and child: nothing was retired or recreated.
expect(deep.created).toHaveLength(1);
expect(deep.created[0]?.closeCalled).toBe(false);
expect((await session.execute("address_name", {})).ok).toBe(true);
expect(deep.created).toHaveLength(1);
});
it("starts a fresh client when the retained child died", async () => {
const { session, deep } = openSession();
expect((await session.open(process.execPath)).ok).toBe(true);
expect((await session.execute("address_name", {})).ok).toBe(true);
expect(deep.created).toHaveLength(1);
// Kill the provider process out from under the session, then re-open
// the same target: the session must not short-circuit on the dead
// child — it must retire it and start a real one.
const dead = deep.created[0];
dead?.kill();
const second = await session.open(process.execPath);
expect(second.ok).toBe(true);
// The dead binding was retired, not retained.
expect(dead?.closeCalled).toBe(true);
// The next query runs against a freshly created child, not the dead one.
expect((await session.execute("address_name", {})).ok).toBe(true);
expect(deep.created).toHaveLength(2);
});
it("treats an uncharacterized operation failure as dead", async () => {
// A recorded failure the provider could not characterize ("unknown",
// e.g. a Hopper spawn failure with no observed exit code) is never
// evidence of health: the gate fails closed.
const { session, deep } = openSession();
expect((await session.open(process.execPath)).ok).toBe(true);
expect((await session.execute("address_name", {})).ok).toBe(true);
expect(deep.created).toHaveLength(1);
const dead = deep.created[0];
dead?.kill("unknown");
const second = await session.open(process.execPath);
expect(second.ok).toBe(true);
expect(dead?.closeCalled).toBe(true);
expect((await session.execute("address_name", {})).ok).toBe(true);
expect(deep.created).toHaveLength(2);
});
it("retires a retained client whose startup never completed", async () => {
// A Hopper startup timeout leaves the operation-health snapshot in
// "not_started" while the retained resources block the next start()
// until close() retries cleanup. Classifying that state as live would return success
// without entering the retire path, so subsequent analysis still hits
// the wedged client.
const { session, deep } = openSession();
expect((await session.open(process.execPath)).ok).toBe(true);
expect((await session.execute("address_name", {})).ok).toBe(true);
expect(deep.created).toHaveLength(1);
const wedged = deep.created[0];
wedged?.kill("not_started");
const second = await session.open(process.execPath);
expect(second.ok).toBe(true);
// The wedged binding was retired (close ran, so cleanup is retried),
// not reused.
expect(wedged?.closeCalled).toBe(true);
// The next query runs against a freshly created child, not the wedged one.
expect((await session.execute("address_name", {})).ok).toBe(true);
expect(deep.created).toHaveLength(2);
});
it("falls back to the health probe when the child reports no operation health", async () => {
// Without an operation-health hook there is no child-liveness signal,
// so the probe keeps the previous `health` admission behavior.
const { session, deep } = openSession({ operationHealth: false });
expect((await session.open(process.execPath)).ok).toBe(true);
expect((await session.execute("address_name", {})).ok).toBe(true);
expect(deep.created).toHaveLength(1);
const second = await session.open(process.execPath);
expect(second.ok).toBe(true);
// The composite's `health` answers ok, so the live client is reused.
expect(deep.created).toHaveLength(1);
expect(deep.created[0]?.closeCalled).toBe(false);
});
it("reports cancellation without touching the session when aborted mid-probe", async () => {
const { session, deep, onProbe } = openSession();
expect((await session.open(process.execPath)).ok).toBe(true);
expect((await session.execute("address_name", {})).ok).toBe(true);
const controller = new AbortController();
// Fire the abort while the fast-path liveness probe is in flight: the
// hook runs synchronously inside the snapshot read, so the abort lands
// after the probe started but before the fast-path decision completes.
let fired = false;
onProbe(() => {
if (!fired) {
fired = true;
controller.abort();
}
});
const cancelled = await session.open(process.execPath, {
signal: controller.signal,
});
expect(cancelled).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
// The dead-or-live question is moot: the session must be untouched.
expect(deep.created).toHaveLength(1);
expect(deep.created[0]?.closeCalled).toBe(false);
const reopened = await session.open(process.execPath);
expect(reopened.ok).toBe(true);
expect(deep.created).toHaveLength(1);
});
});
interface KillableChild extends AnalysisClient {
kill(state?: "exited" | "unreachable" | "unknown" | "not_started"): void;
closeCalled: boolean;
}
const deepIdentity: ProviderIdentity = {
id: "liveness-deep",
name: "Liveness deep provider",
version: "1",
};
const auxIdentity: ProviderIdentity = {
id: "liveness-aux",
name: "Liveness auxiliary provider",
version: "1",
};
const capability = (
identity: ProviderIdentity,
operation: Exclude<AnalysisOperation, "health">,
): CapabilityDescriptor => ({
provider: identity,
operation,
available: true,
reason: null,
effects: {
mutatesArtifact: false,
launchesProcess: false,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
changesPermissions: false,
requiresRoot: false,
},
limitations: [],
});
const openSession = (
options: { operationHealth?: boolean } = {},
): {
session: BinarySession;
deep: { created: KillableChild[] };
onProbe: (hook: () => void) => void;
} => {
const { provider, created, onProbe } = killableDeepProvider(options);
// Mirror the production composition: a deep provider plus auxiliary
// providers, so the route wraps them in a real CompositeProvider (whose
// trivially-ok `health` must not mask a dead child).
const aux: AnalysisProvider = {
identity: () => auxIdentity,
capabilities: () => [],
createClient: (): AnalysisClient => ({
execute: (operation) =>
Promise.resolve(
ok(createAnalysisExecution(`aux:${operation}`, auxIdentity)),
),
close: () => Promise.resolve(ok(null)),
}),
};
const session = new BinarySession(
SessionProviderRouter.selectable(new AnalysisProviderRegistry([provider]), [
aux,
]),
new InvestigationRecords(),
);
return { session, deep: { created }, onProbe };
};
const killableDeepProvider = (options: {
operationHealth?: boolean;
}): {
provider: AnalysisProviderCandidate;
created: KillableChild[];
onProbe: (hook: () => void) => void;
} => {
const created: KillableChild[] = [];
let probeHook: (() => void) | undefined;
const withOperationHealth = options.operationHealth !== false;
const provider: AnalysisProviderCandidate = {
identity: () => deepIdentity,
capabilities: () => [capability(deepIdentity, "address_name")],
inspectAvailability: (): ProviderAvailability => ({
status: "available",
code: null,
reason: null,
diagnostics: {},
}),
inspectTargetSupport: (): ProviderTargetSupport => ({
status: "supported",
code: null,
reason: null,
diagnostics: {},
}),
resolveAnalysisProfile: () =>
Promise.resolve(
ok({
profile: createAnalysisProfile(
{ id: deepIdentity.id, name: deepIdentity.name, version: "1" },
{ fixture: "liveness" },
),
}),
),
createClient: (): KillableChild => {
let alive = true;
let closeCalled = false;
let deadState: "exited" | "unreachable" | "unknown" | "not_started" =
"exited";
const client: KillableChild = {
execute: (operation) => {
return alive
? Promise.resolve(
ok(
createAnalysisExecution(
operation === "health" ? null : `liveness:${operation}`,
deepIdentity,
),
),
)
: Promise.resolve(
err(
new ProviderAdapterError(deepIdentity.id, operation, {
diagnostics: { reason: "process_killed" },
}),
),
);
},
// Genuine child-liveness signal, like HopperClient.operationHealth:
// a recorded process exit stays visible after the kill.
...(withOperationHealth
? {
operationHealthSnapshot: (): ProviderOperationHealth => {
probeHook?.();
return {
state: alive ? "idle" : deadState,
stage: alive ? null : "connection",
retryAction: alive ? null : "restart_provider",
exitCode: alive ? null : 1,
requests: [],
};
},
}
: {}),
close: () => {
closeCalled = true;
return Promise.resolve(ok(null));
},
get closeCalled() {
return closeCalled;
},
kill: (
state:
| "exited"
| "unreachable"
| "unknown"
| "not_started" = "exited",
) => {
alive = false;
deadState = state;
},
};
created.push(client);
return client;
},
};
return {
provider,
created,
onProbe: (hook: () => void) => {
probeHook = hook;
},
};
};
@@ -4,6 +4,7 @@ import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
import type { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import {
analyzeJavaScriptApplicationInputSchema,
type JavaScriptApplicationAnalysisResult,
parseOwnedJavaScriptApplicationAnalysisSteps,
} from "../../domain/javascript/javascriptApplicationAnalysis.js";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
@@ -20,7 +21,10 @@ import {
checkpointJavaScriptAnalysis,
completeJavaScriptAnalysisSteps,
} from "./JavaScriptAnalysisControl.js";
import { reconstructJavaScriptArtifact } from "./JavaScriptArtifactReconstruction.js";
import {
reconstructJavaScriptArtifact,
type JavaScriptArtifactReconstructionResult,
} from "./JavaScriptArtifactReconstruction.js";
import { JAVASCRIPT_APPLICATION_PROVIDER } from "../InvestigationProviders.js";
const OPERATION = "analyze_javascript_application" as const;
@@ -45,6 +49,9 @@ export const analyzeJavaScriptApplicationValidated = async (
scope: ArtifactResourceScope,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
let reconstructed: JavaScriptArtifactReconstructionResult | undefined;
let result: JavaScriptApplicationAnalysisResult | undefined;
let evidence: Evidence | undefined;
try {
assertJavaScriptAnalysisActive(options.signal);
await options.progress?.report({
@@ -54,7 +61,7 @@ export const analyzeJavaScriptApplicationValidated = async (
message: "Inventorying and parsing application artifacts",
});
await checkpointJavaScriptAnalysis(options.signal);
const reconstructed = await reconstructJavaScriptArtifact(
reconstructed = await reconstructJavaScriptArtifact(
{
input_path: input.input_path,
format: input.format,
@@ -78,7 +85,7 @@ export const analyzeJavaScriptApplicationValidated = async (
message: "Validating result metadata and cross-graph bindings",
});
await checkpointJavaScriptAnalysis(options.signal);
const result = await completeJavaScriptAnalysisSteps(
result = await completeJavaScriptAnalysisSteps(
parseOwnedJavaScriptApplicationAnalysisSteps({
...application,
summary,
@@ -93,13 +100,12 @@ export const analyzeJavaScriptApplicationValidated = async (
message: "Creating and hashing application analysis Evidence",
});
await checkpointJavaScriptAnalysis(options.signal);
const evidence =
await createOwnedJavaScriptApplicationEvidenceCooperatively(
input,
result,
options.signal,
options.progress,
);
evidence = await createOwnedJavaScriptApplicationEvidenceCooperatively(
input,
result,
options.signal,
options.progress,
);
await checkpointJavaScriptAnalysis(options.signal);
await options.progress?.report({
phase: "analyze_javascript_application",
@@ -111,6 +117,38 @@ export const analyzeJavaScriptApplicationValidated = async (
assertJavaScriptAnalysisActive(options.signal);
return ok(evidence);
} catch (cause: unknown) {
if (
cause instanceof ArtifactReaderFailure &&
cause.reason === "cancelled" &&
reconstructed !== undefined
) {
try {
if (result === undefined) {
const { electron_summary: summary, ...application } = reconstructed;
result = await completeJavaScriptAnalysisSteps(
parseOwnedJavaScriptApplicationAnalysisSteps({
...application,
summary,
limitations: reconstructed.graph.limitations,
}),
);
}
evidence ??=
await createOwnedJavaScriptApplicationEvidenceCooperatively(
input,
result,
);
return err(
artifactFailureToOperationError(cause).retainPartialObservation(
evidence,
),
);
} catch (completionCause: unknown) {
// A validation or Evidence failure while finishing the partial result
// remains the primary failure instead of being hidden by cancellation.
cause = completionCause;
}
}
// Preserve execution constraints and their completed partial Evidence.
if (cause instanceof AnalysisError) return err(cause);
if (cause instanceof ArtifactReaderFailure)
@@ -1464,6 +1464,159 @@ describe("contextual JavaScript module identity", () => {
});
});
describe("TypeScript NodeNext emitted-extension resolution", () => {
const container = "container";
it.each([
["./dep.js", "src/dep.ts"],
["./ui/Button.js", "src/ui/Button.tsx"],
["./cfg.mjs", "src/cfg.mts"],
["./legacy.cjs", "src/legacy.cts"],
] as const)(
"resolves %s to its TypeScript source counterpart",
(specifier, target) => {
const files = fileMap([
file("src/main.ts", container),
file(target, container, "export const value = 1;"),
]);
expect(
resolve({
declaredPath: specifier,
sourcePath: "src/main.ts",
context: "module-specifier",
moduleKind: "import",
files,
}),
).toMatchObject({ resolution_status: "resolved", resolved_path: target });
},
);
it.each([
["./dep.js", "src/dep.d.ts"],
["./cfg.mjs", "src/cfg.d.mts"],
["./legacy.cjs", "src/legacy.d.cts"],
] as const)(
"resolves %s to a declaration counterpart",
(specifier, target) => {
const files = fileMap([
file("src/main.ts", container),
file(target, container, "export const value = 1;"),
]);
expect(
resolve({
declaredPath: specifier,
sourcePath: "src/main.ts",
context: "module-specifier",
moduleKind: "import",
files,
}),
).toMatchObject({ resolution_status: "resolved", resolved_path: target });
},
);
it("prefers a present runtime file and keeps the fallback off for JS callers", () => {
const files = fileMap([
file("src/main.ts", container),
file("src/dep.js", container),
file("src/dep.ts", container),
file("src/js-main.js", container),
]);
expect(
resolve({
declaredPath: "./dep.js",
sourcePath: "src/main.ts",
context: "module-specifier",
moduleKind: "import",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "src/dep.js",
});
expect(
resolve({
declaredPath: "./dep.js",
sourcePath: "src/js-main.js",
context: "module-specifier",
moduleKind: "import",
files: fileMap([
file("src/js-main.js", container),
file("src/dep.ts", container),
]),
}),
).toMatchObject({ resolution_status: "not-found", resolved_path: null });
});
it("does not apply the mapping to URL resources or package export targets", () => {
const urlFiles = fileMap([
file("src/main.ts", container),
file("src/asset.ts", container),
]);
expect(
resolve({
declaredPath: "asset.js",
sourcePath: "src/main.ts",
context: "url-reference",
files: urlFiles,
}),
).toMatchObject({ resolution_status: "not-found", resolved_path: null });
const packageFiles = fileMap([
file("src/main.ts", container),
file(
"src/node_modules/fixture/package.json",
container,
'{"exports":"./dep.js"}',
),
file("src/node_modules/fixture/dep.ts", container),
]);
expect(
resolve({
declaredPath: "fixture",
sourcePath: "src/main.ts",
context: "module-specifier",
moduleKind: "import",
files: packageFiles,
}),
).toMatchObject({ resolution_status: "not-found", resolved_path: null });
});
it("does not substitute source counterparts for directory or index resolution", () => {
const files = fileMap([
file("src/main.ts", container),
file("src/lib/index.ts", container),
]);
expect(
resolve({
declaredPath: "./lib.js",
sourcePath: "src/main.ts",
context: "module-specifier",
moduleKind: "import",
files,
}),
).toMatchObject({ resolution_status: "not-found", resolved_path: null });
});
it("resolves an emitted dotfile name within its own directory", () => {
const files = fileMap([
file("src/main.ts", container),
file("src/.ts", container),
]);
expect(
resolve({
declaredPath: "./.js",
sourcePath: "src/main.ts",
context: "module-specifier",
moduleKind: "import",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "src/.ts",
});
});
});
describe("url-reference JavaScript artifact path resolution", () => {
it.each([
"app%00.js.map",
@@ -19,6 +19,7 @@ import {
classifyPackageImportTargetString,
lookupExactPackageImport,
} from "../../domain/javascript/javascriptPackageImportAliases.js";
import { typescriptEmittedSourceCandidates } from "../TypeScriptEmittedSourceCandidates.js";
type ArtifactPathResolutionContext =
| "package-entrypoint"
@@ -59,6 +60,7 @@ export interface ResolveArtifactPathInput {
readonly context: ArtifactPathResolutionContext;
readonly files: ReadonlyMap<string, JavaScriptArtifactFile>;
readonly htmlBaseHref?: string | null;
/** Import/require semantics; runtime resource paths omit this provenance. */
readonly moduleKind?: "import" | "require";
}
@@ -73,6 +75,21 @@ const EXTENSIONS = [
".node",
];
// A private URL namespace for logical artifact paths, including root packages.
// Encode inventory segments so filename punctuation remains literal in the base.
const PACKAGE_ARTIFACT_ROOT_URL = new URL("file:///rea-artifact/");
const packageMetadataUrl = (path: string): URL =>
new URL(
path.split("/").map(encodeURIComponent).join("/"),
PACKAGE_ARTIFACT_ROOT_URL,
);
interface PackageFileTarget {
readonly value: string;
/** Normalized URL retained until loader-specific validation and file lookup. */
readonly url: URL;
}
type CandidateResolution =
| {
readonly resolvedPath: string;
@@ -128,7 +145,16 @@ const resolvePath = (input: ResolveArtifactPathInput): CandidateResolution => {
`The exact HTML resource ${confined} was not found among the selected application files.`,
])
);
return resolveCandidate(input, confined, new Set());
return resolveCandidate(
input,
confined,
new Set(),
input.context === "module-specifier" &&
input.moduleKind !== undefined &&
(input.declaredPath.startsWith(".") || input.declaredPath.startsWith("/"))
? typescriptEmittedSourceCandidates(input.sourcePath, confined)
: [],
);
};
const rejectDeclaration = (declared: string): CandidateResolution | null => {
@@ -304,7 +330,11 @@ const resolvePackageImportAlias = (
return unresolvedCandidate("external", [
`Wildcard package import aliases remain unresolved; package metadata ${metadata.path} has no exact imports key ${specifier}.`,
]);
const selected = selectPackageImportTarget(lookup.target, input.moduleKind);
const selected = selectPackageImportTarget(
lookup.target,
input.moduleKind,
metadata.path,
);
if (selected.status === "rejected")
return unresolvedCandidate("rejected", [
`Package metadata ${metadata.path}: ${selected.limitation}`,
@@ -325,14 +355,15 @@ const resolvePackageImportAlias = (
: `External-package import targets remain unresolved; package metadata ${metadata.path} maps ${specifier} to ${JSON.stringify(target.target)}.`,
]);
}
return resolveExportTarget(input, metadata.path, selected.value, "imports");
return resolveExportTarget(input, metadata.path, selected, "imports");
};
const selectPackageImportTarget = (
value: unknown,
moduleKind: ResolveArtifactPathInput["moduleKind"],
packagePath: string,
):
| { readonly status: "value"; readonly value: string }
| ({ readonly status: "value" } & PackageFileTarget)
| { readonly status: "non-relative"; readonly value: string }
| { readonly status: "blocked"; readonly cause: PackageTargetBlockCause }
| { readonly status: "unmatched"; readonly declared: readonly string[] }
@@ -340,6 +371,7 @@ const selectPackageImportTarget = (
const selected = selectExportTarget(
value,
packageExportConditions(moduleKind),
packageMetadataUrl(packagePath),
"imports",
);
if (selected.kind === "invalid" || selected.kind === "invalid-config")
@@ -353,7 +385,11 @@ const selectPackageImportTarget = (
return { status: "blocked", cause: selected.cause };
if (selected.kind === "non-relative")
return { status: "non-relative", value: selected.value };
return { status: "value", value: selected.value };
return {
status: "value",
value: selected.value,
url: selected.url,
};
};
/** Self references use the nearest package scope before dependency lookup. */
@@ -421,7 +457,12 @@ const resolvePackageExports = (
subpath: string,
rawExports: string | object,
): CandidateResolution => {
const exported = selectPackageExport(rawExports, subpath, input.moduleKind);
const exported = selectPackageExport(
rawExports,
subpath,
input.moduleKind,
packagePath,
);
if (exported.status === "rejected")
return unresolvedCandidate("rejected", [
`Package metadata ${packagePath}: ${exported.limitation}`,
@@ -434,25 +475,45 @@ const resolvePackageExports = (
return unresolvedCandidate("external", [
`Directory package metadata ${packagePath} blocks subpath ${subpath} with ${exported.cause === "null" ? "an explicit null exports target" : "an empty exports target array"}.`,
]);
return resolveExportTarget(input, packagePath, exported.value);
return resolveExportTarget(input, packagePath, exported);
};
/** An exports or import target is a URL naming one exact file for both Node loaders. */
const resolveExportTarget = (
input: ResolveArtifactPathInput,
packagePath: string,
target: string,
target: PackageFileTarget,
mapKind: "exports" | "imports" = "exports",
): CandidateResolution => {
const rejected = rejectDeclaration(target);
if (rejected !== null) return rejected;
const decoded = decodeModuleUrlPath(stripQueryAndFragment(target));
if (typeof decoded !== "string") return decoded;
const candidate = confineCandidate(relativeCandidate(packagePath, decoded));
if (typeof candidate !== "string") return candidate;
const withTargetSource = (
outcome: CandidateResolution,
): CandidateResolution => ({
...outcome,
limitations: outcome.limitations.map(
(reason) =>
`Package metadata ${packagePath}, ${mapKind} target ${JSON.stringify(target.value)}: ${reason}`,
),
});
// Node's CommonJS finalizer checks the serialized URL, including suffixes;
// its ESM finalizer checks only the pathname. Neither error retries arrays.
if (input.moduleKind === "require" && /%(?:2f|5c)/iu.test(target.url.href))
return withTargetSource(
unresolvedCandidate("rejected", [
"The selected package URL contains encoded separator bytes.",
]),
);
const encodedPath = target.url.pathname.slice(
PACKAGE_ARTIFACT_ROOT_URL.pathname.length,
);
const rejected = rejectDeclaration(encodedPath);
if (rejected !== null) return withTargetSource(rejected);
const decoded = decodeModuleUrlPath(encodedPath);
if (typeof decoded !== "string") return withTargetSource(decoded);
const candidate = confineCandidate(decoded);
if (typeof candidate !== "string") return withTargetSource(candidate);
return (
resolveFileCandidates(input, [candidate]) ??
exactPackageTargetNotFound(candidate, mapKind)
withTargetSource(exactPackageTargetNotFound(candidate, mapKind))
);
};
@@ -669,8 +730,12 @@ const resolveCandidate = (
input: ResolveArtifactPathInput,
candidate: string,
packageChain: ReadonlySet<string>,
emittedSourceCandidates: readonly string[] = [],
): CandidateResolution =>
resolveFileCandidates(input, fileCandidates(candidate)) ??
resolveFileCandidates(input, [
...fileCandidates(candidate),
...emittedSourceCandidates,
]) ??
resolveDirectory(
input,
candidate,
@@ -763,7 +828,7 @@ const indexCandidates = (candidate: string): readonly string[] =>
type PackageTargetBlockCause = "null" | "empty-array";
type PackageExportOutcome =
| { readonly status: "value"; readonly value: string }
| ({ readonly status: "value" } & PackageFileTarget)
| { readonly status: "rejected"; readonly limitation: string }
| { readonly status: "blocked"; readonly cause: PackageTargetBlockCause }
| { readonly status: "unmatched"; readonly declared: readonly string[] };
@@ -773,6 +838,7 @@ const selectPackageExport = (
value: unknown,
subpath: string,
moduleKind: ResolveArtifactPathInput["moduleKind"],
packagePath: string,
): PackageExportOutcome => {
let target = value;
let declared: string[] = [];
@@ -799,6 +865,7 @@ const selectPackageExport = (
const selected = selectExportTarget(
target,
packageExportConditions(moduleKind),
packageMetadataUrl(packagePath),
);
if (selected.kind === "invalid" || selected.kind === "invalid-config")
return { status: "rejected", limitation: selected.limitation };
@@ -814,11 +881,15 @@ const selectPackageExport = (
status: "rejected",
limitation: `The package exports target ${JSON.stringify(selected.value)} must start with "./".`,
};
return { status: "value", value: selected.value };
return {
status: "value",
value: selected.value,
url: selected.url,
};
};
type ExportTargetOutcome =
| { readonly kind: "value"; readonly value: string }
| ({ readonly kind: "value" } & PackageFileTarget)
| { readonly kind: "non-relative"; readonly value: string }
| { readonly kind: "blocked"; readonly cause: PackageTargetBlockCause }
| { readonly kind: "unmatched"; readonly declared: readonly string[] }
@@ -853,6 +924,7 @@ const forbiddenExportSegment = (value: string): string | undefined =>
const selectStringPackageTarget = (
value: string,
packageUrl: URL,
mapKind: "exports" | "imports",
): ExportTargetOutcome => {
if (mapKind === "imports") {
@@ -867,18 +939,33 @@ const selectStringPackageTarget = (
} else if (!value.startsWith("./"))
return invalidExportTarget(value, 'must start with "./"', mapKind);
const forbidden = forbiddenExportSegment(value);
return forbidden === undefined
? { kind: "value", value }
: invalidExportTarget(
value,
`contains forbidden path segment ${JSON.stringify(forbidden)} before URL normalization`,
mapKind,
);
if (forbidden !== undefined)
return invalidExportTarget(
value,
`contains forbidden path segment ${JSON.stringify(forbidden)} before URL normalization`,
mapKind,
);
// Node constructs the URL before deciding whether this array entry is an
// invalid package target. Tabs/newlines and dot segments normalize here;
// percent decoding and existence checks belong after target selection.
const url = new URL(value, packageUrl);
if (!url.pathname.startsWith(new URL(".", packageUrl).pathname))
return invalidExportTarget(
value,
"escapes the package root after URL normalization",
mapKind,
);
return {
kind: "value",
value,
url,
};
};
const selectArrayPackageTarget = (
value: readonly unknown[],
conditions: ReadonlySet<string>,
packageUrl: URL,
mapKind: "exports" | "imports",
): ExportTargetOutcome => {
if (value.length === 0) return { kind: "blocked", cause: "empty-array" };
@@ -887,7 +974,7 @@ const selectArrayPackageTarget = (
| undefined;
const declared = new Set<string>();
for (const entry of value) {
const nested = selectExportTarget(entry, conditions, mapKind);
const nested = selectExportTarget(entry, conditions, packageUrl, mapKind);
// Node's array fallback catches invalid targets, not invalid configuration.
if (nested.kind === "invalid-config") return nested;
if (nested.kind === "unmatched") {
@@ -913,13 +1000,14 @@ const selectArrayPackageTarget = (
const selectExportTarget = (
value: unknown,
conditions: ReadonlySet<string>,
packageUrl: URL,
mapKind: "exports" | "imports" = "exports",
): ExportTargetOutcome => {
if (typeof value === "string")
return selectStringPackageTarget(value, mapKind);
return selectStringPackageTarget(value, packageUrl, mapKind);
if (value === null) return { kind: "blocked", cause: "null" };
if (Array.isArray(value))
return selectArrayPackageTarget(value, conditions, mapKind);
return selectArrayPackageTarget(value, conditions, packageUrl, mapKind);
if (typeof value !== "object")
return invalidExportTarget(
value,
@@ -938,7 +1026,7 @@ const selectExportTarget = (
for (const [condition, target] of Object.entries(value)) {
declared.add(condition);
if (!conditions.has(condition)) continue;
const nested = selectExportTarget(target, conditions, mapKind);
const nested = selectExportTarget(target, conditions, packageUrl, mapKind);
if (nested.kind !== "unmatched") return nested;
for (const name of nested.declared) declared.add(name);
}
@@ -1,5 +1,6 @@
import { constants } from "node:fs";
import { access, lstat, realpath } from "node:fs/promises";
import { setImmediate } from "node:timers/promises";
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
import {
@@ -13,6 +14,7 @@ import type { JavaScriptSemanticGraph } from "../../domain/javascript/javascript
import type { ElectronBoundarySummary } from "../../domain/javascript/javascriptApplicationAnalysis.js";
import { parseOwnedJavaScriptApplicationAnalysisSteps } from "../../domain/javascript/javascriptApplicationAnalysis.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { ArtifactOperationError } from "../../domain/artifactOperationError.js";
import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js";
import type { ArtifactInventoryPartialObservation } from "../../domain/artifactPartialObservation.js";
import type { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
@@ -68,19 +70,17 @@ export const reconstructJavaScriptArtifact = async (
progress?: ProgressReporter,
): Promise<JavaScriptArtifactReconstructionResult> =>
scope.run(async () => {
let effectiveSignal = signal;
let effectiveProgress = progress;
const reportPhase = async (
phase: string,
message: string,
): Promise<void> => {
await effectiveProgress?.report({
await progress?.report({
phase,
completed: 0,
total: 1,
message,
});
await checkpointJavaScriptAnalysis(effectiveSignal);
await checkpointJavaScriptAnalysis(signal);
};
const input = javascriptArtifactReconstructionInputSchema.parse(rawInput);
abortIfNeeded(signal);
@@ -182,14 +182,24 @@ export const reconstructJavaScriptArtifact = async (
}
}
const analysis = outcome.analysis;
const interruption = cleanupFailure ?? outcome.interruption;
if (interruption !== null && interruption !== undefined) {
effectiveSignal = undefined;
effectiveProgress = undefined;
}
await checkpointJavaScriptAnalysis(effectiveSignal);
abortIfNeeded(effectiveSignal);
await reportPhase(
let interruption = cleanupFailure ?? outcome.interruption;
// Source facts are owned now. Finish their projection cooperatively so a
// later cancellation can retain Evidence instead of discarding those facts.
const checkpointCompletedAnalysis = async (): Promise<void> => {
await setImmediate();
if (interruption == null && signal?.aborted === true)
interruption = new ArtifactOperationError(OPERATION, "cancelled");
};
const reportCompletedPhase = async (
phase: string,
message: string,
): Promise<void> => {
await checkpointCompletedAnalysis();
if (interruption == null)
await progress?.report({ phase, completed: 0, total: 1, message });
await checkpointCompletedAnalysis();
};
await reportCompletedPhase(
"build_javascript_application_graph",
"Constructing application and Electron boundary relationships",
);
@@ -198,15 +208,14 @@ export const reconstructJavaScriptArtifact = async (
files,
analysis,
);
await reportPhase(
await reportCompletedPhase(
"seal_javascript_application_graph",
"Sealing the validated application graph",
);
const graph = await completeJavaScriptAnalysisSteps(
applicationGraphSteps,
effectiveSignal,
);
await reportPhase(
await reportCompletedPhase(
"build_javascript_semantic_graph",
"Binding and validating static semantic relationships",
);
@@ -214,15 +223,13 @@ export const reconstructJavaScriptArtifact = async (
snapshot.manifest.root_sha256,
graph,
);
await reportPhase(
await reportCompletedPhase(
"seal_javascript_semantic_graph",
"Validating and sealing the semantic graph",
);
const semanticGraph = await completeJavaScriptAnalysisSteps(
semanticGraphSteps,
effectiveSignal,
);
await checkpointJavaScriptAnalysis(effectiveSignal);
const semanticGraph =
await completeJavaScriptAnalysisSteps(semanticGraphSteps);
await checkpointCompletedAnalysis();
const completed = {
input_path: path,
format,
@@ -526,12 +526,16 @@ const CPU_TYPE_X86 = 7;
const CPU_TYPE_ARM = 12;
const CPU_SUBTYPE_MASK = 0xff000000;
const CPU_SUBTYPE_ARM64E = 2;
const CPU_SUBTYPE_ARM64E_X1 = 12;
const CPU_SUBTYPE_X86_64_H = 8;
const architectureName = (cpuType: number, cpuSubtype: number): string => {
const subtype = cpuSubtype & ~CPU_SUBTYPE_MASK;
if (cpuType === (CPU_TYPE_ARM | CPU_ARCH_ABI64))
return subtype === CPU_SUBTYPE_ARM64E ? "arm64e" : "arm64";
// Both pointer-authentication subtypes belong to the arm64e family.
return subtype === CPU_SUBTYPE_ARM64E || subtype === CPU_SUBTYPE_ARM64E_X1
? "arm64e"
: "arm64";
if (cpuType === (CPU_TYPE_ARM | CPU_ARCH_ABI64_32)) return "arm64_32";
if (cpuType === (CPU_TYPE_X86 | CPU_ARCH_ABI64))
return subtype === CPU_SUBTYPE_X86_64_H ? "x86_64h" : "x86_64";
+3
View File
@@ -263,6 +263,9 @@ const setupRunOptions = (
? {
readinessScope: {
clients: options.client,
...(options.skillClient.length > 0
? { skillClients: options.skillClient }
: {}),
providers: options.installHopper ? ["hopper"] : [],
skill: options.skill ?? agentIntegrationSelected,
},
+3
View File
@@ -22,6 +22,8 @@ const EXECUTION_WORDING_EXCEPTIONS: Readonly<Record<string, string>> = {
inspect_macho: "runs host Mach-O inspection tools, not the target",
inspect_evm_interface:
"decodes bytecode in REA's bundled worker without executing it",
inspect_wasm_artifact:
"WABT validates and decompiles the module without executing it",
inspect_managed_artifact: "reads metadata without executing target code",
inspect_managed_members: "reads metadata without executing target code",
inspect_managed_native_boundaries:
@@ -47,6 +49,7 @@ const EXECUTION_WORDING_EXCEPTIONS: Readonly<Record<string, string>> = {
compare_javascript_export_shapes: "states it does not execute JavaScript",
project_android_application_graph: "execution-free inventory",
project_apple_application_graph: "execution-free inventory",
project_harmony_application_graph: "execution-free inventory",
trace_web_source_location: "states there is no application execution",
trace_web_module_imports:
"runs only REA's resolver stub in operator-configured Chromium",
+3 -3
View File
@@ -51,9 +51,9 @@ export interface AnalysisCleanupObservation {
/** Optional provider-neutral context that must survive typed error projection. */
export interface AnalysisErrorOptions extends ErrorOptions {
readonly capturedOutput?: AnalysisCapturedOutput;
readonly cleanup?: AnalysisCleanupObservation;
readonly partialObservation?: AnalysisPartialObservation;
readonly capturedOutput?: AnalysisCapturedOutput | undefined;
readonly cleanup?: AnalysisCleanupObservation | undefined;
readonly partialObservation?: AnalysisPartialObservation | undefined;
}
/** Base class for expected analysis, provider, and session failures. */
+4 -1
View File
@@ -265,9 +265,12 @@ const hopperProcessMessage = (error: HopperProcessError): string => {
const startup =
error.userMessage === undefined ? "" : ` ${error.userMessage}`;
if (error.providerState === "exited") {
const signal = error.launcherFailure?.signal;
const exit =
error.exitCode === null
? "no exit code was observed"
? signal === undefined || signal === null
? "no exit code was observed"
: `signal ${signal}`
: `exit code ${String(error.exitCode)}`;
const recovery =
error.failureCode === undefined && stage !== "launch"
+5 -2
View File
@@ -572,7 +572,7 @@ describe("analysis error projection: caller contract", () => {
describe("analysis error projection: operational diagnostics", () => {
it("distinguishes an observed Hopper exit from an undetermined provider failure", () => {
const exited = projectAnalysisError(
new HopperProcessError(7, undefined, "search_strings", 4),
new HopperProcessError(7, { operation: "search_strings", requestId: 4 }),
);
expect(exited).toMatchObject({
code: "provider_unavailable",
@@ -590,7 +590,10 @@ describe("analysis error projection: operational diagnostics", () => {
expect(exited.remediation.action).toContain("Restart the owned provider");
const unknown = projectAnalysisError(
new HopperProcessError(null, undefined, "search_strings", 5),
new HopperProcessError(null, {
operation: "search_strings",
requestId: 5,
}),
);
expect(unknown.details).toMatchObject({
stage: "analysis",
+34 -16
View File
@@ -1,4 +1,7 @@
import { AnalysisError } from "./analysisErrorBase.js";
import {
AnalysisError,
type AnalysisErrorOptions,
} from "./analysisErrorBase.js";
import type {
HopperProcessProviderState,
ProviderFailureStage,
@@ -73,10 +76,10 @@ export type HopperDiagnosticType =
| "bridge_exception";
/** Hopper's JSON-RPC endpoint returned an expected remote error response. */
export interface HopperRemoteErrorContext {
readonly diagnosticType?: HopperDiagnosticType;
readonly operation?: string;
readonly requestId?: number;
export interface HopperRemoteErrorContext extends AnalysisErrorOptions {
readonly diagnosticType?: HopperDiagnosticType | undefined;
readonly operation?: string | undefined;
readonly requestId?: number | undefined;
}
export class HopperRemoteError extends HopperError {
@@ -90,7 +93,7 @@ export class HopperRemoteError extends HopperError {
readonly safeMessage: string,
context: HopperRemoteErrorContext = {},
) {
super(`Hopper request failed (${String(code)}): ${safeMessage}`);
super(`Hopper request failed (${String(code)}): ${safeMessage}`, context);
this.diagnosticType = context.diagnosticType ?? "remote";
this.operation = context.operation;
this.requestId = context.requestId;
@@ -98,35 +101,50 @@ export class HopperRemoteError extends HopperError {
}
/** The owned Hopper bridge stopped before its client was closed. */
export interface HopperProcessErrorContext extends AnalysisErrorOptions {
readonly diagnostic?: HopperStartupFailureDiagnostic | undefined;
readonly operation?: string | undefined;
readonly requestId?: number | undefined;
readonly providerState?: HopperProcessProviderState | undefined;
readonly stage?: ProviderFailureStage | undefined;
readonly launcherFailure?: HopperLauncherOutcome | undefined;
}
export class HopperProcessError extends HopperError {
readonly _tag = "HopperProcessError";
readonly failureCode: HopperStartupFailureCode | undefined;
override readonly userMessage: string | undefined;
readonly providerState: HopperProcessProviderState;
readonly stage: ProviderFailureStage;
readonly diagnostic: HopperStartupFailureDiagnostic | undefined;
readonly operation: string | undefined;
readonly requestId: number | undefined;
readonly launcherFailure: HopperLauncherOutcome | undefined;
constructor(
readonly exitCode: number | null,
readonly diagnostic?: HopperStartupFailureDiagnostic,
readonly operation?: string,
readonly requestId?: number,
providerState?: HopperProcessProviderState,
stage?: ProviderFailureStage,
readonly launcherFailure?: HopperLauncherOutcome,
context: HopperProcessErrorContext = {},
) {
super(`Hopper bridge stopped unexpectedly with code ${String(exitCode)}`);
super(
`Hopper bridge stopped unexpectedly with code ${String(exitCode)}`,
context,
);
this.diagnostic = context.diagnostic;
this.operation = context.operation;
this.requestId = context.requestId;
this.launcherFailure = context.launcherFailure;
const failure = hopperStartupFailure(exitCode);
this.stage =
stage ??
context.stage ??
(failure === undefined
? operation === undefined
? context.operation === undefined
? "connection"
: "analysis"
: "launch");
this.failureCode = failure?.code;
this.userMessage = failure?.message;
this.providerState =
providerState ?? (exitCode === null ? "unknown" : "exited");
context.providerState ?? (exitCode === null ? "unknown" : "exited");
}
}
@@ -18,6 +18,7 @@ export const javaScriptAnalysisCoverageLimits = (
"worker_process_memory_limit_bytes",
"worker_timeout_ms",
"parent_result_budget_bytes",
"parent_available_result_budget_bytes",
"semantic_result_budget_bytes",
"transfer_record_bytes",
"transfer_file_bytes",
+43 -6
View File
@@ -249,10 +249,37 @@ const networkIdentity = (
): string =>
`net_${digestCanonicalValue({ method: request.method, url: request.url, resource_type: request.resource_type })}`;
const networkResponseFields = [
"status",
"mime_type",
"encoded_data_length",
] as const;
type NetworkResponseField = (typeof networkResponseFields)[number];
const sharedNetworkResponseFields = (
before: WebPageInspection,
after: WebPageInspection,
): ReadonlyMap<string, ReadonlySet<NetworkResponseField>> => {
const shared = new Map<string, Set<NetworkResponseField>>();
for (const inspection of [before, after])
for (const request of inspection.network.requests) {
const identity = networkIdentity(request);
const fields = shared.get(identity) ?? new Set(networkResponseFields);
for (const field of networkResponseFields)
if (request[field] === null) fields.delete(field);
shared.set(identity, fields);
}
return shared;
};
const networkDimension = (
before: WebPageInspection,
after: WebPageInspection,
): Dimension => {
const responseFields = sharedNetworkResponseFields(before, after);
const responseFieldsComplete = [...responseFields.values()].every(
(fields) => fields.size === networkResponseFields.length,
);
const selected = bodyShapesSelected(before) && bodyShapesSelected(after);
const webSocketShapes =
webSocketShapesSelected(before) && webSocketShapesSelected(after);
@@ -313,14 +340,14 @@ const networkDimension = (
afterWebSockets,
webSocketShapes,
);
return compareDimension(
const compared = compareDimension(
new Map([
...networkMap(before, sources),
...networkMap(before, sources, responseFields),
...webSocketMetadataMap(beforeWebSockets),
...beforeWebSocketPayload,
]),
new Map([
...networkMap(after, sources),
...networkMap(after, sources, responseFields),
...webSocketMetadataMap(afterWebSockets),
...afterWebSocketPayload,
]),
@@ -336,21 +363,31 @@ const networkDimension = (
webSocketShapesComplete,
"Network capture or selected HTTP/WebSocket payload-shape coverage is attach-window limited, unavailable, or incomplete.",
);
return compared.status === "unchanged" && !responseFieldsComplete
? {
...compared,
status: "unknown",
reason:
"HTTP response status, MIME type, or byte-count evidence is incomplete.",
}
: compared;
};
const networkMap = (
inspection: WebPageInspection,
sources: ReadonlyMap<string, BodyShapeSources>,
responseFields: ReadonlyMap<string, ReadonlySet<NetworkResponseField>>,
): ReadonlyMap<string, string> => {
const grouped = new Map<string, unknown[]>();
for (const request of inspection.network.requests) {
const identity = networkIdentity(request);
const shapes = sources.get(identity);
const values = grouped.get(identity) ?? [];
const response: Record<string, unknown> = {};
for (const field of responseFields.get(identity) ?? [])
response[field] = request[field];
values.push({
status: request.status,
mime_type: request.mime_type,
encoded_data_length: request.encoded_data_length,
...response,
redirects: (request.redirects ?? []).map(
({
request_timestamp: _requestTimestamp,
+7 -8
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import { digestSchema } from "./digests.js";
import { localPathStringSchema } from "./localPath.js";
import {
exportedWebScriptSchema,
webScriptExportManifestSchema,
@@ -8,10 +9,9 @@ import {
/** Inspect one captured script's native ES module relationships. */
export const webModuleTraceInputSchema = z.strictObject({
manifest_path: z
.string()
.min(1)
.describe("Absolute path to an export_web_scripts manifest"),
manifest_path: localPathStringSchema.describe(
"Absolute path to an export_web_scripts manifest",
),
script_index: z
.number()
.int()
@@ -26,10 +26,9 @@ export const webModuleTraceInputSchema = z.strictObject({
),
import_map: z
.strictObject({
path: z
.string()
.min(1)
.describe("Absolute local import-map JSON path; no fetch"),
path: localPathStringSchema.describe(
"Absolute local import-map JSON path; no fetch",
),
base_url: z
.string()
.min(1)
+4 -4
View File
@@ -1,5 +1,6 @@
import { z } from "zod";
import { jsonValueSchema } from "./jsonValue.js";
import { localPathStringSchema } from "./localPath.js";
/** Complete historical evidence budgets; exceeding a budget returns no partial capture. */
export const WEB_NETWORK_CAPTURE_LIMITS = {
@@ -11,10 +12,9 @@ export const WEB_NETWORK_CAPTURE_LIMITS = {
/** Inspect an explicit retained capture without contacting its recorded destinations. */
export const inspectWebNetworkCaptureInputSchema = z.strictObject({
capture_path: z
.string()
.min(1)
.describe("Absolute local HAR or mitmproxy capture path."),
capture_path: localPathStringSchema.describe(
"Absolute local HAR or mitmproxy capture path.",
),
format: z.enum(["har", "mitmproxy"]),
record_ordinals: z
.array(z.number().int().nonnegative())
+4 -4
View File
@@ -1,13 +1,13 @@
import { z } from "zod";
import { digestSchema } from "./digests.js";
import { localPathStringSchema } from "./localPath.js";
import { webScriptExportManifestSchema } from "./webScriptExport.js";
/** Select one source from an existing captured-script export. */
export const selectedWebScriptInputSchema = z.strictObject({
manifest_path: z
.string()
.min(1)
.describe("Absolute export_web_scripts manifest path"),
manifest_path: localPathStringSchema.describe(
"Absolute export_web_scripts manifest path",
),
script_index: z
.number()
.int()
+7 -12
View File
@@ -3,21 +3,16 @@ import { z } from "zod";
import { browserCompletenessSchema } from "./browserCompleteness.js";
import { browserScenarioCompletenessSchema } from "./browserScenarioCaptureValues.js";
import { digestSchema, prefixedDigestSchema } from "./digests.js";
import { localPathStringSchema } from "./localPath.js";
/** Export already captured scripts into one absent, caller-selected directory. */
export const exportWebScriptsInputSchema = z.strictObject({
capture_path: z
.string()
.min(1)
.describe(
"Absolute filesystem path to saved inspect_web_page or capture_browser_scenario JSON, normalized result or complete Evidence",
),
output_directory: z
.string()
.min(1)
.describe(
"Absolute absent filesystem directory for verified scripts and manifest; parent directory must exist",
),
capture_path: localPathStringSchema.describe(
"Absolute filesystem path to saved inspect_web_page or capture_browser_scenario JSON, normalized result or complete Evidence",
),
output_directory: localPathStringSchema.describe(
"Absolute absent filesystem directory for verified scripts and manifest; parent directory must exist",
),
});
export type ExportWebScriptsInput = z.output<
typeof exportWebScriptsInputSchema
+4 -4
View File
@@ -1,5 +1,6 @@
import { z } from "zod";
import { digestSchema } from "./digests.js";
import { localPathStringSchema } from "./localPath.js";
import { exportedWebScriptSchema } from "./webScriptExport.js";
import {
capturedWebManifestIdentitySchema,
@@ -17,10 +18,9 @@ export const webSourcePositionSchema = z.strictObject({
export const webSourceLocationInputSchema = selectedWebScriptInputSchema.extend(
{
source_map: z.strictObject({
path: z
.string()
.min(1)
.describe("Absolute local source-map path; no fetch"),
path: localPathStringSchema.describe(
"Absolute local source-map path; no fetch",
),
url: z
.string()
.min(1)
+14 -10
View File
@@ -19,6 +19,10 @@ import {
readMetadataString,
sha256Bytes,
} from "./ManagedMetadataHeaps.js";
import {
memberListIndexSize,
memberListTable,
} from "./ManagedMemberPointers.js";
export type ManagedType = ManagedMemberInspection["types"][number];
export type ManagedExportedType = NonNullable<
@@ -93,8 +97,8 @@ const readTypeRange = (
row: number,
issues: ManagedParseIssue[],
): TypeRange => {
const methods = layout.table(6);
const fields = layout.table(4);
const methods = memberListTable(layout, 6);
const fields = memberListTable(layout, 4);
const cursor = metadataRowCursor(bytes, layout, 2, row);
cursor.readUInt32();
const nameIndex = cursor.readIndex(layout.stringIndexSize);
@@ -114,8 +118,8 @@ const readTypeRange = (
issues,
) ?? null;
cursor.readIndex(layout.codedIndexSize("TypeDefOrRef"));
const fieldStart = cursor.readIndex(layout.tableIndexSize(4));
const methodStart = cursor.readIndex(layout.tableIndexSize(6));
const fieldStart = cursor.readIndex(memberListIndexSize(layout, 4));
const methodStart = cursor.readIndex(memberListIndexSize(layout, 6));
let nextField = (fields?.rowCount ?? 0) + 1;
let nextMethod = (methods?.rowCount ?? 0) + 1;
const typeTable = layout.table(2);
@@ -125,8 +129,8 @@ const readTypeRange = (
next.readIndex(layout.stringIndexSize);
next.readIndex(layout.stringIndexSize);
next.readIndex(layout.codedIndexSize("TypeDefOrRef"));
nextField = next.readIndex(layout.tableIndexSize(4));
nextMethod = next.readIndex(layout.tableIndexSize(6));
nextField = next.readIndex(memberListIndexSize(layout, 4));
nextMethod = next.readIndex(memberListIndexSize(layout, 6));
}
return {
token: metadataToken(2, row),
@@ -209,8 +213,8 @@ export const parseTypes = (
readonly issues: readonly ManagedParseIssue[];
} => {
const typeTable = layout.table(2);
const fields = layout.table(4);
const methods = layout.table(6);
const fields = memberListTable(layout, 4);
const methods = memberListTable(layout, 6);
const items: ManagedType[] = [];
const issues: ManagedParseIssue[] = [];
for (let row = 1; row <= (typeTable?.rowCount ?? 0); row += 1) {
@@ -233,8 +237,8 @@ export const parseTypes = (
const extendsRaw = cursor.readIndex(
layout.codedIndexSize("TypeDefOrRef"),
);
const fieldStart = cursor.readIndex(layout.tableIndexSize(4));
const methodStart = cursor.readIndex(layout.tableIndexSize(6));
const fieldStart = cursor.readIndex(memberListIndexSize(layout, 4));
const methodStart = cursor.readIndex(memberListIndexSize(layout, 6));
const nextRange = ranges[row] ?? null;
const fieldRange = rowRange(
fields,
@@ -0,0 +1,96 @@
import { describe, expect, it, vi } from "vitest";
import {
attachManagedDecodeBudget,
ManagedDecodeBudget,
} from "./ManagedDecodeBudget.js";
import { memberListRowLookup } from "./ManagedMemberPointers.js";
import { readManagedMetadataLayout } from "./ManagedMetadataLayout.js";
import { buildManagedMemberPointerFixture } from "./ManagedPe.fixture.js";
import { readManagedPeLayout } from "./ManagedPeReader.js";
import { ManagedReaderFailure } from "./ManagedReaderFailure.js";
const representationCapacity = 64 * 1024 * 1024;
const pointerFixture = () => {
const bytes = buildManagedMemberPointerFixture();
const pe = readManagedPeLayout(bytes);
if (pe.cli === null) throw new Error("Fixture has no CLI metadata");
const layout = readManagedMetadataLayout(
bytes,
pe.rvaToOffset(pe.cli.metadata.rva, pe.cli.metadata.size, "cli.metadata"),
pe.cli.metadata.size,
);
// A fresh owner lets the test set exact remaining capacity independently of
// the metadata version/string admission already exercised by the parser.
const budget = new ManagedDecodeBudget();
attachManagedDecodeBudget(layout, budget);
const indexBytes =
((layout.table(6)?.rowCount ?? 0) + 1) * Uint32Array.BYTES_PER_ELEMENT +
256;
return { bytes, layout, budget, indexBytes };
};
describe("managed member pointer index capacity", () => {
it("rejects insufficient capacity before allocating the inverse index", () => {
const { bytes, layout, budget, indexBytes } = pointerFixture();
budget.reserve(representationCapacity - indexBytes + 1, null);
let allocations = 0;
let failure: unknown;
// Proxy forwards static BYTES_PER_ELEMENT too: losing it would produce a
// NaN admission failure and falsely pass a before-allocation assertion.
vi.stubGlobal(
"Uint32Array",
new Proxy(Uint32Array, {
construct(target, arguments_, newTarget) {
allocations += 1;
return Reflect.construct(target, arguments_, newTarget);
},
}),
);
try {
memberListRowLookup(bytes, layout, 6);
} catch (cause: unknown) {
failure = cause;
} finally {
vi.unstubAllGlobals();
}
expect(failure).toBeInstanceOf(ManagedReaderFailure);
expect(failure).toMatchObject({
issue: {
code: "resource-limit",
scope: "metadata.representation",
offset: layout.table(5)?.offset,
},
});
expect(allocations).toBe(0);
});
it("reuses one layout's index without allocating or charging it again", () => {
const { bytes, layout, budget, indexBytes } = pointerFixture();
budget.reserve(representationCapacity - indexBytes, null);
let allocations = 0;
let observed: number[];
vi.stubGlobal(
"Uint32Array",
new Proxy(Uint32Array, {
construct(target, arguments_, newTarget) {
allocations += 1;
return Reflect.construct(target, arguments_, newTarget);
},
}),
);
try {
const first = memberListRowLookup(bytes, layout, 6);
const repeated = memberListRowLookup(bytes, layout, 6);
observed = [first(1), first(2), repeated(1), repeated(2)];
} finally {
vi.unstubAllGlobals();
}
expect(observed).toEqual([2, 1, 2, 1]);
expect(allocations).toBe(1);
expect(() => budget.reserve(1, null)).toThrow(ManagedReaderFailure);
});
});
+275
View File
@@ -0,0 +1,275 @@
import { describe, expect, it } from "vitest";
import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js";
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
import { readManagedMetadataLayout } from "./ManagedMetadataLayout.js";
import { readManagedPeLayout } from "./ManagedPeReader.js";
import {
buildManagedMemberPointerFixture,
managedPeFixtureTarget,
} from "./ManagedPe.fixture.js";
const metadataLayout = (bytes: Buffer) => {
const pe = readManagedPeLayout(bytes);
if (pe.cli === null) throw new Error("Fixture omitted CLI metadata");
return readManagedMetadataLayout(
bytes,
pe.rvaToOffset(pe.cli.metadata.rva, pe.cli.metadata.size, "cli.metadata"),
pe.cli.metadata.size,
);
};
describe("managed member pointer ownership", () => {
it.each([
{ table: "fields" as const, prefix: "0x040000" },
{ table: "methods" as const, prefix: "0x060000" },
])("maps reordered pointer slots to physical $table", ({ table, prefix }) => {
const bytes = buildManagedMemberPointerFixture();
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
);
expect(result.coverage).toEqual({ state: "complete", issues: [] });
expect(result.types.map((type) => type.full_name)).toEqual([
"<Module>",
"Fixture.A",
"Fixture.B",
]);
expect(
result[table].map(({ token, declaring_type, declaring_type_token }) => ({
token,
declaring_type,
declaring_type_token,
})),
).toEqual([
{
token: `${prefix}01`,
declaring_type: "Fixture.B",
declaring_type_token: "0x02000003",
},
{
token: `${prefix}02`,
declaring_type: "Fixture.A",
declaring_type_token: "0x02000002",
},
]);
});
it("resolves a local custom-attribute constructor through MethodPtr", () => {
const bytes = buildManagedMemberPointerFixture();
const target = managedPeFixtureTarget(bytes);
const artifact = inspectManagedArtifactBytes(bytes, target);
const members = inspectManagedMembersBytes(bytes, target);
expect(artifact.metadata.stream_names).toContain("#-");
expect(artifact.coverage).toEqual({ state: "complete", issues: [] });
expect(artifact.attributes).toEqual([
expect.objectContaining({
parent_token: "0x20000001",
constructor_token: "0x06000001",
type_name: "Fixture.B",
}),
]);
expect(artifact.attributes[0]?.type_name).toBe(
members.methods[0]?.declaring_type,
);
});
it.each([
{
label: "identity pointer tables",
fieldPointers: [1, 2],
methodPointers: [1, 2],
streamName: "#-" as const,
},
{
label: "ordinary direct lists",
fieldPointers: null,
methodPointers: null,
streamName: "#~" as const,
},
{
label: "empty pointer tables with direct lists",
fieldPointers: [],
methodPointers: [],
streamName: "#-" as const,
},
])("preserves $label", ({ fieldPointers, methodPointers, streamName }) => {
const bytes = buildManagedMemberPointerFixture({
fieldPointers,
methodPointers,
streamName,
});
const target = managedPeFixtureTarget(bytes);
const members = inspectManagedMembersBytes(bytes, target);
const artifact = inspectManagedArtifactBytes(bytes, target);
expect(members.coverage).toEqual({ state: "complete", issues: [] });
expect(members.fields.map((field) => field.declaring_type)).toEqual([
"Fixture.A",
"Fixture.B",
]);
expect(members.methods.map((method) => method.declaring_type)).toEqual([
"Fixture.A",
"Fixture.B",
]);
expect(artifact.attributes[0]?.type_name).toBe("Fixture.A");
});
});
describe("invalid managed member pointers", () => {
describe.each([
{
table: "fields" as const,
pointers: "fieldPointers" as const,
scope: "metadata.FieldPtr",
prefix: "0x040000",
names: ["firstField", "secondField"],
independent: "methods" as const,
},
{
table: "methods" as const,
pointers: "methodPointers" as const,
scope: "metadata.MethodPtr",
prefix: "0x060000",
names: [".ctor", ".ctor"],
independent: "fields" as const,
},
])(
"invalid $table pointers",
({ table, pointers, scope, prefix, names, independent }) => {
it.each([
{ label: "zero row", rows: [0, 1], owners: [null, null] },
{ label: "out-of-range row", rows: [3, 1], owners: [null, null] },
{ label: "duplicate row", rows: [1, 1], owners: [null, null] },
{ label: "omitted row", rows: [1], owners: ["Fixture.A", null] },
])(
"preserves member facts and independent ownership for $label",
({ rows, owners }) => {
const bytes = buildManagedMemberPointerFixture({ [pointers]: rows });
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
);
expect(result.coverage.state).toBe("partial");
expect(result.coverage.issues).toEqual(
expect.arrayContaining([
expect.objectContaining({
code: "invalid-row",
scope,
offset: expect.any(Number),
}),
]),
);
expect(
result[table].map(
({ token, name, declaring_type, declaring_type_token }) => ({
token,
name,
declaring_type,
declaring_type_token,
}),
),
).toEqual(
owners.map((owner, index) => ({
token: `${prefix}0${index + 1}`,
name: names[index],
declaring_type: owner,
declaring_type_token: owner === null ? null : "0x02000002",
})),
);
expect(
result[independent].map((member) => member.declaring_type),
).toEqual(["Fixture.B", "Fixture.A"]);
expect(
result.coverage.issues.some(
(issue) =>
issue.scope ===
(table === "fields"
? "metadata.MethodPtr"
: "metadata.FieldPtr"),
),
).toBe(false);
},
);
},
);
it.each([
{ label: "zero row", methodPointers: [2, 0] },
{ label: "duplicate row", methodPointers: [2, 2] },
{ label: "omitted constructor row", methodPointers: [2] },
])(
"preserves attribute facts with an unknown constructor owner for $label",
({ methodPointers }) => {
const controlBytes = buildManagedMemberPointerFixture();
const control = inspectManagedArtifactBytes(
controlBytes,
managedPeFixtureTarget(controlBytes),
).attributes[0];
if (control === undefined)
throw new Error("Fixture omitted custom attribute");
expect(control.type_name).toBe("Fixture.B");
const bytes = buildManagedMemberPointerFixture({ methodPointers });
const result = inspectManagedArtifactBytes(
bytes,
managedPeFixtureTarget(bytes),
);
expect(result.coverage.state).toBe("partial");
expect(result.coverage.issues).toEqual(
expect.arrayContaining([
expect.objectContaining({
code: "invalid-row",
scope: "metadata.MethodPtr",
}),
]),
);
expect(result.attributes).toEqual([
{ ...control, row_offset: expect.any(Number), type_name: null },
]);
},
);
it.each([
{ name: "FieldPtr", table: 3 },
{ name: "MethodPtr", table: 5 },
])("rejects a table stream ending inside a $name row", ({ table }) => {
const bytes = buildManagedMemberPointerFixture();
const layout = metadataLayout(bytes);
const pointers = layout.table(table);
if (pointers === undefined)
throw new Error("Fixture omitted pointer table");
const versionLength = bytes.readUInt32LE(layout.rootOffset + 12);
const firstStreamHeader =
((layout.rootOffset + 16 + versionLength + 3) & ~3) + 4;
const streamNameEnd = bytes.indexOf(0, firstStreamHeader + 8);
expect(bytes.toString("ascii", firstStreamHeader + 8, streamNameEnd)).toBe(
"#-",
);
const tablesOffset =
layout.rootOffset + bytes.readUInt32LE(firstStreamHeader);
bytes.writeUInt32LE(
pointers.offset + pointers.rowSize - 1 - tablesOffset,
firstStreamHeader + 4,
);
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
);
expect(result.coverage).toMatchObject({
state: "unavailable",
issues: [
expect.objectContaining({
code: "invalid-metadata-root",
scope: "metadata.table-data",
}),
],
});
expect(result.fields).toEqual([]);
expect(result.methods).toEqual([]);
});
});
+101
View File
@@ -0,0 +1,101 @@
import { managedDecodeBudget } from "./ManagedDecodeBudget.js";
import type { ManagedMetadataLayout } from "./ManagedMetadataLayout.js";
import {
managedFailure,
ManagedReaderFailure,
} from "./ManagedReaderFailure.js";
type MemberTable = 4 | 6;
type ListRowLookup = (definitionRow: number) => number;
const lookups = new WeakMap<
ManagedMetadataLayout,
Map<MemberTable, ListRowLookup | ManagedReaderFailure>
>();
/** TypeDef list coordinates refer to the nonempty pointer table when present. */
export const memberListTable = (
layout: ManagedMetadataLayout,
table: MemberTable,
) => {
const pointers = layout.table(table - 1);
return pointers !== undefined && pointers.rowCount > 0
? pointers
: layout.table(table);
};
/** List columns must accommodate either physical definition or pointer rows. */
export const memberListIndexSize = (
layout: ManagedMetadataLayout,
table: MemberTable,
): 2 | 4 =>
layout.tableIndexSize(table - 1) === 4 || layout.tableIndexSize(table) === 4
? 4
: 2;
/** Resolve physical definition rows to list positions without changing token identity. */
export const memberListRowLookup = (
bytes: Buffer,
layout: ManagedMetadataLayout,
table: MemberTable,
): ListRowLookup => {
const pointers = layout.table(table - 1);
if (pointers === undefined || pointers.rowCount === 0) return (row) => row;
let byTable = lookups.get(layout);
const cached = byTable?.get(table);
if (cached instanceof ManagedReaderFailure) throw cached;
if (cached !== undefined) return cached;
const definitionCount = layout.table(table)?.rowCount ?? 0;
// The layout already admitted the source table extent. Reserve retained index
// storage and its fixed bookkeeping before allocating either container.
managedDecodeBudget(layout).reserve(
(definitionCount + 1) * Uint32Array.BYTES_PER_ELEMENT + 256,
pointers.offset,
);
if (byTable === undefined) {
byTable = new Map();
lookups.set(layout, byTable);
}
const positions = new Uint32Array(definitionCount + 1);
try {
const width = layout.tableIndexSize(table);
for (let row = 1; row <= pointers.rowCount; row += 1) {
const offset: number = pointers.offset + (row - 1) * pointers.rowSize;
const definition =
width === 2 ? bytes.readUInt16LE(offset) : bytes.readUInt32LE(offset);
if (definition === 0 || definition > definitionCount)
throw managedFailure(
"invalid-row",
`metadata.${pointers.name}`,
`Pointer row ${String(row)} names an out-of-range definition row ${String(definition)}`,
offset,
);
if (positions[definition] !== 0)
throw managedFailure(
"invalid-row",
`metadata.${pointers.name}`,
`Definition row ${String(definition)} has more than one pointer row; its declaring type is ambiguous`,
offset,
);
positions[definition] = row;
}
const lookup: ListRowLookup = (definition) => {
const position = positions[definition] ?? 0;
if (position === 0)
throw managedFailure(
"invalid-row",
`metadata.${pointers.name}`,
`Definition row ${String(definition)} has no pointer row identifying its declaring type`,
pointers.offset,
);
return position;
};
byTable.set(table, lookup);
return lookup;
} catch (cause: unknown) {
// Invalid metadata must not rebuild and charge the same retained index for
// every attribute/member that asks for its owner.
if (cause instanceof ManagedReaderFailure) byTable.set(table, cause);
throw cause;
}
};
+19 -2
View File
@@ -31,6 +31,7 @@ import {
} from "./ManagedMetadataHeaps.js";
import { readManagedValue } from "./ManagedReaderFailure.js";
import { methodBody } from "./ManagedMethodBodyReader.js";
import { memberListRowLookup } from "./ManagedMemberPointers.js";
export const parseFields = (
bytes: Buffer,
@@ -46,6 +47,10 @@ export const parseFields = (
const issues: ManagedParseIssue[] = [];
const table = layout.table(4);
const declaringType = createDeclaringTypeLookup(ranges, "field");
const listRow = readManagedValue(
() => memberListRowLookup(bytes, layout, 4),
issues,
);
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
readManagedValue(() => {
const cursor = metadataRowCursor(bytes, layout, 4, row);
@@ -62,7 +67,11 @@ export const parseFields = (
cursor.readIndex(layout.blobIndexSize),
layout.blob.size,
);
const declared = declaringType(row);
const position =
listRow === undefined
? undefined
: readManagedValue(() => listRow(row), issues);
const declared = position === undefined ? null : declaringType(position);
const token = metadataToken(4, row);
fields.push({
token,
@@ -237,6 +246,10 @@ export const parseMethods = ({
const issues: ManagedParseIssue[] = [];
const table = layout.table(6);
const declaringType = createDeclaringTypeLookup(ranges, "method");
const listRow = readManagedValue(
() => memberListRowLookup(bytes, layout, 6),
issues,
);
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
readManagedValue(() => {
const cursor = metadataRowCursor(bytes, layout, 6, row);
@@ -256,7 +269,11 @@ export const parseMethods = ({
layout.blob.size,
);
cursor.readIndex(layout.tableIndexSize(8));
const declared = declaringType(row);
const position =
listRow === undefined
? undefined
: readManagedValue(() => listRow(row), issues);
const declared = position === undefined ? null : declaringType(position);
const token = metadataToken(6, row);
methods.push({
token,
+208
View File
@@ -0,0 +1,208 @@
import { describe, expect, it } from "vitest";
import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js";
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
import { readManagedPeLayout } from "./ManagedPeReader.js";
import {
buildManagedPeFixture,
managedPeFixtureTarget,
} from "./ManagedPe.fixture.js";
const fixtureTablesStream = (bytes: Buffer) => {
const pe = readManagedPeLayout(bytes);
if (pe.cli === null) throw new Error("Fixture omitted CLI metadata");
const root = pe.rvaToOffset(
pe.cli.metadata.rva,
pe.cli.metadata.size,
"cli.metadata",
);
const versionLength = bytes.readUInt32LE(root + 12);
const streamHeader = ((root + 16 + versionLength + 3) & ~3) + 4;
expect(
bytes.toString(
"ascii",
streamHeader + 8,
bytes.indexOf(0, streamHeader + 8),
),
).toBe("#~");
const tablesOffset = root + bytes.readUInt32LE(streamHeader);
const valid = bytes.readBigUInt64LE(tablesOffset + 8);
let count = 0;
for (let table = 0; table < 64; table += 1)
if ((valid & (1n << BigInt(table))) !== 0n) count += 1;
return { streamHeader, tablesOffset, extraDataOffset: 24 + count * 4 };
};
describe("CLR metadata tables ExtraData extension", () => {
it.each([
{ label: "absent extension", metadataExtraData: undefined },
{ label: "zero word", metadataExtraData: 0 },
{ label: "nonzero word", metadataExtraData: 0x1234_5678 },
{ label: "maximum unsigned word", metadataExtraData: 0xffff_ffff },
])(
"preserves metadata and member identities with $label",
({ metadataExtraData }) => {
const plain = buildManagedPeFixture();
const plainTarget = managedPeFixtureTarget(plain);
const baseline = inspectManagedArtifactBytes(plain, plainTarget);
const baselineMembers = inspectManagedMembersBytes(plain, plainTarget);
const bytes = buildManagedPeFixture(
metadataExtraData === undefined ? {} : { metadataExtraData },
);
const target = managedPeFixtureTarget(bytes);
const artifact = inspectManagedArtifactBytes(bytes, target);
const members = inspectManagedMembersBytes(bytes, target);
const shift = metadataExtraData === undefined ? 0 : 4;
expect(artifact.coverage).toEqual({ state: "complete", issues: [] });
expect(members.coverage).toEqual({ state: "complete", issues: [] });
if (baseline.module === null || baseline.assembly === null)
throw new Error("Fixture omitted module or assembly");
expect(artifact.module).toEqual({
...baseline.module,
row_offset: baseline.module.row_offset + shift,
});
expect(artifact.assembly).toEqual({
...baseline.assembly,
row_offset: baseline.assembly.row_offset + shift,
});
expect(artifact.metadata.table_row_counts).toEqual(
baseline.metadata.table_row_counts,
);
expect(artifact.target_frameworks).toEqual(baseline.target_frameworks);
expect(members.types).toEqual(
baselineMembers.types.map((type) => ({
...type,
row_offset: type.row_offset + shift,
})),
);
expect(members.fields).toEqual(
baselineMembers.fields.map((field) => ({
...field,
row_offset: field.row_offset + shift,
})),
);
expect(members.methods).toEqual(
baselineMembers.methods.map((method) => ({
...method,
row_offset: method.row_offset + shift,
})),
);
expect(members.call_edges).toEqual(baselineMembers.call_edges);
expect(members.field_accesses).toEqual(baselineMembers.field_accesses);
},
);
});
describe("CLR ExtraData index widths and boundaries", () => {
it("combines ExtraData with actual four-byte string heap indexes", () => {
const fieldName = "f".repeat(65_536);
const plain = buildManagedPeFixture({ fieldName });
const baseline = inspectManagedMembersBytes(
plain,
managedPeFixtureTarget(plain),
);
const bytes = buildManagedPeFixture({
fieldName,
metadataExtraData: 0x1234_5678,
});
const { tablesOffset } = fixtureTablesStream(bytes);
expect(bytes[tablesOffset + 6]).toBe(0x41);
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
);
expect(baseline.coverage).toEqual({ state: "complete", issues: [] });
expect(result.coverage).toEqual({ state: "complete", issues: [] });
expect(result.module?.name).toBe("Fixture.dll");
expect(result.module?.mvid).toBe(baseline.module?.mvid);
expect(result.types.map((type) => type.full_name)).toEqual([
"Fixture.Program",
]);
expect(result.fields.map(({ token, name }) => ({ token, name }))).toEqual([
{ token: "0x04000001", name: fieldName },
]);
// Main is placed after the large field name, so its index exceeds 0xffff.
expect(result.methods.map(({ token, name }) => ({ token, name }))).toEqual([
{ token: "0x06000001", name: "Main" },
]);
});
it("honors ExtraData in an unoptimized table stream without pointer tables", () => {
const bytes = buildManagedPeFixture({ metadataExtraData: 0x1234_5678 });
const baselineTarget = managedPeFixtureTarget(bytes);
const baseline = inspectManagedArtifactBytes(bytes, baselineTarget);
const baselineMembers = inspectManagedMembersBytes(bytes, baselineTarget);
const { streamHeader } = fixtureTablesStream(bytes);
bytes.write("#-", streamHeader + 8, "ascii");
const target = managedPeFixtureTarget(bytes);
const result = inspectManagedArtifactBytes(bytes, target);
const members = inspectManagedMembersBytes(bytes, target);
expect(result.coverage).toEqual({ state: "complete", issues: [] });
expect(members.coverage).toEqual({ state: "complete", issues: [] });
expect(result.metadata.stream_names).toContain("#-");
expect(result.metadata.stream_names).not.toContain("#~");
expect(result.module).toEqual(baseline.module);
expect(result.assembly).toEqual(baseline.assembly);
expect(members.types).toEqual(baselineMembers.types);
expect(members.fields).toEqual(baselineMembers.fields);
expect(members.methods).toEqual(baselineMembers.methods);
});
it("reports a truncated row count before interpreting ExtraData", () => {
const bytes = buildManagedPeFixture({ metadataExtraData: 0x1234_5678 });
const { streamHeader, extraDataOffset } = fixtureTablesStream(bytes);
bytes.writeUInt32LE(extraDataOffset - 1, streamHeader + 4);
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
);
expect(result.coverage).toMatchObject({
state: "unavailable",
issues: [
expect.objectContaining({
code: "invalid-metadata-root",
scope: "metadata.table-row-count",
}),
],
});
expect(result.types).toEqual([]);
expect(result.methods).toEqual([]);
});
it.each([0, 1, 3])(
"rejects an ExtraData word with only %i declared bytes",
(availableBytes) => {
const bytes = buildManagedPeFixture({ metadataExtraData: 0x1234_5678 });
const { streamHeader, tablesOffset, extraDataOffset } =
fixtureTablesStream(bytes);
expect(bytes[tablesOffset + 6]).toBe(0x40);
expect(bytes.readUInt32LE(tablesOffset + extraDataOffset)).toBe(
0x1234_5678,
);
// Only the declared tables-stream extent is shortened; the PE and heaps stay intact.
bytes.writeUInt32LE(extraDataOffset + availableBytes, streamHeader + 4);
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
);
expect(result.coverage).toMatchObject({
state: "unavailable",
issues: [
expect.objectContaining({
code: "invalid-metadata-root",
scope: "metadata.tables-extra-data",
offset: tablesOffset + extraDataOffset,
}),
],
});
expect(result.module).toBeNull();
expect(result.types).toEqual([]);
expect(result.methods).toEqual([]);
},
);
});
+1 -1
View File
@@ -155,7 +155,7 @@ const readAttributes = (
} => {
const attributes = readRows(layout.table(12), (row) =>
readManagedValue(
() => readCustomAttribute(bytes, layout, row, heapExtent(layout)),
() => readCustomAttribute(bytes, layout, row, heapExtent(layout), issues),
issues,
),
);
+21 -8
View File
@@ -1,4 +1,9 @@
import { managedDecodeBudget } from "./ManagedDecodeBudget.js";
import {
memberListIndexSize,
memberListRowLookup,
memberListTable,
} from "./ManagedMemberPointers.js";
import type {
ManagedArtifactInspection,
@@ -17,7 +22,7 @@ import {
readMetadataGuid,
readMetadataString,
} from "./ManagedMetadataHeaps.js";
import { managedFailure } from "./ManagedReaderFailure.js";
import { managedFailure, readManagedValue } from "./ManagedReaderFailure.js";
import type { ManagedResourceDirectory } from "./ManagedMetadataInventory.js";
type ModuleIdentity = NonNullable<ManagedArtifactInspection["module"]>;
@@ -242,21 +247,24 @@ const declaringTypeForMethod = (
heapExtent: number,
): string | null => {
const types = layout.table(2);
const methods = layout.table(6);
const methods = memberListTable(layout, 6);
if (types === undefined || methods === undefined) return null;
if (methodRow < 1 || methodRow > (layout.table(6)?.rowCount ?? 0))
return null;
const position = memberListRowLookup(bytes, layout, 6)(methodRow);
for (let row = 1; row <= types.rowCount; row += 1) {
const cursor = metadataRowCursor(bytes, layout, 2, row);
cursor.readUInt32();
const nameIndex = cursor.readIndex(layout.stringIndexSize);
const namespaceIndex = cursor.readIndex(layout.stringIndexSize);
cursor.readIndex(layout.codedIndexSize("TypeDefOrRef"));
cursor.readIndex(layout.tableIndexSize(4));
const methodStart = cursor.readIndex(layout.tableIndexSize(6));
cursor.readIndex(memberListIndexSize(layout, 4));
const methodStart = cursor.readIndex(memberListIndexSize(layout, 6));
const methodEnd =
row === types.rowCount
? methods.rowCount + 1
: methodListForType(bytes, layout, row + 1);
if (methodRow < methodStart || methodRow >= methodEnd) continue;
if (position < methodStart || position >= methodEnd) continue;
const name = readMetadataString(bytes, layout, nameIndex, heapExtent);
const namespace = readMetadataString(
bytes,
@@ -279,8 +287,8 @@ const methodListForType = (
cursor.readIndex(layout.stringIndexSize);
cursor.readIndex(layout.stringIndexSize);
cursor.readIndex(layout.codedIndexSize("TypeDefOrRef"));
cursor.readIndex(layout.tableIndexSize(4));
return cursor.readIndex(layout.tableIndexSize(6));
cursor.readIndex(memberListIndexSize(layout, 4));
return cursor.readIndex(memberListIndexSize(layout, 6));
};
const attributeTypeName = (
@@ -377,6 +385,7 @@ export const readCustomAttribute = (
layout: ManagedMetadataLayout,
row: number,
heapExtent: number,
issues: ManagedParseIssue[],
): CustomAttribute => {
const cursor = metadataRowCursor(bytes, layout, 12, row);
const parentRaw = cursor.readIndex(
@@ -432,7 +441,11 @@ export const readCustomAttribute = (
: `CustomAttribute constructor coded index 0x${typeRaw.toString(16)} is invalid: ${typeReason}`,
typeOffset,
);
const typeName = attributeTypeName(bytes, layout, typeRaw, heapExtent);
const typeName =
readManagedValue(
() => attributeTypeName(bytes, layout, typeRaw, heapExtent),
issues,
) ?? null;
return {
parent_token: parent,
constructor_token: metadataCodedToken(
+12
View File
@@ -358,6 +358,18 @@ const buildMetadataTables = ({
if ((valid & (1n << BigInt(index))) === 0n) continue;
tableCursor += 4;
}
// CLR readers honor an optional extra-data word after the row counts.
// Its value is opaque; it is not a length or part of the first table row.
if (((tableBytes[6] ?? 0) & 0x40) !== 0) {
if (tableCursor > tableBytes.length - 4)
throw managedFailure(
"invalid-metadata-root",
"metadata.tables-extra-data",
"Metadata tables extra-data word is truncated",
tablesOffset + tableCursor,
);
tableCursor += 4;
}
for (let index = 0; index < METADATA_TABLE_NAMES.length; index += 1) {
const count = rowCounts[index] ?? 0;
if ((valid & (1n << BigInt(index))) === 0n) continue;
+1 -1
View File
@@ -15,7 +15,7 @@ const ROW_SIZE_FACTORIES: readonly RowSizeFactory[] = [
({ stringSize: s, guidSize: g }) => 2 + s + g * 3,
({ codedSize: c, stringSize: s }) => c("ResolutionScope") + s * 2,
({ tableSize: t, codedSize: c, stringSize: s }) =>
4 + s * 2 + c("TypeDefOrRef") + t(4) + t(6),
4 + s * 2 + c("TypeDefOrRef") + Math.max(t(3), t(4)) + Math.max(t(5), t(6)),
({ tableSize: t }) => t(4),
({ stringSize: s, blobSize: b }) => 2 + s + b,
({ tableSize: t }) => t(6),
+149 -7
View File
@@ -20,6 +20,7 @@ interface ManagedPeFixtureOptions {
readonly ilBody?: Buffer;
readonly malformedAssemblyReferenceRows?: readonly number[];
readonly malformedCustomAttributeRows?: readonly number[];
readonly metadataExtraData?: number;
readonly metadataValidMaskExtra?: bigint;
readonly methodName?: string;
readonly methodFlags?: number;
@@ -190,6 +191,7 @@ const typeDefRow = ({
fieldListSize,
methodListSize,
extendsRaw = (1 << 2) | 1,
flags = 0x0010_0001,
}: {
readonly name: number;
readonly namespace: number;
@@ -200,9 +202,10 @@ const typeDefRow = ({
readonly fieldListSize: MetadataIndexSize;
readonly methodListSize: MetadataIndexSize;
readonly extendsRaw?: number;
readonly flags?: number;
}): Buffer =>
Buffer.concat([
u32(0x0010_0001),
u32(flags),
metadataIndex(name, stringSize),
metadataIndex(namespace, stringSize),
metadataIndex(extendsRaw, typeDefOrRefSize),
@@ -231,6 +234,7 @@ interface MethodDefRowInput {
readonly rva?: number;
readonly flags?: number;
readonly implFlags?: number;
readonly parameterList?: number;
}
const methodDefRow = ({
@@ -242,6 +246,7 @@ const methodDefRow = ({
rva = 0,
flags = 0x0016,
implFlags = 0,
parameterList = 0,
}: MethodDefRowInput): Buffer =>
Buffer.concat([
u32(rva),
@@ -249,7 +254,7 @@ const methodDefRow = ({
u16(flags),
metadataIndex(name, stringSize),
metadataIndex(signature, blobSize),
metadataIndex(0, parameterSize),
metadataIndex(parameterList, parameterSize),
]);
const memberRefRow = ({
@@ -416,6 +421,7 @@ const metadataRoot = (
strings: Buffer,
guid: Buffer,
blob: Buffer,
tableStreamName: "#~" | "#-" = "#~",
): Buffer => {
const version = Buffer.from("v4.0.30319\0\0", "utf8");
const header = Buffer.concat([
@@ -429,7 +435,7 @@ const metadataRoot = (
u16(4),
]);
const streamHeaderSize =
metadataStreamHeader(0, 0, "#~").length +
metadataStreamHeader(0, 0, tableStreamName).length +
metadataStreamHeader(0, 0, "#Strings").length +
metadataStreamHeader(0, 0, "#GUID").length +
metadataStreamHeader(0, 0, "#Blob").length;
@@ -442,7 +448,7 @@ const metadataRoot = (
offset = align4(offset + guid.length);
const blobOffset = offset;
const headers = Buffer.concat([
metadataStreamHeader(tablesOffset, tables.length, "#~"),
metadataStreamHeader(tablesOffset, tables.length, tableStreamName),
metadataStreamHeader(stringsOffset, strings.length, "#Strings"),
metadataStreamHeader(guidOffset, guid.length, "#GUID"),
metadataStreamHeader(blobOffset, blob.length, "#Blob"),
@@ -461,12 +467,13 @@ const tablesStream = (
rows: ReadonlyMap<number, readonly Buffer[]>,
extraValidMask: bigint,
heapSizes: number,
extraData?: number,
): Buffer => {
let valid = extraValidMask;
for (const table of rows.keys()) valid |= 1n << BigInt(table);
const header = Buffer.alloc(24);
header.writeUInt8(2, 4);
header.writeUInt8(heapSizes, 6);
header.writeUInt8(heapSizes | (extraData === undefined ? 0 : 0x40), 6);
header.writeUInt8(1, 7);
header.writeBigUInt64LE(valid, 8);
const counts: Buffer[] = [];
@@ -481,7 +488,12 @@ const tablesStream = (
if (tableRows === undefined) continue;
data.push(...tableRows);
}
return Buffer.concat([header, ...counts, ...data]);
return Buffer.concat([
header,
...counts,
...(extraData === undefined ? [] : [u32(extraData)]),
...data,
]);
};
interface FixtureMetadataRowContext {
@@ -870,7 +882,12 @@ const buildManagedFixtureMetadata = (
(guidSize === 4 ? 0x02 : 0) |
(blobSize === 4 ? 0x04 : 0);
const metadata = metadataRoot(
tablesStream(rows, options.metadataValidMaskExtra ?? 0n, heapFlags),
tablesStream(
rows,
options.metadataValidMaskExtra ?? 0n,
heapFlags,
options.metadataExtraData,
),
strings.toBuffer(),
guidHeap(options.mvid),
blobs.toBuffer(),
@@ -990,6 +1007,131 @@ export const buildManagedPeFixture = (
buildManagedFixtureMetadata(options, methodRva),
);
/** Two attribute classes whose pointer-table slots can reorder physical members. */
export const buildManagedMemberPointerFixture = (
options: {
readonly fieldPointers?: readonly number[] | null;
readonly methodPointers?: readonly number[] | null;
readonly streamName?: "#~" | "#-";
} = {},
): Buffer => {
const fieldPointers =
options.fieldPointers === undefined ? [2, 1] : options.fieldPointers;
const methodPointers =
options.methodPointers === undefined ? [2, 1] : options.methodPointers;
// Both instance constructors call System.Attribute::.ctor(), then return.
const body = Buffer.from([0x1e, 0x02, 0x28, 0x01, 0, 0, 0x0a, 0x2a]);
const image = buildManagedFixtureImage({ ilBody: body }, (methodRva) => {
const strings = new StringHeap();
const blobs = new BlobHeap();
const moduleName = strings.add("MemberPointers.dll");
const assemblyName = strings.add("Fixture.MemberPointers");
const namespace = strings.add("Fixture");
const typeNames = ["<Module>", "A", "B"].map((name) => strings.add(name));
const fieldNames = ["firstField", "secondField"].map((name) =>
strings.add(name),
);
const constructorName = strings.add(".ctor");
const attributeName = strings.add("Attribute");
const systemNamespace = strings.add("System");
const runtimeName = strings.add("System.Runtime");
const fieldSignature = blobs.add(Buffer.from([0x06, 0x08]));
const constructorSignature = blobs.add(
Buffer.from([0x20, 0x01, 0x01, 0x0e]),
);
const baseConstructorSignature = blobs.add(Buffer.from([0x20, 0, 0x01]));
const attributeValue = blobs.add(fixedStringAttributeBlob("fixture"));
const rows = new Map<number, readonly Buffer[]>([
[0, [moduleRow(moduleName, 2, 2)]],
// ResolutionScope selects AssemblyRef 1, which contains System.Attribute.
[
1,
[
Buffer.concat([
u16((1 << 2) | 2),
u16(attributeName),
u16(systemNamespace),
]),
],
],
[
2,
typeNames.map((name, index) =>
typeDefRow({
name,
namespace: index === 0 ? 0 : namespace,
fieldList: index === 2 ? 2 : 1,
methodList: index === 2 ? 2 : 1,
stringSize: 2,
typeDefOrRefSize: 2,
fieldListSize: 2,
methodListSize: 2,
extendsRaw: index === 0 ? 0 : (1 << 2) | 1,
flags: index === 0 ? 0 : 0x0010_0001,
}),
),
],
[4, fieldNames.map((name) => fieldRow(name, fieldSignature, 2, 2))],
[
6,
[1, 2].map(() =>
methodDefRow({
name: constructorName,
signature: constructorSignature,
stringSize: 2,
blobSize: 2,
parameterSize: 2,
parameterList: 1,
rva: methodRva,
flags: 0x1886,
}),
),
],
[
10,
[
memberRefRow({
name: constructorName,
signature: baseConstructorSignature,
stringSize: 2,
blobSize: 2,
parentSize: 2,
}),
],
],
// The assembly attribute constructor is physical MethodDef row 1.
[
12,
[
customAttributeRow({
value: attributeValue,
options: { customAttributeTypeRaw: (1 << 3) | 2 },
parentIndexSize: 2,
typeIndexSize: 2,
blobSize: 2,
row: 1,
}),
],
],
[32, [assemblyRow(assemblyName, 2, 2)]],
[35, [assemblyRefRow(runtimeName, 0, false, 2, 2)]],
]);
if (fieldPointers !== null) rows.set(3, fieldPointers.map(u16));
if (methodPointers !== null) rows.set(5, methodPointers.map(u16));
return metadataRoot(
tablesStream(rows, 0n, 0),
strings.toBuffer(),
guidHeap(),
blobs.toBuffer(),
options.streamName ?? "#-",
);
});
// The shared PE shell defaults to an executable; this fixture is a DLL.
image.writeUInt16LE(image.readUInt16LE(0x84 + 18) | 0x2000, 0x84 + 18);
image.writeUInt32LE(0, 0x0200 + 20);
return image;
};
/** Build a syntactically valid PE32 fixture with no CLI directory. */
export const buildNativePeFixture = (): Buffer => {
const image = buildManagedPeFixture();
+3 -4
View File
@@ -362,10 +362,9 @@ export class HopperApplicationLauncher implements BridgeLauncher {
? { ok: true, strategy: selection.strategy }
: {
ok: false,
error: new HopperProcessError(
selection.exitCode,
selection.diagnostic,
),
error: new HopperProcessError(selection.exitCode, {
diagnostic: selection.diagnostic,
}),
};
}
}
+1 -3
View File
@@ -202,9 +202,7 @@ const shutdownRequestFailure = (
operation: "shutdown" | "shutdown_document",
cause: unknown,
): HopperProcessError => {
const failure = new HopperProcessError(null, undefined, operation);
failure.cause = cause;
return failure;
return new HopperProcessError(null, { operation, cause });
};
const shutdownFailureDetails = (
+44 -44
View File
@@ -129,13 +129,9 @@ export class HopperClient {
this.#responses.push(chunk);
};
readonly #onSocketError = (): void => {
const error = new HopperProcessError(
null,
undefined,
undefined,
undefined,
"unreachable",
);
const error = new HopperProcessError(null, {
providerState: "unreachable",
});
this.#failAll(error);
this.#rememberProcessFailure(error, []);
};
@@ -151,25 +147,18 @@ export class HopperClient {
setImmediate(() => {
if (this.#closing || this.#launcherExitCode !== undefined) return;
const exitCode = launch.process.exitCode ?? null;
const error = new HopperProcessError(
exitCode,
this.#launcherFailureDiagnostic,
undefined,
undefined,
exitCode !== null ? "exited" : "unreachable",
);
const error = new HopperProcessError(exitCode, {
diagnostic: this.#launcherFailureDiagnostic,
providerState: exitCode !== null ? "exited" : "unreachable",
});
this.#failAll(error);
this.#rememberProcessFailure(error, []);
});
return;
}
const error = new HopperProcessError(
null,
undefined,
undefined,
undefined,
"unreachable",
);
const error = new HopperProcessError(null, {
providerState: "unreachable",
});
this.#failAll(error);
this.#rememberProcessFailure(error, []);
};
@@ -729,15 +718,12 @@ export class HopperClient {
)) ?? false;
const launcherFailure = this.#launcherOutcome(outputClosed);
if (ownsProviderLifetime)
return new HopperProcessError(
exitCode,
this.#launcherFailureDiagnostic,
undefined,
undefined,
"exited",
"launch",
return new HopperProcessError(exitCode, {
diagnostic: this.#launcherFailureDiagnostic,
providerState: "exited",
stage: "launch",
launcherFailure,
);
});
if (
this.#resources.launch?.authorizationDenialBeforeHandoff === true &&
nativeHopperLaunchWasDenied(launcherFailure)
@@ -766,18 +752,34 @@ export class HopperClient {
},
): Promise<Result<JsonValue, HopperError>> {
const id = this.#nextId++;
if (
this.#resources.launch?.providerLifetime === "launcher-process" &&
this.#launcherExitCode !== undefined
) {
return this.#unavailableRequest(
new HopperProcessError(this.#launcherExitCode, {
diagnostic: this.#launcherFailureDiagnostic,
operation: method,
requestId: id,
providerState: "exited",
stage: hopperOperationStage(method),
launcherFailure: this.#launcherOutcome(
(await this.#resources.processSupervisor?.waitForOutputClose(0)) ??
false,
),
}),
);
}
const socket = this.#socket;
const token = this.#token;
if (socket === undefined || socket.destroyed || token === undefined) {
return this.#unavailableRequest(
new HopperProcessError(
null,
undefined,
method,
id,
"unreachable",
hopperOperationStage(method),
),
new HopperProcessError(null, {
operation: method,
requestId: id,
providerState: "unreachable",
stage: hopperOperationStage(method),
}),
);
}
if (options.signal?.aborted === true)
@@ -888,13 +890,11 @@ export class HopperClient {
if (launch.providerLifetime === "launcher-process" && !this.#closing) {
this.#rememberExit(event.code);
this.#failAll(
new HopperProcessError(
event.code,
this.#launcherFailureDiagnostic,
undefined,
undefined,
"exited",
),
new HopperProcessError(event.code, {
diagnostic: this.#launcherFailureDiagnostic,
providerState: "exited",
launcherFailure: this.#launcherOutcome(false),
}),
);
}
}
+18 -19
View File
@@ -273,14 +273,12 @@ export class HopperRequestQueue {
this.accept(
entry.id,
err(
new HopperProcessError(
null,
undefined,
entry.method,
entry.id,
"unreachable",
hopperOperationStage(entry.method),
),
new HopperProcessError(null, {
operation: entry.method,
requestId: entry.id,
providerState: "unreachable",
stage: hopperOperationStage(entry.method),
}),
),
),
);
@@ -386,19 +384,20 @@ const withRequestContext = (
entry: QueuedRequest,
): HopperError => {
if (error instanceof HopperProcessError)
return new HopperProcessError(
error.exitCode,
error.diagnostic,
error.operation ?? entry.method,
error.requestId ?? entry.id,
error.providerState,
error.operation === undefined && error.stage === "connection"
? hopperOperationStage(entry.method)
: error.stage,
);
return new HopperProcessError(error.exitCode, {
...error,
cause: error.cause,
operation: error.operation ?? entry.method,
requestId: error.requestId ?? entry.id,
stage:
error.operation === undefined && error.stage === "connection"
? hopperOperationStage(entry.method)
: error.stage,
});
if (error instanceof HopperRemoteError)
return new HopperRemoteError(error.code, error.safeMessage, {
diagnosticType: error.diagnosticType,
...error,
cause: error.cause,
operation: error.operation ?? entry.method,
requestId: error.requestId ?? entry.id,
});
@@ -59,6 +59,7 @@ import {
const OPERATION = "analyze_javascript_application";
const PROVIDER = "javascript-static-analysis";
const MIB = 1024 * 1024;
const STATIC_CHECKPOINT_RETENTION_EXPANSION = 6;
const pendingCleanup = new Set<JavaScriptAnalysisWorker>();
/** The worker runs on this executable; Bun accepts but ignores V8 heap flags. */
const WORKER_HEAP_FLAGS_ENFORCED =
@@ -80,7 +81,6 @@ export class JavaScriptAnalysisWorker {
#estimatedRetainedBytes = 0;
#applicationProjectionFailure: AnalysisResourceConstraintError | undefined;
#parentCapacityExhausted = false;
#retainedStaticBytes = 0;
#sourcesRemaining: number | undefined;
readonly #resultBudgetBytes: number;
/** Null when the runtime enforces the V8 heap flags instead. */
@@ -326,7 +326,13 @@ export class JavaScriptAnalysisWorker {
{
...this.#limits(),
parent_result_budget_bytes: this.#resultBudgetBytes,
parent_available_result_budget_bytes: remaining,
module_transfer_bytes: descriptor.module_bytes,
module_retention_estimate_bytes: moduleEstimate,
},
{
remediationAction:
"Use the retained static facts or analyze fewer source files. This limit belongs to the parent result budget; increasing the worker heap alone does not increase it.",
},
),
});
@@ -358,9 +364,16 @@ export class JavaScriptAnalysisWorker {
{
...this.#limits(),
parent_result_budget_bytes: this.#resultBudgetBytes,
parent_available_result_budget_bytes: remaining,
module_retention_estimate_bytes: moduleEstimate,
graph_retention_estimate_bytes: graphEstimate,
graph_transfer_bytes: descriptor.graph_bytes,
graph_records: descriptor.graph_records,
},
{
remediationAction:
"Use the retained static and module facts or analyze fewer source files. This limit belongs to the parent result budget; increasing the worker heap alone does not increase it.",
},
),
});
break;
@@ -582,16 +595,16 @@ export class JavaScriptAnalysisWorker {
const value: unknown = JSON.parse(text);
const facts = javaScriptWorkerStaticAnalysisSchema.parse(value);
const remaining = this.#remainingTotalResultBudget();
const retainedBytes = bytes * 6;
const retainedBytes = bytes * STATIC_CHECKPOINT_RETENTION_EXPANSION;
this.#parentCapacityExhausted = retainedBytes > remaining;
this.#estimatedRetainedBytes += retainedBytes;
this.#retainedStaticBytes += retainedBytes;
const expandedBytes = estimateJavaScriptStaticApplicationProjection(
facts,
bytes,
sourcePath,
);
if (expandedBytes <= this.#remainingResultBudget())
const availableResultBudget = this.#remainingResultBudget();
if (expandedBytes <= availableResultBudget)
this.#estimatedRetainedBytes += expandedBytes;
else
this.#applicationProjectionFailure = new AnalysisResourceConstraintError(
@@ -600,8 +613,13 @@ export class JavaScriptAnalysisWorker {
`Expanded application relationships for ${sourcePath} exceed the parent's result budget; complete static facts were retained on the file node`,
{
parent_result_budget_bytes: this.#resultBudgetBytes,
parent_available_result_budget_bytes: availableResultBudget,
application_projection_required_bytes: expandedBytes,
},
{
remediationAction:
"Read the complete static facts on the file node or analyze fewer source files. Expanded application relationships exceed the parent result budget; increasing the worker heap alone does not increase it.",
},
);
return facts;
}
@@ -638,16 +656,17 @@ export class JavaScriptAnalysisWorker {
);
}
#remainingResultBudget(): number {
// Future sources need their compact observations before current modules
// consume capacity with expanded relationships. A final or sole source
// can use the unused reserve as well.
// One sequential worker produces one next checkpoint at a time. Reserve
// its maximum protocol size at the same retained expansion used on receipt;
// earlier checkpoints are already charged to estimatedRetainedBytes.
// Reserving every unexamined source's maximum would reject useful results
// merely because many small files remain. Actual retained growth and live
// heap capacity are checked again for every checkpoint and transfer.
const checkpointReserve =
DEFAULTS.checkpointBytes * STATIC_CHECKPOINT_RETENTION_EXPANSION;
const staticReserve =
this.#sourcesRemaining !== undefined && this.#sourcesRemaining > 0
? Math.max(
0,
Math.floor((this.#resultBudgetBytes * 4) / 5) -
this.#retainedStaticBytes,
)
? checkpointReserve
: 0;
return Math.max(0, this.#remainingTotalResultBudget() - staticReserve);
}
@@ -36,11 +36,30 @@ it("returns a nonzero exit for a streamed JSON analysis failure", async () => {
// `analyze` routes a JavaScript directory to the same workflow and must keep
// its typed cancellation contract.
it
.skipIf(process.platform === "win32")
.each(["analyze-javascript-application", "analyze"])(
"returns a typed cancelled CLI result and exit 130 after SIGINT through %s",
async (command) => {
it.skipIf(process.platform === "win32").each([
{
command: "analyze-javascript-application",
phase: "analyze_javascript_application",
parsedFiles: null,
},
{
command: "analyze",
phase: "analyze_javascript_application",
parsedFiles: null,
},
{
command: "analyze-javascript-application",
phase: "build_javascript_application_graph",
parsedFiles: 1,
},
{
command: "analyze-javascript-application",
phase: "hash_javascript_application_evidence",
parsedFiles: 1,
},
])(
"returns typed cancellation and exit 130 after SIGINT through $command during $phase",
async ({ command, phase, parsedFiles }) => {
const root = await createTestTempDirectory("rea-cli-js-cancellation-");
await writeFile(join(root, "main.js"), "export const observed = 1;\n");
const child = spawn(
@@ -70,7 +89,11 @@ it
const line = partial.slice(0, newline);
partial = partial.slice(newline + 1);
const parsed = progressSchema.safeParse(JSON.parse(line));
if (parsed.success && !requested) {
if (
parsed.success &&
parsed.data.rea_progress.phase === phase &&
!requested
) {
requested = true;
child.kill("SIGINT");
}
@@ -89,5 +112,18 @@ it
code: "cancelled",
details: { reason: "cancelled" },
});
if (parsedFiles !== null)
expect(JSON.parse(stdout)).toMatchObject({
details: {
partial_observation: {
normalized_result: {
statistics: {
parsed_javascript_files: parsedFiles,
parse_failures: 0,
},
},
},
},
});
},
);
@@ -0,0 +1,132 @@
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { z } from "zod";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest.skipIf(process.versions.bun !== undefined).for([
{ laterSources: 1, heapMb: 640, methodsCount: 400, retainGraph: true },
{ laterSources: 10, heapMb: 640, methodsCount: 400, retainGraph: true },
// Even an otherwise empty parent cannot admit this graph after reserving
// transient decoding and the next checkpoint, independent of GC timing.
{ laterSources: 1, heapMb: 448, methodsCount: 600, retainGraph: false },
])(
"preserves evidence with $laterSources later checkpoints and a $heapMb MiB parent heap",
{ timeout: 90_000 },
async ({ laterSources, heapMb, methodsCount, retainGraph }, { cli }) => {
const root = await createTestTempDirectory("rea-js-checkpoint-reserve-");
const source = Array.from(
{ length: methodsCount },
(_, index) =>
`export function method_${String(index)}(input) { const value = input + ${String(index)}; const pair = { value }; return pair.value; }`,
).join("\n");
const files: readonly (readonly [string, string])[] = [
["a-large.mjs", source],
...Array.from(
{ length: laterSources },
(_, index) =>
[
`z-tiny-${String(index)}.mjs`,
`export const tiny${String(index)} = 1;\n`,
] as const,
),
];
for (const [name, text] of files) await writeFile(join(root, name), text);
const response = await cli.run({
arguments: ["analyze", root, "--format", "json"],
environment: {
NODE_OPTIONS: `--max-old-space-size=${String(heapMb)} --max-semi-space-size=8`,
},
timeoutMs: 60_000,
});
expect(response.exitCode).toBe(0);
const result = javascriptApplicationAnalysisResultSchema.parse(
parseEvidence(response.json).normalized_result,
);
expect(result.statistics.parsed_javascript_files).toBe(laterSources + 1);
expect(result.statistics.parse_failures).toBe(0);
const failures = result.graph.nodes.flatMap(({ observations }) =>
observations.flatMap(({ properties }) =>
properties.analysis_failure === undefined
? []
: [properties.analysis_failure],
),
);
const methods = result.semantic_graph.nodes.filter(
({ kind, identity }) =>
kind === "function" && identity.module_path === "a-large.mjs",
);
if (retainGraph)
expect(methods.map(({ label }) => label).sort()).toEqual(
Array.from(
{ length: methodsCount },
(_, index) => `method_${String(index)}`,
).sort(),
);
else {
expect(methods).toHaveLength(0);
expect([
result.graph.coverage.status,
result.semantic_graph.coverage.status,
]).toContain("partial");
}
expect(
result.semantic_graph.nodes.some(
({ identity, label }) =>
identity.module_path === `z-tiny-${String(laterSources - 1)}.mjs` &&
label === `tiny${String(laterSources - 1)}`,
),
).toBe(true);
for (const [name, text] of files) {
const digest = createHash("sha256").update(text).digest("hex");
const node = result.graph.nodes.find(
({ kind, identity }) =>
kind === "javascript-asset" &&
identity.strategy === "content-digest" &&
identity.sha256 === digest,
);
expect(node?.observations).toEqual(
expect.arrayContaining([
expect.objectContaining({
properties: expect.objectContaining({
path: name,
parse_status: "complete",
}),
}),
]),
);
if (retainGraph) expect(failures).toEqual([]);
expect(await readFile(join(root, name), "utf8")).toBe(text);
if (!retainGraph && name === "a-large.mjs") {
const failure = z
.object({
code: z.literal("resource_constraint"),
remediation: z.object({ action: z.string() }),
details: z.object({
reported_limits: z.object({
parent_available_result_budget_bytes: z.number(),
module_retention_estimate_bytes: z.number(),
graph_retention_estimate_bytes: z.number(),
}),
}),
})
.parse(failures[0]);
const limits = failure.details.reported_limits;
expect(
limits.module_retention_estimate_bytes +
limits.graph_retention_estimate_bytes,
).toBeGreaterThan(limits.parent_available_result_budget_bytes);
expect(failure.remediation.action).toContain("parent result budget");
expect(failure.remediation.action).toContain(
"retained static and module facts",
);
}
}
expect(response.stderr).not.toMatch(/FATAL ERROR:.*heap/iu);
},
);
@@ -13,6 +13,11 @@ import { cliTest } from "../../support/cli/cliFixture.js";
const literalAliases = ["#/x", "#x%2Fy", "#x%2Ey", "#x\\y", "#x\0y"];
const fallbackAliases = {
"#tab-escape": ["./.\t./outside.cjs", "./config.cjs"],
"#newline-escape": ["./.%\n2e/outside.cjs", "./config.cjs"],
"#normalized-url": "./con\tfig.cjs",
"#trimmed-url": "./config.cjs \t",
"#url-suffix": "./config.cjs?selected=one#fragment",
"#inactive-array": {
node: [{ browser: "./browser.cjs" }],
default: "./config.cjs",
@@ -30,29 +35,53 @@ const fallbackAliases = {
};
const resolvedAliases = [...literalAliases, ...Object.keys(fallbackAliases)];
const refusedAliases = {
"#empty": { target: [], limitation: "an empty imports target array" },
"#empty": {
target: [],
status: "external",
limitation: "an empty imports target array",
},
"#empty-active": {
target: { node: [] },
status: "external",
limitation: "an empty imports target array",
},
"#null-last": {
target: [[], null],
status: "external",
limitation: "an explicit null imports target",
},
"#empty-last": {
target: [null, []],
status: "external",
limitation: "an empty imports target array",
},
"#inactive": {
target: [{ browser: "./browser.cjs" }],
status: "external",
limitation: "it declares browser.",
},
"#nested-inactive": {
status: "external",
target: [
[{ browser: "./browser.cjs" }, { "rea-inactive": "./inactive.cjs" }],
],
limitation: "it declares browser, rea-inactive.",
},
"#escape": {
target: "./.\t./outside.cjs",
status: "rejected",
limitation: "escapes the package root",
},
"#encoded-separator": {
target: ["./con%2ffig.cjs", "./config.cjs"],
status: "rejected",
limitation: "separator bytes",
},
"#missing-url": {
target: ["./miss\ting.cjs", "./config.cjs"],
status: "not-found",
limitation: JSON.stringify("./miss\ting.cjs"),
},
};
const allAliases = [...resolvedAliases, ...Object.keys(refusedAliases)];
@@ -168,7 +197,9 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
const imports = graph.edges.filter(
({ properties }) => properties.module_link_kind === "require",
);
for (const [specifier, { limitation }] of Object.entries(refusedAliases))
for (const [specifier, { status, limitation }] of Object.entries(
refusedAliases,
))
for (const [moduleKind, sourcePath, source] of [
["require", "main.cjs", mainSource],
["import", "main.mjs", moduleSource],
@@ -179,7 +210,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
module_link_kind: moduleKind,
specifier,
resolved_path: null,
resolution_status: "external",
resolution_status: status,
}),
evidence: sourceEvidence(sourcePath, source, limitation),
}),
@@ -0,0 +1,94 @@
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { expect } from "vitest";
import { parseEvidence } from "../../src/domain/evidence.js";
import { buildManagedMemberPointerFixture } from "../../src/dotnet/ManagedPe.fixture.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
cliTest(
"CLI and stdio MCP retain physical member identities through reordered pointers",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-managed-member-pointers-");
const path = join(root, "reordered.dll");
const bytes = buildManagedMemberPointerFixture();
const sha256 = createHash("sha256").update(bytes).digest("hex");
await writeFile(path, bytes);
const transport = new StdioClientTransport({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
cwd: process.cwd(),
env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" },
stderr: "pipe",
});
transport.stderr?.on("data", () => undefined);
const client = new Client({ name: "managed-pointer-parity", version: "1" });
try {
await client.connect(transport);
for (const name of [
"inspect_managed_artifact",
"inspect_managed_members",
] as const) {
const cliResult = await cli.run({
arguments: [name.replaceAll("_", "-"), path, "--json"],
});
expect(cliResult.exitCode, cliResult.stderr).toBe(0);
const cliEvidence = parseEvidence(cliResult.json);
const response = await client.callTool({ name, arguments: { path } });
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const mcpEvidence = parseEvidence(response.structuredContent);
expect(mcpEvidence.normalized_result).toEqual(
cliEvidence.normalized_result,
);
expect(mcpEvidence.subject?.digest.sha256).toBe(sha256);
expect(cliEvidence.subject?.digest.sha256).toBe(sha256);
expect(mcpEvidence.normalized_result).toMatchObject({
coverage: { state: "complete", issues: [] },
});
if (name === "inspect_managed_artifact") {
expect(mcpEvidence.normalized_result).toMatchObject({
attributes: [
expect.objectContaining({
constructor_token: "0x06000001",
type_name: "Fixture.B",
}),
],
});
} else {
expect(mcpEvidence.normalized_result).toMatchObject({
fields: [
expect.objectContaining({
token: "0x04000001",
declaring_type: "Fixture.B",
}),
expect.objectContaining({
token: "0x04000002",
declaring_type: "Fixture.A",
}),
],
methods: [
expect.objectContaining({
token: "0x06000001",
declaring_type: "Fixture.B",
}),
expect.objectContaining({
token: "0x06000002",
declaring_type: "Fixture.A",
}),
],
});
}
}
} finally {
try {
await client.close();
} finally {
await transport.close();
}
}
},
);
@@ -0,0 +1,84 @@
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { expect } from "vitest";
import { parseEvidence } from "../../src/domain/evidence.js";
import { buildManagedPeFixture } from "../../src/dotnet/ManagedPe.fixture.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
cliTest(
"CLI and stdio MCP inspect CLR ExtraData metadata without shifting table identities",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-managed-extra-data-");
const path = join(root, "extra-data.dll");
const bytes = buildManagedPeFixture({ metadataExtraData: 0x1234_5678 });
const sha256 = createHash("sha256").update(bytes).digest("hex");
await writeFile(path, bytes);
const transport = new StdioClientTransport({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
cwd: process.cwd(),
env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" },
stderr: "pipe",
});
transport.stderr?.on("data", () => undefined);
const client = new Client({
name: "managed-extra-data-parity",
version: "1",
});
try {
await client.connect(transport);
for (const name of [
"inspect_managed_artifact",
"inspect_managed_members",
] as const) {
const cliResult = await cli.run({
arguments: [name.replaceAll("_", "-"), path, "--json"],
});
expect(cliResult.exitCode, cliResult.stderr).toBe(0);
const cliEvidence = parseEvidence(cliResult.json);
const response = await client.callTool({ name, arguments: { path } });
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const mcpEvidence = parseEvidence(response.structuredContent);
expect(mcpEvidence.normalized_result).toEqual(
cliEvidence.normalized_result,
);
expect(mcpEvidence.subject?.digest.sha256).toBe(sha256);
expect(cliEvidence.subject?.digest.sha256).toBe(sha256);
expect(mcpEvidence.normalized_result).toMatchObject({
module: {
name: "Fixture.dll",
mvid: "00112233-4455-6677-8899-aabbccddeeff",
},
coverage: { state: "complete", issues: [] },
});
if (name === "inspect_managed_artifact") {
expect(mcpEvidence.normalized_result).toMatchObject({
assembly: { name: "Fixture.Managed" },
});
} else {
expect(mcpEvidence.normalized_result).toMatchObject({
types: [expect.objectContaining({ full_name: "Fixture.Program" })],
methods: [
expect.objectContaining({
token: "0x06000001",
name: "Main",
declaring_type: "Fixture.Program",
}),
],
});
}
}
} finally {
try {
await client.close();
} finally {
await transport.close();
}
}
},
);
@@ -0,0 +1,156 @@
import { access, readFile, readdir, writeFile } from "node:fs/promises";
import { join, relative, resolve } from "node:path";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"skill-only setup verifies its selected client copy on install, rerun and repair",
async ({ cli }) => {
const directory = await createTestTempDirectory("rea-selected-skill-");
const selected = join(
directory,
".claude/skills/reverse-engineer-anything",
);
const shared = join(directory, ".agents/skills/reverse-engineer-anything");
const run = (args: readonly string[]) =>
cli.run({
arguments: [...args, "--json"],
cwd: directory,
environment: { USERPROFILE: directory },
});
const preview = await run([
"setup",
"--skill-client",
"claude_code",
"--dry-run",
]);
expect(preview.exitCode, preview.stdout).toBe(0);
expect(preview.json).toMatchObject({
status: "planned",
doctor: {
scope: {
clients: [],
skill: true,
skill_clients: ["claude_code"],
},
},
});
const registered = await run([
"setup",
"--client",
"claude_code",
"--skill=false",
"--yes",
]);
expect(registered.exitCode, registered.stderr).toBe(0);
const configuration = join(directory, ".claude.json");
const before = await readFile(configuration, "utf8");
const args = ["setup", "--skill-client", "claude_code", "--yes"];
const installed = await run(args);
expect(installed.exitCode, installed.stdout).toBe(0);
expect(installed.json).toMatchObject({
status: "ready",
appliedActions: ["installed_skill"],
doctor: {
healthy: true,
scope: { clients: [], skill: true, skill_clients: ["claude_code"] },
identity: { skill: { state: "aligned" } },
},
});
const bundle = resolve("skills/reverse-engineer-anything");
const assertAligned = async () => {
for (const entry of await readdir(bundle, {
recursive: true,
withFileTypes: true,
})) {
if (!entry.isFile()) continue;
const path = relative(bundle, join(entry.parentPath, entry.name));
expect(await readFile(join(selected, path))).toEqual(
await readFile(join(bundle, path)),
);
}
};
await assertAligned();
const repeated = await run(args);
expect(repeated.exitCode, repeated.stdout).toBe(0);
expect(repeated.json).toMatchObject({
status: "ready",
appliedActions: [],
});
await writeFile(
join(selected, "references/native-and-artifacts.md"),
"damaged selected copy\n",
);
const damaged = await run(["doctor", "--client", "claude_code", "--skill"]);
expect(damaged.json).toMatchObject({
healthy: false,
identity: { skill: { state: "stale" } },
});
const repaired = await run(args);
expect(repaired.exitCode, repaired.stdout).toBe(0);
expect(repaired.json).toMatchObject({
status: "ready",
appliedActions: ["installed_skill"],
});
await assertAligned();
await expect(access(shared)).rejects.toMatchObject({ code: "ENOENT" });
expect(await readFile(configuration, "utf8")).toBe(before);
const sharedControl = await run([
"setup",
"--skill-client",
"shared",
"--yes",
]);
expect(sharedControl.exitCode, sharedControl.stdout).toBe(0);
expect(sharedControl.json).toMatchObject({ status: "ready" });
await access(join(shared, "SKILL.md"));
},
);
cliTest(
"setup keeps registration and skill readiness selections independent",
async ({ cli }) => {
const directory = await createTestTempDirectory("rea-independent-skill-");
const result = await cli.run({
arguments: [
"setup",
"--client",
"codex",
"--skill-client",
"claude_code",
"--yes",
"--json",
],
cwd: directory,
environment: { USERPROFILE: directory },
});
expect(result.exitCode, result.stdout).toBe(0);
expect(result.json).toMatchObject({
status: "ready",
doctor: {
healthy: true,
scope: {
clients: ["codex"],
skill_clients: ["claude_code"],
skill: true,
},
identity: { skill: { state: "aligned" } },
},
});
await access(join(directory, ".codex/config.toml"));
await access(
join(directory, ".claude/skills/reverse-engineer-anything/SKILL.md"),
);
await expect(access(join(directory, ".claude.json"))).rejects.toMatchObject(
{ code: "ENOENT" },
);
await expect(
access(join(directory, ".agents/skills/reverse-engineer-anything")),
).rejects.toMatchObject({ code: "ENOENT" });
},
);
@@ -91,6 +91,42 @@ const pathRequests: readonly [string, Record<string, unknown>][] = [
),
["capture_electron_scenario", { ...electron, args: ["a\0b"] }],
["demangle_swift", { symbols: ["abc\0def"] }],
["inspect_web_network_capture", { capture_path: nul, format: "har" }],
[
"export_web_scripts",
{ capture_path: nul, output_directory: "/tmp/exported-scripts" },
],
[
"export_web_scripts",
{ capture_path: "/tmp/capture.json", output_directory: nul },
],
[
"trace_web_source_location",
{
manifest_path: nul,
script_index: 0,
source_map: { path: "/tmp/source.map", url: "http://127.0.0.1/a" },
generated_position: { line: 1, column: 0 },
},
],
[
"trace_web_source_location",
{
manifest_path: "/tmp/manifest.json",
script_index: 0,
source_map: { path: nul, url: "http://127.0.0.1/a" },
generated_position: { line: 1, column: 0 },
},
],
["trace_web_module_imports", { manifest_path: nul, script_index: 0 }],
[
"trace_web_module_imports",
{
manifest_path: "/tmp/manifest.json",
script_index: 0,
import_map: { path: nul, base_url: "http://127.0.0.1/a" },
},
],
];
it("rejects OS-invalid local inputs through the real advertised MCP contracts", async () => {
@@ -446,6 +446,92 @@ describe("web capture WebSocket payload byte coverage", () => {
});
describe("web capture diff", () => {
it("treats unavailable HTTP response facts as unknown while retaining observed changes", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
const captured = await new CdpBrowserProvider().inspectPage(
inspectWebPageInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
observation_ms: 0,
}),
);
if (!captured.ok) throw captured.error;
const before = structuredClone(captured.value);
const request = before.network.requests[0];
if (request === undefined) throw new Error("Missing network request");
request.status = null;
request.mime_type = null;
request.encoded_data_length = null;
markSectionsComplete(before, [
"network_requests",
"websocket_connections",
"websocket_frames",
"json_body_shapes",
]);
for (const item of before.network.requests)
item.body_shapes.status = "not_approved";
const after = structuredClone(before);
const responseObserved = after.network.requests[0];
if (responseObserved === undefined)
throw new Error("Missing network request");
responseObserved.status = 200;
responseObserved.mime_type = "application/json";
responseObserved.encoded_data_length = 100;
expect(compareNetwork(before, after)).toMatchObject({
status: "unknown",
total_changes: 0,
changes: [],
});
expect(compareNetwork(after, before)).toMatchObject({
status: "unknown",
total_changes: 0,
});
expect(compareNetwork(before, before).status).toBe("unknown");
for (const field of [
"status",
"mime_type",
"encoded_data_length",
] as const) {
const partial = structuredClone(after);
partial.network.requests[0]![field] = null;
expect(compareNetwork(partial, after).status).toBe("unknown");
expect(compareNetwork(after, partial).status).toBe("unknown");
}
const inventoryBefore = structuredClone(before);
inventoryBefore.network.requests = [];
expect(compareNetwork(inventoryBefore, before)).toMatchObject({
status: "changed",
total_changes: 1,
changes: [expect.objectContaining({ change: "added" })],
});
const statusChanged = structuredClone(after);
statusChanged.network.requests[0]!.status = 500;
expect(compareNetwork(after, statusChanged)).toMatchObject({
status: "changed",
changes: [expect.objectContaining({ change: "modified" })],
});
after.network.requests[0]!.encoded_data_length = null;
expect(compareNetwork(after, statusChanged).status).toBe("changed");
const repeated = structuredClone(statusChanged);
const duplicate = structuredClone(repeated.network.requests[0]!);
duplicate.status = 200;
duplicate.mime_type = "text/plain";
repeated.network.requests.push(duplicate);
const reassociated = structuredClone(repeated);
reassociated.network.requests[0]!.mime_type = "text/plain";
reassociated.network.requests.at(-1)!.mime_type = "application/json";
expect(compareNetwork(repeated, reassociated).status).toBe("changed");
repeated.network.requests[0]!.status = null;
expect(compareNetwork(repeated, reassociated).status).toBe("unknown");
});
it("ignores transient request IDs and capture-approval state", async () => {
const browser = await startFakeCdpBrowser();
browsers.push(browser);
+27 -8
View File
@@ -1,6 +1,9 @@
import { expect, it } from "vitest";
import { serveCli as serve } from "./cliServeHarness.js";
import {
expectConfigurationRefusal,
serveCli as serve,
} from "./cliServeHarness.js";
it.each([
["inspect-adb-client"],
@@ -34,13 +37,29 @@ it.each([
expect(schema).toBeTruthy();
});
it("reports a missing adb binary with recovery guidance", async () => {
const result = await serve(["inspect-adb-client", "--json"], {
REA_ADB_PATH: "/nonexistent/adb",
});
expect(result.stdout).toContain("capability_unavailable");
expect(result.stdout).toContain("REA_ADB_PATH");
});
it.each([
[
["inspect-adb-client", "--json"],
"/nonexistent/adb",
"The selected adb binary was not found: /nonexistent/adb. Set REA_ADB_PATH",
],
[
["list-adb-devices", "--json"],
"/nonexistent/adb",
"The selected adb binary was not found: /nonexistent/adb. Set REA_ADB_PATH",
],
[
["list-adb-devices", "--json"],
"relative/adb",
"REA_ADB_PATH must be an absolute path to the adb binary.",
],
])(
"%j with REA_ADB_PATH=%s names the host requirement",
async (argv, binary, reason) => {
const result = await serve(argv, { REA_ADB_PATH: binary });
expectConfigurationRefusal(result, reason);
},
);
it("validates device serials before contacting any device", async () => {
const result = await serve(["inspect-adb-device", "bad serial", "--json"]);
+27 -8
View File
@@ -1,6 +1,9 @@
import { expect, it } from "vitest";
import { serveCli as serve } from "./cliServeHarness.js";
import {
expectConfigurationRefusal,
serveCli as serve,
} from "./cliServeHarness.js";
it.each(["inspect-apktool-client", "decode-android-resources"])(
"%s advertises a schema through the public CLI",
@@ -12,13 +15,29 @@ it.each(["inspect-apktool-client", "decode-android-resources"])(
},
);
it("reports a missing apktool launcher with recovery guidance", async () => {
const result = await serve(["inspect-apktool-client", "--json"], {
REA_APKTOOL_COMMAND: "/nonexistent/apktool",
});
expect(result.stdout).toContain("capability_unavailable");
expect(result.stdout).toContain("REA_APKTOOL_COMMAND");
});
it.each([
[
["inspect-apktool-client", "--json"],
"/nonexistent/apktool",
"The selected apktool launcher was not found: /nonexistent/apktool. Set REA_APKTOOL_COMMAND",
],
[
["decode-android-resources", "/targets/app.apk", "--json"],
"/nonexistent/apktool",
"The selected apktool launcher was not found: /nonexistent/apktool. Set REA_APKTOOL_COMMAND",
],
[
["decode-android-resources", "/targets/app.apk", "--json"],
"relative/apktool",
"REA_APKTOOL_COMMAND must be an absolute path to the apktool launcher.",
],
])(
"%j with REA_APKTOOL_COMMAND=%s names the host requirement",
async (argv, command, reason) => {
const result = await serve(argv, { REA_APKTOOL_COMMAND: command });
expectConfigurationRefusal(result, reason);
},
);
it("validates the locale option before launching apktool", async () => {
const result = await serve([
+17
View File
@@ -1,3 +1,5 @@
import { expect } from "vitest";
import { createCli } from "../../../src/cli.js";
/** Captured CLI invocation for boundary tests. */
@@ -25,3 +27,18 @@ export const serveCli = async (
});
return { stdout, exitCode };
};
/** A host tool configuration refusal names what to configure, not the target. */
export const expectConfigurationRefusal = (
result: ServedCli,
reason: string,
): void => {
const output = JSON.parse(result.stdout) as {
code?: unknown;
message?: unknown;
remediation?: { action?: unknown };
};
expect(output.code).toBe("capability_unavailable");
expect(output.message).toEqual(expect.stringContaining(reason));
expect(output.remediation?.action).toEqual(expect.stringContaining(reason));
};
@@ -11,6 +11,78 @@ import {
writeFixtureFiles,
} from "../../support/javascriptApplicationFixture.js";
cliTest(
"resolves emitted module imports without substituting Electron runtime paths",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-typescript-runtime-paths-");
await writeFixtureFiles(root, {
"package.json": JSON.stringify({ main: "main.ts" }),
"main.ts": `import { BrowserWindow, utilityProcess } from "electron";
import "./worker.js";
import "./config.mjs";
import "./legacy.cjs";
import "./view.js";
import "./runtime.js";
const win = new BrowserWindow({webPreferences:{preload:"./worker.js"}});
win.loadURL("./renderer.js");
utilityProcess.fork("./worker.js");
utilityProcess.fork("./runtime.js");
throw new Error("source must stay inert");`,
"worker.ts": "export const worker = 1;",
"config.mts": "export const config = 1;",
"legacy.cts": "export const legacy = 1;",
"view.tsx": "export const view = <div />;",
"renderer.ts": "export const renderer = 1;",
"runtime.ts": "export const source = 1;",
"runtime.js": "throw new Error('runtime must stay inert');",
});
const output = await cli.run({
arguments: ["analyze-javascript-application", root, "--json"],
});
expect(output.exitCode, output.stderr).toBe(0);
const result = javascriptApplicationAnalysisResultSchema.parse(
parseEvidence(output.json).normalized_result,
);
const { graph } = result;
const source = findSourceModule(graph, "main.ts");
for (const [specifier, target] of [
["./worker.js", "worker.ts"],
["./config.mjs", "config.mts"],
["./legacy.cjs", "legacy.cts"],
["./view.js", "view.tsx"],
["./runtime.js", "runtime.js"],
] as const)
expect(
findGraphEdge(graph, source, findSourceModule(graph, target), "imports")
?.properties,
).toMatchObject({ specifier, resolved_path: target });
expect(result.summary).toMatchObject({
utility_processes: 2,
resolved_utility_entrypoints: 1,
});
expect(
graph.edges.find(
(edge) =>
edge.evidence.extractor.operation ===
"associate-browser-window-preload",
)?.properties,
).toMatchObject({
declared_path: "./worker.js",
resolved_path: null,
resolution_status: "not-found",
});
expect(
graph.edges
.filter(
(edge) =>
edge.properties.declared_path === "./worker.js" ||
edge.properties.declared_path === "./renderer.js",
)
.some((edge) => edge.properties.resolved_path != null),
).toBe(false);
},
);
cliTest(
"returns literal self-import evidence while preserving sibling imports and self-re-exports",
async ({ cli }) => {
@@ -75,7 +147,7 @@ cliTest(
);
cliTest(
"discloses CommonJS and TypeScript self-imports while retaining unresolved extension rewrites",
"discloses CommonJS and TypeScript self-imports including emitted-name rewrites",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-self-require-");
await writeFixtureFiles(root, {
@@ -94,8 +166,10 @@ cliTest(
expect(
graph.edges.filter((edge) => edge.source_node_id === edge.target_node_id),
).toEqual([]);
// ./util.ts is a literal self-import and ./util.js resolves under NodeNext
// emitted-name semantics back to util.ts itself, as ./c.cjs does for CJS.
expect(graph.limitations).toContainEqual(
expect.stringMatching(/^2 import specifiers .*were omitted;/u),
expect.stringMatching(/^3 import specifiers .*were omitted;/u),
);
expect(result.limitations).toEqual(
expect.arrayContaining(graph.limitations),
@@ -128,12 +202,21 @@ cliTest(
).toBe(false);
}
expect(
graph.edges.find(
graph.edges.some(
(edge) =>
edge.source_node_id === findSourceModule(graph, "util.ts")?.node_id &&
edge.properties.specifier === "./util.js" &&
edge.properties.module_link_kind === "import",
)?.properties,
).toMatchObject({ resolved_path: null, resolution_status: "not-found" });
(edge.properties.module_link_kind === "import" ||
edge.properties.resolution_status === "not-found"),
),
).toBe(false);
expect(
graph.nodes.some((node) =>
node.observations.some(
({ properties }) =>
properties.semantic_role === "module-reference" &&
properties.declared_specifier === "./util.js",
),
),
).toBe(false);
},
);
+137 -2
View File
@@ -1,4 +1,4 @@
import { execFile } from "node:child_process";
import { execFile, spawn } from "node:child_process";
import {
chmod,
mkdir,
@@ -172,6 +172,99 @@ describe("curl installer scenarios", { timeout: 20_000 }, () => {
});
});
describe("truncated installer download", { timeout: 20_000 }, () => {
it("runs nothing from a download truncated after the npm install line", async () => {
const fixture = await createFixture();
const source = await readFile(join(process.cwd(), "install.sh"), "utf8");
const installLine = source.indexOf('npm "${install_args[@]}" ||');
expect(installLine).toBeGreaterThan(0);
const truncated = join(fixture.home, "..", "install-truncated.sh");
await writeFile(
truncated,
source.slice(0, source.indexOf("\n", installLine) + 1),
);
const failure: unknown = await runInstaller(
fixture,
["--version", "0.3.0", "--no-setup"],
{},
truncated,
).then(
() => undefined,
(error: unknown) => error,
);
expect(failure).toBeInstanceOf(Error);
expect(getProcessOutput(failure, "stdout")).toBe("");
expect(getProcessOutput(failure, "stderr")).toContain("syntax error");
await expect(readFile(fixture.npmLog, "utf8")).rejects.toMatchObject({
code: "ENOENT",
});
});
});
describe(
"installer download truncated at any byte",
{
timeout: 180_000,
},
() => {
// Every prefix of the script, from the empty download to the full file, as
// `curl ... | bash -s -- --dry-run` would see it. Covers the preamble (a
// cut right after `set` would print every shell variable), the body, and
// the final invocation (a cut right after `main` would drop the flags).
it("runs nothing and prints nothing until the closing brace arrives", async () => {
const source = await readFile(join(process.cwd(), "install.sh"));
expect(source.subarray(0, 14).toString()).toBe("#!/bin/bash\n{\n");
const groupOpen = source.indexOf("\n{\n") + 2;
const groupEnd = source.lastIndexOf("\n}\n") + 2;
expect(groupEnd).toBe(source.length - 1);
expect(source.subarray(groupOpen, groupEnd).toString()).toContain(
"set -euo pipefail",
);
const fixture = await createFixture();
const offsets = Array.from(
{ length: source.length + 1 },
(_, offset) => offset,
);
const failures: string[] = [];
const check = async (offset: number): Promise<void> => {
const result = await runPipedInstaller(
fixture,
source.subarray(0, offset),
["--dry-run"],
{ SECRET_TOKEN: "inherited-secret" },
);
const context = `truncated at byte ${offset} after ${JSON.stringify(
source.subarray(Math.max(0, offset - 24), offset).toString(),
)}`;
if (offset >= groupEnd) {
if (result.code !== 0 || !result.stdout.includes("no changes made"))
failures.push(`${context}: complete script did not dry-run`);
return;
}
if (result.stdout !== "")
failures.push(`${context}: stdout ${JSON.stringify(result.stdout)}`);
if (offset >= groupOpen) {
if (result.code === 0) failures.push(`${context}: exit code 0`);
if (!/syntax error|unexpected EOF/u.test(result.stderr))
failures.push(
`${context}: stderr ${JSON.stringify(result.stderr)}`,
);
} else if (result.code !== 0 || result.stderr !== "")
failures.push(`${context}: preamble did not exit quietly`);
};
for (let index = 0; index < offsets.length; index += 16)
await Promise.all(offsets.slice(index, index + 16).map(check));
expect(failures).toEqual([]);
await expect(readFile(fixture.npmLog, "utf8")).rejects.toMatchObject({
code: "ENOENT",
});
await expect(readFile(fixture.reaLog, "utf8")).rejects.toMatchObject({
code: "ENOENT",
});
});
},
);
describe("Linux user-prefix installer", { timeout: 20_000 }, () => {
it("prints the executed arguments as a reusable command with shell metacharacters", async () => {
const fixture = await createFixture();
@@ -408,8 +501,9 @@ const runInstaller = async (
fixture: InstallerFixture,
args: readonly string[] = [],
overrides: Readonly<Record<string, string>> = {},
script = join(process.cwd(), "install.sh"),
): Promise<{ readonly stdout: string; readonly stderr: string }> =>
execFileAsync("/bin/bash", [join(process.cwd(), "install.sh"), ...args], {
execFileAsync("/bin/bash", [script, ...args], {
env: {
...process.env,
HOME: fixture.home,
@@ -423,5 +517,46 @@ const runInstaller = async (
},
});
/**
* Run the installer as `curl ... | bash -s -- ARGS` does: source on stdin.
* The environment is minimal and does not inherit the test runner's.
*/
const runPipedInstaller = async (
fixture: InstallerFixture,
source: Uint8Array,
args: readonly string[],
overrides: Readonly<Record<string, string>> = {},
): Promise<{
readonly code: number | null;
readonly stdout: string;
readonly stderr: string;
}> =>
new Promise((resolve, reject) => {
const child = spawn("/bin/bash", ["-s", "--", ...args], {
env: {
HOME: fixture.home,
TMPDIR: fixture.temporary,
PATH: `${fixture.bin}:/usr/bin:/bin`,
FAKE_NPM_LOG: fixture.npmLog,
FAKE_REA_LOG: fixture.reaLog,
FAKE_REA_SOURCE: join(fixture.bin, "rea-source"),
FAKE_NPM_PREFIX: join(fixture.home, ".npm-global"),
...overrides,
},
stdio: ["pipe", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
child.stdout.setEncoding("utf8").on("data", (chunk: string) => {
stdout += chunk;
});
child.stderr.setEncoding("utf8").on("data", (chunk: string) => {
stderr += chunk;
});
child.on("error", reject);
child.on("close", (code) => resolve({ code, stdout, stderr }));
child.stdin.end(source);
});
const shellQuote = (value: string): string =>
`'${value.replaceAll("'", `'"'"'`)}'`;
@@ -1,86 +0,0 @@
import { describe, expect } from "vitest";
import { inspectBundleKeyedArchive } from "../../../src/artifacts/apple/KeyedArchiveReader.js";
import { keyedArchiveResultSchema } from "../../../src/domain/apple/keyedArchive.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import {
keyedArchiveIntegerFormats,
keyedArchiveIntegerCases,
keyedArchiveIntegerFixtures,
expectKeyedArchiveIntegerCase,
type KeyedArchiveIntegerFixtures,
} from "../../fixtures/keyedArchiveIntegers.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import {
createTestWorkspace,
removeTestWorkspace,
} from "../../support/workspace/workspaceFixture.js";
const archiveTest = cliTest.extend<{
$worker: { keyedArchiveIntegerArchives: KeyedArchiveIntegerFixtures };
}>({
keyedArchiveIntegerArchives: [
// oxlint-disable-next-line no-empty-pattern -- Vitest parses fixture dependencies from object destructuring.
async ({}, use) => {
const workspace = await createTestWorkspace("rea-keyed-integers-");
try {
await use(await keyedArchiveIntegerFixtures(workspace.root));
} finally {
await removeTestWorkspace(workspace.root);
}
},
{ scope: "worker" },
],
});
const cases = keyedArchiveIntegerFormats.flatMap((format) =>
keyedArchiveIntegerCases.map((selectedCase) => ({ format, selectedCase })),
);
// Selected by the existing required native keyed-archive verifier, not Linux skips.
describe.skipIf(process.platform !== "darwin")(
"Foundation archive integer precision",
() => {
archiveTest.for(cases)(
"filesystem preserves $format $selectedCase numeric meaning",
async ({ format, selectedCase }, { keyedArchiveIntegerArchives }) => {
const fixture = keyedArchiveIntegerArchives[format];
const result = await inspectBundleKeyedArchive({
bundlePath: fixture.root,
targetSha256: fixture.digest,
parameters: { path: fixture.selected.filename, limit: 100 },
});
expectKeyedArchiveIntegerCase(
result,
selectedCase,
fixture.selected,
fixture.digest,
);
},
);
archiveTest.for(cases)(
"built CLI preserves $format $selectedCase numeric meaning",
async (
{ format, selectedCase },
{ cli, keyedArchiveIntegerArchives },
) => {
const fixture = keyedArchiveIntegerArchives[format];
const output = await cli.run({
arguments: ["inspect-keyed-archive", fixture.archivePath, "--json"],
environment: {
REA_LOG_LEVEL: "silent",
REA_ANALYSIS_PROVIDER: "auto",
},
});
expect(output.exitCode).toBe(0);
const result = keyedArchiveResultSchema.parse(
parseEvidence(output.json).normalized_result,
);
expectKeyedArchiveIntegerCase(
result,
selectedCase,
fixture.selected,
fixture.digest,
);
},
);
},
);
@@ -1,13 +1,72 @@
import { setImmediate } from "node:timers";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { expect, it, onTestFinished } from "vitest";
import { z } from "zod";
import {
ArtifactResourceScope,
type ArtifactResourceOwner,
} from "../../../src/artifacts/ArtifactResourceScope.js";
import { analyzeJavaScriptApplication as analyzeOwnedApplication } from "../../../src/application/javascript/JavaScriptApplicationService.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { analyzeJavaScriptApplication } from "../../support/javascriptApplicationScope.js";
it.each(["during cleanup", "on the next control turn"] as const)(
"retains the final source when cancellation arrives %s after analysis",
async (timing) => {
const root = await createTestTempDirectory("rea-js-cancel-handoff-");
await writeFile(
join(root, "main.js"),
'import { readFile } from "node:fs/promises"; export { readFile };\n',
);
const controller = new AbortController();
class CancellingCleanupScope extends ArtifactResourceScope {
override async release(owner: ArtifactResourceOwner) {
const result = await super.release(owner);
if (owner.kind === "javascript-source-analysis") {
if (timing === "during cleanup") controller.abort();
else setImmediate(() => controller.abort());
}
return result;
}
}
const scope = new CancellingCleanupScope();
onTestFinished(() => scope.close());
const result = await analyzeOwnedApplication(
{ input_path: root, format: "directory" },
scope,
{ signal: controller.signal },
);
if (result.ok) throw new Error("Cancelled handoff must not succeed");
const projected = projectAnalysisError(result.error);
expect(projected.code).toBe("cancelled");
const partial = z
.object({
details: z.object({
partial_observation: z.object({
normalized_result: javascriptApplicationAnalysisResultSchema,
}),
}),
})
.parse(projected).details.partial_observation.normalized_result;
expect(partial.statistics).toMatchObject({
relevant_files: 1,
parsed_javascript_files: 1,
parse_failures: 0,
});
expect(partial.graph.edges).toContainEqual(
expect.objectContaining({
properties: expect.objectContaining({
specifier: "node:fs/promises",
module_link_kind: "import",
}),
}),
);
},
);
it("preserves imported manifest status when cancelled before visiting manifests", async () => {
const root = await createTestTempDirectory("rea-js-cancel-package-");
const manifests = [
@@ -75,156 +134,169 @@ it("preserves imported manifest status when cancelled before visiting manifests"
});
});
describe("JavaScript application cancellation", () => {
it("interrupts semantic graph commitment before result validation", async () => {
const root = await createTestTempDirectory("rea-js-cancel-semantic-");
await writeFile(
join(root, "main.js"),
Array.from(
{ length: 500 },
(_, index) =>
`export function inspect${index}(value) { return JSON.stringify(value); }`,
).join("\n"),
);
const controller = new AbortController();
const phases: string[] = [];
const result = await analyzeJavaScriptApplication(
{ input_path: root, format: "directory" },
{
signal: controller.signal,
progress: {
async report(event) {
phases.push(event.phase);
if (event.phase === "seal_javascript_semantic_graph")
setImmediate(() => controller.abort());
},
it("interrupts semantic graph commitment before result validation", async () => {
const root = await createTestTempDirectory("rea-js-cancel-semantic-");
await writeFile(
join(root, "main.js"),
Array.from(
{ length: 500 },
(_, index) =>
`export function inspect${index}(value) { return JSON.stringify(value); }`,
).join("\n"),
);
const controller = new AbortController();
const phases: string[] = [];
const result = await analyzeJavaScriptApplication(
{ input_path: root, format: "directory" },
{
signal: controller.signal,
progress: {
async report(event) {
phases.push(event.phase);
if (event.phase === "seal_javascript_semantic_graph")
setImmediate(() => controller.abort());
},
},
},
);
if (result.ok)
throw new Error(
"Cancelled commitment must not publish a successful analysis",
);
if (result.ok)
throw new Error(
"Cancelled commitment must not publish a successful analysis",
);
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cancelled",
details: { reason: "cancelled" },
});
expect(phases).toContain("seal_javascript_semantic_graph");
expect(phases).not.toContain("validate_javascript_application_result");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cancelled",
details: { reason: "cancelled" },
});
expect(phases).toContain("seal_javascript_semantic_graph");
expect(phases).not.toContain("validate_javascript_application_result");
});
it("honors control turns and cancellation while preparing one large source for owned analysis (#1462)", async () => {
const root = await createTestTempDirectory("rea-js-cancel-in-file-");
await writeFile(
join(root, "index.js"),
Array.from(
{ length: 1200 },
(_, index) =>
`export function f${index}(){return {name:'f${index}',value:${index}};}`,
).join("\n"),
);
const controller = new AbortController();
const phases: string[] = [];
let turns = 0;
// Count event-loop turns once the file starts; parsing, analysis and
// projection of this one file must leave room for them.
const tick = (): void => {
turns += 1;
if (turns === 3) controller.abort();
else if (!controller.signal.aborted) setImmediate(tick);
};
const result = await analyzeJavaScriptApplication(
{ input_path: root, format: "directory" },
{
signal: controller.signal,
progress: {
async report(event) {
phases.push(event.phase);
if (event.phase === "parse_javascript_source") setImmediate(tick);
},
it("honors control turns and cancellation while preparing one large source for owned analysis (#1462)", async () => {
const root = await createTestTempDirectory("rea-js-cancel-in-file-");
await writeFile(
join(root, "index.js"),
Array.from(
{ length: 1200 },
(_, index) =>
`export function f${index}(){return {name:'f${index}',value:${index}};}`,
).join("\n"),
);
const controller = new AbortController();
const phases: string[] = [];
let turns = 0;
// Count event-loop turns once the file starts; parsing, analysis and
// projection of this one file must leave room for them.
const tick = (): void => {
turns += 1;
if (turns === 3) controller.abort();
else if (!controller.signal.aborted) setImmediate(tick);
};
const result = await analyzeJavaScriptApplication(
{ input_path: root, format: "directory" },
{
signal: controller.signal,
progress: {
async report(event) {
phases.push(event.phase);
if (event.phase === "parse_javascript_source") setImmediate(tick);
},
},
);
if (result.ok) throw new Error("Cancelled analysis must not succeed");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cancelled",
});
expect(phases).toContain("parse_javascript_source");
expect(phases).not.toContain("build_javascript_application_graph");
},
);
if (result.ok) throw new Error("Cancelled analysis must not succeed");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cancelled",
});
expect(phases).toContain("parse_javascript_source");
expect(phases).not.toContain("build_javascript_application_graph");
});
it.each([
"parse_javascript_source",
"build_javascript_application_graph",
"seal_javascript_application_graph",
"build_javascript_semantic_graph",
"seal_javascript_semantic_graph",
"validate_javascript_application_result",
"create_javascript_application_evidence",
"seal_javascript_application_result",
"validate_javascript_application_evidence",
"hash_javascript_application_evidence",
])("rejects cancellation scheduled during %s", async (phase) => {
const root = await createTestTempDirectory("rea-js-cancel-phase-");
await writeFile(
join(root, "main.js"),
"export function inspect(value) { return JSON.stringify(value); }\n",
);
const controller = new AbortController();
let requested = false;
const terminal: string[] = [];
const result = await analyzeJavaScriptApplication(
{ input_path: root, format: "directory" },
{
signal: controller.signal,
progress: {
async report(event) {
if (event.terminal) terminal.push(event.phase);
if (event.phase === phase) {
requested = true;
setImmediate(() => controller.abort());
}
it.each([
"parse_javascript_source",
"build_javascript_application_graph",
"seal_javascript_application_graph",
"build_javascript_semantic_graph",
"seal_javascript_semantic_graph",
"validate_javascript_application_result",
"create_javascript_application_evidence",
"seal_javascript_application_result",
"validate_javascript_application_evidence",
"hash_javascript_application_evidence",
])("rejects cancellation scheduled during %s", async (phase) => {
const root = await createTestTempDirectory("rea-js-cancel-phase-");
await writeFile(
join(root, "main.js"),
"export function inspect(value) { return JSON.stringify(value); }\n",
);
const controller = new AbortController();
let requested = false;
const terminal: string[] = [];
const result = await analyzeJavaScriptApplication(
{ input_path: root, format: "directory" },
{
signal: controller.signal,
progress: {
async report(event) {
if (event.terminal) terminal.push(event.phase);
if (event.phase === phase) {
requested = true;
setImmediate(() => controller.abort());
}
},
},
},
);
expect(requested).toBe(true);
if (result.ok) throw new Error("Cancelled analysis must return a failure");
const failure = projectAnalysisError(result.error);
expect(failure).toMatchObject({ code: "cancelled" });
expect(failure).toMatchObject({
details: {
operation: "analyze_javascript_application",
partial_observation: {
normalized_result: {
statistics: {
relevant_files: 1,
parsed_javascript_files:
phase === "parse_javascript_source" ? 0 : 1,
parse_failures: 0,
},
},
},
);
expect(requested).toBe(true);
if (result.ok) throw new Error("Cancelled analysis must return a failure");
const failure = projectAnalysisError(result.error);
expect(failure).toMatchObject({ code: "cancelled" });
if (phase === "parse_javascript_source")
expect(failure).toMatchObject({
details: {
operation: "analyze_javascript_application",
cleanup: "complete",
partial_observation: {
normalized_result: {
statistics: { relevant_files: 1, parse_failures: 0 },
},
},
},
});
expect(terminal).toEqual([]);
},
});
if (phase === "parse_javascript_source")
expect(failure.details).toMatchObject({ cleanup: "complete" });
expect(terminal).toEqual([]);
});
it("honors cancellation observed during the terminal publication race", async () => {
const root = await createTestTempDirectory("rea-js-cancel-terminal-");
await writeFile(join(root, "main.js"), "export const value = 1;\n");
const controller = new AbortController();
const result = await analyzeJavaScriptApplication(
{ input_path: root, format: "directory" },
{
signal: controller.signal,
progress: {
async report(event) {
if (event.terminal) controller.abort();
},
it("honors cancellation observed during the terminal publication race", async () => {
const root = await createTestTempDirectory("rea-js-cancel-terminal-");
await writeFile(join(root, "main.js"), "export const value = 1;\n");
const controller = new AbortController();
const result = await analyzeJavaScriptApplication(
{ input_path: root, format: "directory" },
{
signal: controller.signal,
progress: {
async report(event) {
if (event.terminal) controller.abort();
},
},
);
if (result.ok) throw new Error("Expected cancellation before admission");
expect(projectAnalysisError(result.error)).toMatchObject({
details: { reason: "cancelled" },
});
},
);
if (result.ok) throw new Error("Expected cancellation before admission");
const failure = projectAnalysisError(result.error);
expect(failure).toMatchObject({
details: { reason: "cancelled" },
});
expect(failure).toMatchObject({
details: {
partial_observation: {
normalized_result: {
statistics: { relevant_files: 1, parsed_javascript_files: 1 },
},
},
},
});
});
@@ -741,6 +741,51 @@ describe("nested and array package export targets", () => {
},
);
});
describe("package export target URL normalization compared with Node", () => {
it.each([
[["./.\t./outside.cjs", "./array.cjs"]],
[["./.%\n2e/outside.cjs", "./array.cjs"]],
[["./.\r./outside.cjs", "./array.cjs"]],
["./arr\tay.cjs"],
["./array.cjs \t"],
["./array.cjs?selected=one#fragment"],
["./.\t./example/array.cjs"],
] as const)(
"resolves normalized target %j through both loaders",
async (target) => {
for (const moduleKind of ["import", "require"] as const) {
const { node, outcome } = await compareWithNode(target, moduleKind);
expect(node).toBe("array.cjs");
expect(outcome).toMatchObject({
resolution_status: "resolved",
resolved_path: "node_modules/example/array.cjs",
});
}
},
);
it.each([
[["./arr%2fay.cjs", "./array.cjs"], "rejected"],
[["./miss\ting.cjs", "./array.cjs"], "not-found"],
] as const)(
"retains the first selected target failure in %j",
async (target, status) => {
for (const moduleKind of ["import", "require"] as const) {
const { node, node_error, outcome } = await compareWithNode(
target,
moduleKind,
);
expect(node).toBeNull();
expect(node_error).not.toBeNull();
expect(outcome).toMatchObject({
resolution_status: status,
resolved_path: null,
});
}
},
);
});
describe("unmatched package export conditions", () => {
it.each([
[[{ browser: "./default.cjs" }], "browser"],
@@ -455,6 +455,138 @@ describe("package import target arrays compared with Node", () => {
});
});
describe("package import target URL normalization compared with Node", () => {
it("normalizes targets before package-root validation and array selection", async () => {
const root = await createTestTempDirectory("rea-package-target-url-");
const directory = "app space#?%λ";
const imports = {
"#tab-escape": ["./.\t./outside.cjs", "./fallback.cjs"],
"#newline-escape": ["./.%\n2e/outside.cjs", "./fallback.cjs"],
"#cr-escape": ["./.\r./outside.cjs", "./fallback.cjs"],
"#normalized": "./fall\tback.cjs",
"#trimmed": "./fallback.cjs \t",
"#suffix": "./fallback.cjs?selected=one#fragment",
"#return": `./.\t./${encodeURIComponent(directory)}/fallback.cjs`,
};
const contents = await writeTree(root, {
[`${directory}/package.json`]: JSON.stringify({ imports }),
[`${directory}/main.cjs`]: "module.exports = 1;",
[`${directory}/fallback.cjs`]: "module.exports = 1;",
});
const inventoried = inventory(contents);
for (const specifier of Object.keys(imports)) {
const required = await nodeRequireTarget(
join(root, directory, "main.cjs"),
specifier,
);
expect(required.error_code, specifier).toBeNull();
expect(posixRelative(root, required.target ?? "")).toBe(
`${directory}/fallback.cjs`,
);
const imported = await nodeImportTarget(join(root, directory), specifier);
expect(imported.error_code, specifier).toBeNull();
expect(posixRelative(root, fileURLToPath(imported.target ?? ""))).toBe(
`${directory}/fallback.cjs`,
);
for (const moduleKind of ["require", "import"] as const)
expect(
resolveAlias(
inventoried,
specifier,
`${directory}/main.cjs`,
moduleKind,
),
specifier,
).toMatchObject({
declared_path: specifier,
resolution_status: "resolved",
resolved_path: `${directory}/fallback.cjs`,
});
}
});
it("keeps URL decoding and missing-file failures after array selection", async () => {
const root = await createTestTempDirectory(
"rea-package-target-url-refusal-",
);
const contents = await writeTree(root, {
"package.json": JSON.stringify({
imports: {
"#escape": "./.\t./outside.cjs",
"#separator": ["./fall%2fback.cjs", "./fallback.cjs"],
"#missing": ["./miss\ting.cjs", "./fallback.cjs"],
"#query-separator": ["./first.cjs?selected=%2f", "./fallback.cjs"],
},
}),
"main.cjs": "module.exports = 1;",
"fallback.cjs": "module.exports = 1;",
"first.cjs": "module.exports = 2;",
});
const inventoried = inventory(contents);
for (const [specifier, code] of [
["#escape", "ERR_INVALID_PACKAGE_TARGET"],
["#separator", "ERR_INVALID_MODULE_SPECIFIER"],
] as const) {
expect(
(await nodeRequireTarget(join(root, "main.cjs"), specifier)).error_code,
).toBe(code);
expect((await nodeImportTarget(root, specifier)).error_code).toBe(code);
for (const moduleKind of ["require", "import"] as const)
expect(
resolveAlias(inventoried, specifier, "main.cjs", moduleKind),
).toMatchObject({ resolution_status: "rejected", resolved_path: null });
}
expect(
(await nodeRequireTarget(join(root, "main.cjs"), "#missing")).error_code,
).toBe("MODULE_NOT_FOUND");
const imported = await nodeImportTarget(root, "#missing");
expect(posixRelative(root, fileURLToPath(imported.target ?? ""))).toBe(
"missing.cjs",
);
for (const moduleKind of ["require", "import"] as const)
expect(
resolveAlias(inventoried, "#missing", "main.cjs", moduleKind),
).toMatchObject({
resolution_status: "not-found",
resolved_path: null,
limitations: [expect.stringContaining("missing.cjs")],
});
expect(
resolveAlias(
inventoried,
"#escape",
"main.cjs",
"require",
).limitations.join(" "),
).toContain(JSON.stringify("./.\t./outside.cjs"));
expect(
(await nodeRequireTarget(join(root, "main.cjs"), "#query-separator"))
.error_code,
).toBe("ERR_INVALID_MODULE_SPECIFIER");
expect(
resolveAlias(inventoried, "#query-separator", "main.cjs", "require"),
).toMatchObject({ resolution_status: "rejected", resolved_path: null });
const withQuery = await nodeImportTarget(root, "#query-separator");
expect(posixRelative(root, fileURLToPath(withQuery.target ?? ""))).toBe(
"first.cjs",
);
expect(
resolveAlias(inventoried, "#query-separator", "main.cjs", "import"),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "first.cjs",
});
expect(
resolveAlias(
inventoried,
"#missing",
"main.cjs",
"require",
).limitations.join(" "),
).toContain(JSON.stringify("./miss\ting.cjs"));
});
});
describe("package import aliases compared with Node", () => {
it("matches Node require and import for an exact root alias", async () => {
const root = await createTestTempDirectory("rea-import-alias-root-");
@@ -12,128 +12,143 @@ import {
} from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("retains completed source facts and prior Evidence after SDK cancellation, then accepts subsequent work", async () => {
const root = await createTestTempDirectory("rea-mcp-js-cancellation-");
await writeFile(join(root, "main.js"), "export const observed = 1;\n");
await writeFile(join(root, "second.js"), "export const pending = 2;\n");
const session = createTestBinarySession(() => {
throw new Error(
"Static JavaScript analysis must not start a binary provider",
);
});
const prior = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: "prior_observation",
parameters: {},
result: { preserved: true },
},
);
expect(session.recordEvidence(prior).ok).toBe(true);
const completed = createDeferred<string>();
const completionSchema = z.object({
tool: z.string(),
status: z.string(),
msg: z.string(),
});
const logger = pino(
{ level: "info" },
{
write(line) {
const value: unknown = JSON.parse(line);
const parsed = completionSchema.safeParse(value);
if (
parsed.success &&
parsed.data.tool === "analyze_javascript_application" &&
parsed.data.msg === "MCP tool execution completed"
)
completed.resolve(parsed.data.status);
it.each([
{ phase: "parse_javascript_source", message: "second.js", parsedFiles: 1 },
{
phase: "analyze_javascript_application",
message: "Application graph and Electron boundaries reconstructed",
parsedFiles: 2,
},
])(
"retains completed facts and prior Evidence after SDK cancellation during $phase, then accepts subsequent work",
async ({ phase, message, parsedFiles }) => {
const root = await createTestTempDirectory("rea-mcp-js-cancellation-");
await writeFile(join(root, "main.js"), "export const observed = 1;\n");
await writeFile(join(root, "second.js"), "export const pending = 2;\n");
const session = createTestBinarySession(() => {
throw new Error(
"Static JavaScript analysis must not start a binary provider",
);
});
const prior = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{
operation: "prior_observation",
parameters: {},
result: { preserved: true },
},
},
);
const server = createServer({ kind: "session", session }, { logger });
const client = new Client({ name: "javascript-cancellation", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const controller = new AbortController();
let requested = false;
const call = client.callTool(
{
);
expect(session.recordEvidence(prior).ok).toBe(true);
const completed = createDeferred<string>();
const completionSchema = z.object({
tool: z.string(),
status: z.string(),
msg: z.string(),
});
const logger = pino(
{ level: "info" },
{
write(line) {
const value: unknown = JSON.parse(line);
const parsed = completionSchema.safeParse(value);
if (
parsed.success &&
parsed.data.tool === "analyze_javascript_application" &&
parsed.data.msg === "MCP tool execution completed"
)
completed.resolve(parsed.data.status);
},
},
);
const server = createServer({ kind: "session", session }, { logger });
const client = new Client({
name: "javascript-cancellation",
version: "1",
});
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const controller = new AbortController();
let requested = false;
const call = client.callTool(
{
name: "analyze_javascript_application",
arguments: {
input_path: root,
format: "directory",
},
},
{
signal: controller.signal,
onprogress(update) {
if (
!update.message?.startsWith(`${phase}:`) ||
!update.message.includes(message)
)
return;
requested = true;
controller.abort(new Error("SDK cancellation verification"));
},
},
);
await expect(call).rejects.toThrow("SDK cancellation verification");
expect(requested).toBe(true);
// A rejected client promise alone does not prove that the server stopped.
expect(await completed.promise).toBe("error");
await client.ping();
const bundle = await client.callTool({
name: "get_evidence_bundle",
arguments: {},
});
const records = z
.object({
result: z.object({
records: z.array(z.object({ evidence_id: z.string() })),
}),
})
.parse(bundle.structuredContent).result.records;
expect(records).toContainEqual({ evidence_id: prior.evidence_id });
const partial = records.find(
({ evidence_id }) => evidence_id !== prior.evidence_id,
);
if (partial === undefined)
throw new Error(
"Cancelled analysis discarded its completed source facts",
);
expect(
z
.object({
statistics: z.object({
parsed_javascript_files: z.number(),
parse_failures: z.number(),
}),
})
.parse(session.evidenceById(partial.evidence_id)?.normalized_result)
.statistics,
).toEqual({ parsed_javascript_files: parsedFiles, parse_failures: 0 });
const view = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "retained-evidence", evidence_id: partial.evidence_id },
view: { kind: "summary" },
},
});
expect(view.isError, JSON.stringify(view)).not.toBe(true);
const next = await client.callTool({
name: "analyze_javascript_application",
arguments: {
input_path: root,
format: "directory",
},
},
{
signal: controller.signal,
onprogress(update) {
if (
!update.message?.startsWith("parse_javascript_source:") ||
!update.message.includes("second.js")
)
return;
requested = true;
controller.abort(new Error("SDK cancellation verification"));
},
},
);
await expect(call).rejects.toThrow("SDK cancellation verification");
expect(requested).toBe(true);
// A rejected client promise alone does not prove that the server stopped.
expect(await completed.promise).toBe("error");
await client.ping();
const bundle = await client.callTool({
name: "get_evidence_bundle",
arguments: {},
});
const records = z
.object({
result: z.object({
records: z.array(z.object({ evidence_id: z.string() })),
}),
})
.parse(bundle.structuredContent).result.records;
expect(records).toContainEqual({ evidence_id: prior.evidence_id });
const partial = records.find(
({ evidence_id }) => evidence_id !== prior.evidence_id,
);
if (partial === undefined)
throw new Error("Cancelled analysis discarded its completed source facts");
expect(
z
.object({
statistics: z.object({
parsed_javascript_files: z.number(),
parse_failures: z.number(),
}),
})
.parse(session.evidenceById(partial.evidence_id)?.normalized_result)
.statistics,
).toEqual({ parsed_javascript_files: 1, parse_failures: 0 });
const view = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source: { kind: "retained-evidence", evidence_id: partial.evidence_id },
view: { kind: "summary" },
},
});
expect(view.isError, JSON.stringify(view)).not.toBe(true);
const next = await client.callTool({
name: "analyze_javascript_application",
arguments: {
input_path: root,
format: "directory",
},
});
expect(next.isError, JSON.stringify(next)).not.toBe(true);
await client.ping();
});
});
expect(next.isError, JSON.stringify(next)).not.toBe(true);
await client.ping();
},
);
+16 -14
View File
@@ -338,20 +338,22 @@ describe("tool result projection", () => {
const result = delivery.toCallToolResult(
err(
new HopperProcessError(80, {
component: "hopper_private_display",
operation: "launch",
status: "error",
failure_code: "x11_socket_directory_unusable",
reason: "socket_directory_read_only",
socket_directory: "/tmp/.X11-unix",
socket_directory_mode: "0777",
mount_read_only: true,
effective_socket_directory_mode: "1777",
effective_mount_read_only: false,
wsl: true,
strategy: "user-mount-namespace",
fallback_reason: null,
xvfb_stderr_bytes: 512,
diagnostic: {
component: "hopper_private_display",
operation: "launch",
status: "error",
failure_code: "x11_socket_directory_unusable",
reason: "socket_directory_read_only",
socket_directory: "/tmp/.X11-unix",
socket_directory_mode: "0777",
mount_read_only: true,
effective_socket_directory_mode: "1777",
effective_mount_read_only: false,
wsl: true,
strategy: "user-mount-namespace",
fallback_reason: null,
xvfb_stderr_bytes: 512,
},
}),
),
contract,
@@ -3,7 +3,6 @@ import { access } from "node:fs/promises";
import { afterEach, describe, expect, it } from "vitest";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
import { ok } from "../../../../src/domain/result.js";
import type {
BridgeLauncher,
@@ -53,31 +52,6 @@ class OwnedFixtureLauncher implements BridgeLauncher {
}
}
class UnconfirmedFixtureLauncher implements BridgeLauncher {
constructor(readonly ownsProcessLifetime = false) {}
launch(session: BridgeSession) {
return Promise.resolve(
ok({
process: spawn(
process.execPath,
[
fixturePath,
session.socketPath,
session.token,
session.runId,
"unconfirmed",
],
{ stdio: ["ignore", "ignore", "pipe"] },
),
ownsProcessLifetime: this.ownsProcessLifetime,
providerLifetime: "external-application" as const,
shutdownMode: "bridge-request" as const,
}),
);
}
}
const clients: HopperClient[] = [];
afterEach(async () => {
@@ -137,42 +111,6 @@ describe("HopperClient cleanup", () => {
});
});
it.each([
["unowned", false],
["owned helper", true],
] as const)(
"reports unconfirmed external document cleanup for an %s process",
async (_description, ownsProcessLifetime) => {
const client = new HopperClient({
launcher: new UnconfirmedFixtureLauncher(ownsProcessLifetime),
startupTimeoutMs: 1_000,
});
clients.push(client);
expect((await client.start()).ok).toBe(true);
const closed = await client.close();
expect(closed).toMatchObject({
ok: false,
error: {
_tag: "ProviderAdapterError",
cleanupIncomplete: true,
cleanupResources: expect.arrayContaining(["hopper-document"]),
},
});
if (!closed.ok)
expect(projectAnalysisError(closed.error)).toMatchObject({
code: "cleanup_incomplete",
details: {
provider_id: "hopper",
operation: "close_binary",
cleanup: "incomplete",
resources: expect.arrayContaining(["hopper-document"]),
},
});
},
);
it("kills only its owned Hopper group and emits sanitized shutdown coordinates", async () => {
const unrelated = spawn(
process.execPath,
@@ -160,50 +160,71 @@ it("retains failed startup cleanup until an owned process and its backing image
});
});
it("keeps an unconfirmed external document visible across sequential closes", async () => {
const launcher = new RetryCleanupLauncher(true);
const runtimeRoot = await PrivateRuntimeRoot.create();
onTestFinished(() => runtimeRoot.close());
const launched = await launcher.launch({
directory: runtimeRoot.path,
socketPath: join(runtimeRoot.path, "bridge.sock"),
token: "fixture-token",
runId: "fixture-run",
});
if (!launched.ok) throw launched.error;
const child = launched.value.process;
const supervisor = new ProviderProcessSupervisor(launched.value);
onTestFinished(() => supervisor.dispose());
const resources: HopperOwnedResources = {
launch: launched.value,
processSupervisor: supervisor,
runtimeRoot,
shutdownConfirmed: false,
};
for (let attempt = 0; attempt < 2; attempt += 1) {
await expect(
cleanupHopperSession({
socket: undefined,
resources,
activeRequest: null,
retainDocument: false,
progress: undefined,
logger: silentLogger,
onDiagnostic: undefined,
request: () => Promise.resolve(ok(null)),
releaseTransport: (socket) => socket?.destroy(),
}),
).resolves.toMatchObject({
ok: false,
error: { cleanupResources: ["hopper-document", runtimeRoot.path] },
it.each([false, true])(
"keeps an unconfirmed external document across closes when helper ownership is %s",
async (ownsHelper) => {
const launcher = new RetryCleanupLauncher(true);
const runtimeRoot = await PrivateRuntimeRoot.create();
onTestFinished(() => runtimeRoot.close());
const launched = await launcher.launch({
directory: runtimeRoot.path,
socketPath: join(runtimeRoot.path, "bridge.sock"),
token: "fixture-token",
runId: "fixture-run",
});
}
expect(child.exitCode).toBeNull();
expect(child.signalCode).toBeNull();
await expect(
access(join(runtimeRoot.path, "image.macho")),
).resolves.toBeUndefined();
});
if (!launched.ok) throw launched.error;
const child = launched.value.process;
const launch: BridgeLaunch = ownsHelper
? { ...launched.value, ownsProcessLifetime: true }
: launched.value;
const supervisor = new ProviderProcessSupervisor(launch);
onTestFinished(() => supervisor.dispose());
const resources: HopperOwnedResources = {
launch,
processSupervisor: supervisor,
runtimeRoot,
shutdownConfirmed: false,
};
const socket = new Socket();
onTestFinished(() => {
socket.destroy();
});
for (let attempt = 0; attempt < 2; attempt += 1) {
await expect(
cleanupHopperSession({
socket: attempt === 0 ? socket : undefined,
resources,
activeRequest: null,
retainDocument: false,
progress: undefined,
logger: silentLogger,
onDiagnostic: undefined,
request: () =>
Promise.resolve(
ok({
shutdown: true,
analysis_stopped: true,
document_closed: false,
}),
),
releaseTransport: (socket) => socket?.destroy(),
}),
).resolves.toMatchObject({
ok: false,
error: { cleanupResources: ["hopper-document", runtimeRoot.path] },
});
}
if (ownsHelper)
expect(child.exitCode !== null || child.signalCode !== null).toBe(true);
else {
expect(child.exitCode).toBeNull();
expect(child.signalCode).toBeNull();
}
await expect(
access(join(runtimeRoot.path, "image.macho")),
).resolves.toBeUndefined();
},
);
it("blocks a fresh launch while cleanup remains unverified", async () => {
const launcher = new RetryCleanupLauncher();
@@ -228,6 +249,32 @@ it("blocks a fresh launch while cleanup remains unverified", async () => {
});
});
it("preserves failed startup state through a blocked retry until cleanup succeeds", async () => {
const launcher = new RetryCleanupLauncher();
const { client } = await failedStartup(launcher);
// The startup timeout leaves the client in not_started with retained
// resources; cleanup is still incomplete.
expect(client.operationHealth()).toMatchObject({ state: "not_started" });
// An intervening retry is blocked by the retained resources, and now
// surfaces the recorded startup failure (upstream 069308bb) instead of
// a generic protocol error...
await expect(client.start()).resolves.toMatchObject({
ok: false,
error: {
_tag: "ProviderAdapterError",
cleanupIncomplete: true,
cause: { _tag: "HopperTimeoutError" },
},
});
// ...but must not wipe the failed-startup state: the client still
// reports not_started (never idle) until cleanup succeeds, so a
// same-target open_binary keeps retiring the wedged client instead of
// fast-pathing it.
expect(client.operationHealth()).toMatchObject({ state: "not_started" });
launcher.allowCleanup = true;
await expect(client.close()).resolves.toEqual({ ok: true, value: null });
});
it("permits a fresh launch after stopping an owned bridge-request provider without an acknowledgement", async () => {
const fixture = new RetryCleanupLauncher();
fixture.allowCleanup = true;

Some files were not shown because too many files have changed in this diff Show More