Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92fddf3176 | ||
|
|
9655845bbc | ||
|
|
12ee785e5e | ||
|
|
e59db2f5de | ||
|
|
d802304c54 | ||
|
|
0f4992fb9e | ||
|
|
72489a9445 | ||
|
|
b6651cb99f | ||
|
|
0b2aa69531 | ||
|
|
b5b73019f9 | ||
|
|
d0edeec100 | ||
|
|
3b490a743f | ||
|
|
3298219d8c | ||
|
|
b07e54a10e | ||
|
|
fb43dd9716 | ||
|
|
0485cd3bce | ||
|
|
c32d84622f | ||
|
|
601814ed0e | ||
|
|
dfe31172ca | ||
|
|
6407718f30 | ||
|
|
f8513a42dc | ||
|
|
a95795c6ed | ||
|
|
369cd3dfdc | ||
|
|
2976fac30d | ||
|
|
f598bab488 | ||
|
|
bb508134ef | ||
|
|
1dfb933e47 | ||
|
|
486b56724c | ||
|
|
499ac18011 |
@@ -9,7 +9,6 @@
|
||||
**See a feature you like. Understand how it works, down to the binary level.**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#what-you-can-analyze)
|
||||
[](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>
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
**وجدت ميزة تعجبك؟ افهم طريقة عملها حتى مستوى الشيفرة الثنائية.**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
**Eine Funktion gefällt dir? Verstehe, wie sie funktioniert – bis hinunter auf die Binärebene.**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
**¿Ves una función que te gusta? Entiende cómo funciona, hasta el nivel binario.**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
**قابلیتی دیدهاید که دوستش دارید؟ سازوکارش را تا سطح باینری درک کنید.**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
**Repérez une fonctionnalité qui vous plaît. Comprenez son fonctionnement, jusqu'au niveau du binaire.**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
**Melihat fitur yang Anda sukai. Pahami cara kerjanya hingga ke tingkat biner.**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
**Vedi una funzionalità che ti piace. Capisci come funziona, fino al livello binario.**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#cosa-puoi-analizzare)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
**気に入った機能を見つけたら、その仕組みをバイナリのレベルまで理解する。**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
**마음에 드는 기능을 발견했다면, 바이너리 수준까지 작동 원리를 이해하세요.**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
**Widzisz funkcję, która Ci się podoba? Dowiedz się, jak działa, aż do poziomu kodu binarnego.**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
**Viu uma funcionalidade de que gostou? Entenda como ela funciona, até o nível binário.**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
**Нашли интересную функцию? Разберитесь, как она работает, вплоть до двоичного кода.**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
**เห็นฟีเจอร์ที่ชอบแล้วอยากรู้ว่าทำงานอย่างไร? เข้าใจได้ลึกถึงระดับไบนารี**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -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.**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
**Побачили цікаву функцію? Зрозумійте, як вона працює, аж до рівня двійкового коду.**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -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.**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
**看到喜歡的功能,弄清它的工作原理,深入到二進位層面。**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](https://skills.sh/morluto/rea/reverse-engineer-anything)
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
**看到喜欢的功能,弄清它的工作原理,深入到二进制层面。**
|
||||
|
||||
[](https://www.npmjs.com/package/rea-agents)
|
||||
[](https://github.com/morluto/rea/actions/workflows/ci.yml)
|
||||
[](docs/mcp-contracts.md#generated-catalog)
|
||||
[](#current-status)
|
||||
[](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
@@ -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
|
||||
|
||||
@@ -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;
|
||||
@@ -350,14 +357,10 @@ creation. Arguments follow each actual callable invocation rather than property
|
||||
chain depth; rebinding retains the original bound receiver.
|
||||
Visibly replaced invocation intrinsics produce unknown effects instead
|
||||
of using their former call semantics; captured function aliases retain their
|
||||
earlier identity. Invocation member reads are checked separately from the earlier
|
||||
function capture. Comma-expression callees use their final value while all
|
||||
preceding expressions remain in the effect traversal. Call effects are
|
||||
classified after callee and argument effects have been collected. Unexamined
|
||||
targets remain unresolved. `Reflect.set` examines its explicit receiver as well
|
||||
as its target, retaining unknown receiver effects. Creating an unused binding
|
||||
does not itself mutate an intrinsic. Variable redeclarations retain a single
|
||||
unconditional initializer
|
||||
earlier identity. Unexamined targets remain unresolved. `Reflect.set` examines
|
||||
its explicit receiver as well as its target, retaining unknown receiver effects.
|
||||
Creating an unused binding does not itself mutate an intrinsic. Variable
|
||||
redeclarations retain a single unconditional initializer
|
||||
when they introduce no assignment or second initializer.
|
||||
Stable identifier chains to fresh object, array, function,
|
||||
undecorated class or RegExp syntax keep those targets separate from intrinsic
|
||||
@@ -486,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
|
||||
|
||||
@@ -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
@@ -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
@@ -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 $?
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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 α测试");
|
||||
|
||||
@@ -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", {});
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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 =
|
||||
| {
|
||||
|
||||
@@ -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[] = [
|
||||
{
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -232,6 +232,7 @@ describe("setup scoped readiness", () => {
|
||||
clients: ["codex"],
|
||||
providers: [],
|
||||
skill: true,
|
||||
skillClients: ["codex"],
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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}`);
|
||||
};
|
||||
@@ -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";
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ROLLDOWN_MODULE_INTEROP } from "./javascriptModuleInterop.fixture.js";
|
||||
import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
|
||||
|
||||
const CAPTURED_INTEROP = ROLLDOWN_MODULE_INTEROP.replace(
|
||||
"__defProp = Object.defineProperty",
|
||||
"__defProp = define",
|
||||
);
|
||||
const WINDOW = `let electron = require("electron");
|
||||
electron = __toESM(electron, 1); new electron.BrowserWindow({});`;
|
||||
|
||||
describe("captured intrinsic invocation reads", () => {
|
||||
it.each([
|
||||
'(0, Object.defineProperty.call)(null,Object,"create",{value:replacement});',
|
||||
'(0, Object.defineProperty.apply)(null,[Object,"create",{value:replacement}]);',
|
||||
])(
|
||||
"does not invent a receiver for a detached invocation member: %s",
|
||||
(invoke) => {
|
||||
const result = analyzeJavaScriptStaticSource(`
|
||||
${invoke}
|
||||
${ROLLDOWN_MODULE_INTEROP} ${WINDOW}
|
||||
`);
|
||||
expect(result.electron.browser_windows).toHaveLength(1);
|
||||
},
|
||||
);
|
||||
|
||||
it("retains callee-prefix effects before classifying the invocation", () => {
|
||||
const result = analyzeJavaScriptStaticSource(`
|
||||
const define = Object.defineProperty;
|
||||
const metadata = {};
|
||||
(Object.defineProperty = replacement, Object.defineProperty)(metadata,"x",{value:1});
|
||||
${CAPTURED_INTEROP} ${WINDOW}
|
||||
`);
|
||||
expect(result.electron.browser_windows).toEqual([]);
|
||||
});
|
||||
|
||||
it("retains a callee selected before an argument replaces its global property", () => {
|
||||
const result = analyzeJavaScriptStaticSource(`
|
||||
const define = Object.defineProperty;
|
||||
const metadata = {};
|
||||
Object.defineProperty(metadata,"x",(Object.defineProperty = replacement,{value:1}));
|
||||
${CAPTURED_INTEROP} ${WINDOW}
|
||||
`);
|
||||
expect(result.electron.browser_windows).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'define.call(null,metadata,"x",{value:1});',
|
||||
'define.apply(null,[metadata,"x",{value:1}]);',
|
||||
'const change = define.bind(null,metadata,"x"); change({value:1});',
|
||||
'const also = define; also.call(null,metadata,"x",{value:1});',
|
||||
])("retains a function captured before global replacement: %s", (invoke) => {
|
||||
const result = analyzeJavaScriptStaticSource(`
|
||||
const define = Object.defineProperty;
|
||||
Object.defineProperty = replacement;
|
||||
const metadata = {}; ${invoke}
|
||||
${CAPTURED_INTEROP} ${WINDOW}
|
||||
`);
|
||||
expect(result.electron.browser_windows).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["call", 'define.call(null,metadata,"x",{value:1});'],
|
||||
["apply", 'define.apply(null,[metadata,"x",{value:1}]);'],
|
||||
[
|
||||
"bind",
|
||||
'const change = define.bind(null,metadata,"x"); change({value:1});',
|
||||
],
|
||||
])(
|
||||
"checks the later %s property read on a captured function",
|
||||
(method, invoke) => {
|
||||
for (const owner of ["define", "Function.prototype"]) {
|
||||
const result = analyzeJavaScriptStaticSource(`
|
||||
const define = Object.defineProperty;
|
||||
${owner}.${method} = replacement;
|
||||
const metadata = {}; ${invoke}
|
||||
${CAPTURED_INTEROP} ${WINDOW}
|
||||
`);
|
||||
expect(result.electron.browser_windows, owner).toEqual([]);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -615,10 +615,6 @@ describe("Electron module interop bound mutators", () => {
|
||||
'Reflect.set({},"create",...valuesAndReceivers);',
|
||||
"Reflect.set({},...keysValuesAndReceivers);",
|
||||
'Reflect.set({},"create",customCreate,receiver);',
|
||||
'(0, Object.defineProperty)(Object,"create",{value:customCreate});',
|
||||
'const change = Object.defineProperty.bind(null,Object,"create"); (0, change)({value:customCreate});',
|
||||
'(0, Reflect.apply)(Object.defineProperty,null,[Object,"create",{value:customCreate}]);',
|
||||
'Reflect.apply((0,Function.prototype.call),Object.defineProperty,[null,Object,"create",{value:customCreate}]);',
|
||||
])("rejects intrinsic writes through a bound mutator: %s", (write) => {
|
||||
expect(
|
||||
analyzeJavaScriptStaticSource(
|
||||
@@ -645,7 +641,6 @@ describe("Electron module interop bound mutators", () => {
|
||||
'const {apply:change} = Object.defineProperty; change.call(Object.defineProperty,null,[metadata,"x",{value:1}]);',
|
||||
'Reflect.set(metadata,"x",1,{});',
|
||||
'const receiver = {}; Reflect.set({},"x",1,receiver);',
|
||||
'(0, Object.defineProperty)(metadata,"x",{value:1});',
|
||||
])("keeps a fresh bound target or unused binding separate: %s", (write) => {
|
||||
expect(
|
||||
analyzeJavaScriptStaticSource(
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -79,60 +79,60 @@ export function* collectJavaScriptIdentityWritesSteps(
|
||||
"setPrototypeOf",
|
||||
]);
|
||||
const keyedMutators = new Set(["set", "deleteProperty", "defineProperty"]);
|
||||
const retainCallEffects = (
|
||||
node: t.CallExpression | t.OptionalCallExpression,
|
||||
): void => {
|
||||
const invocation = intrinsicInvocation(node);
|
||||
if (invocation?.kind === "opaque") {
|
||||
const scope = origin(node, "opaque-call");
|
||||
if (scope !== undefined) retain(node, scope);
|
||||
return;
|
||||
}
|
||||
const callee = invocation?.path;
|
||||
const arguments_ = invocation?.arguments;
|
||||
const method = callee?.at(-1);
|
||||
const owner = callee?.length === 3 ? callee[1] : undefined;
|
||||
if (
|
||||
(owner === "Object" && objectMutators.has(method ?? "")) ||
|
||||
(owner === "Reflect" && reflectMutators.has(method ?? ""))
|
||||
) {
|
||||
// Reflect.set can write through its explicit receiver as well as
|
||||
// dispatching through its target. Both identities need examination.
|
||||
const targets =
|
||||
owner === "Reflect" &&
|
||||
method === "set" &&
|
||||
arguments_ !== undefined &&
|
||||
(arguments_.length >= 4 || arguments_.some(t.isSpreadElement))
|
||||
? [
|
||||
arguments_[0],
|
||||
arguments_.some(t.isSpreadElement) ? undefined : arguments_[3],
|
||||
]
|
||||
: [arguments_?.[0]];
|
||||
for (const target of targets) {
|
||||
// A known mutator with an opaque argument list can overwrite any
|
||||
// captured intrinsic. Do not turn an unexamined target into proof.
|
||||
if (target === undefined || t.isSpreadElement(target)) {
|
||||
yield* traverseJavaScriptAstSteps(program, {
|
||||
enter: (node) => {
|
||||
if (t.isCallExpression(node) || t.isOptionalCallExpression(node)) {
|
||||
const invocation = intrinsicInvocation(node);
|
||||
if (invocation?.kind === "opaque") {
|
||||
const scope = origin(node, "opaque-call");
|
||||
if (scope !== undefined) retain(node, scope);
|
||||
return;
|
||||
}
|
||||
if (t.isNode(target) && !t.isSpreadElement(target)) {
|
||||
const { root, members } = electronMemberPath(target);
|
||||
const exported = origin(root, "member");
|
||||
if (exported !== undefined) {
|
||||
const key = keyedMutators.has(method ?? "")
|
||||
? [staticString(arguments_?.[1]) ?? null]
|
||||
: [];
|
||||
retain(node, [...exported, ...members, ...key]);
|
||||
} else if (!freshObject(target)) {
|
||||
const scope = origin(node, "opaque-call");
|
||||
if (scope !== undefined) retain(node, scope);
|
||||
const callee = invocation?.path;
|
||||
const arguments_ = invocation?.arguments;
|
||||
const method = callee?.at(-1);
|
||||
const owner = callee?.length === 3 ? callee[1] : undefined;
|
||||
if (
|
||||
(owner === "Object" && objectMutators.has(method ?? "")) ||
|
||||
(owner === "Reflect" && reflectMutators.has(method ?? ""))
|
||||
) {
|
||||
// Reflect.set can write through its explicit receiver as well as
|
||||
// dispatching through its target. Both identities need examination.
|
||||
const targets =
|
||||
owner === "Reflect" &&
|
||||
method === "set" &&
|
||||
arguments_ !== undefined &&
|
||||
(arguments_.length >= 4 || arguments_.some(t.isSpreadElement))
|
||||
? [
|
||||
arguments_[0],
|
||||
arguments_.some(t.isSpreadElement)
|
||||
? undefined
|
||||
: arguments_[3],
|
||||
]
|
||||
: [arguments_?.[0]];
|
||||
for (const target of targets) {
|
||||
// A known mutator with an opaque argument list can overwrite any
|
||||
// captured intrinsic. Do not turn an unexamined target into proof.
|
||||
if (target === undefined || t.isSpreadElement(target)) {
|
||||
const scope = origin(node, "opaque-call");
|
||||
if (scope !== undefined) retain(node, scope);
|
||||
}
|
||||
if (t.isNode(target) && !t.isSpreadElement(target)) {
|
||||
const { root, members } = electronMemberPath(target);
|
||||
const exported = origin(root, "member");
|
||||
if (exported !== undefined) {
|
||||
const key = keyedMutators.has(method ?? "")
|
||||
? [staticString(arguments_?.[1]) ?? null]
|
||||
: [];
|
||||
retain(node, [...exported, ...members, ...key]);
|
||||
} else if (!freshObject(target)) {
|
||||
const scope = origin(node, "opaque-call");
|
||||
if (scope !== undefined) retain(node, scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
yield* traverseJavaScriptAstSteps(program, {
|
||||
enter: (node) => {
|
||||
const target = t.isAssignmentExpression(node)
|
||||
? node.left
|
||||
: t.isUpdateExpression(node)
|
||||
@@ -154,9 +154,5 @@ export function* collectJavaScriptIdentityWritesSteps(
|
||||
if (exported !== undefined) retain(node, [...exported, ...members]);
|
||||
}
|
||||
},
|
||||
exit: (node) => {
|
||||
if (t.isCallExpression(node) || t.isOptionalCallExpression(node))
|
||||
retainCallEffects(node);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -41,15 +41,6 @@ export const resolveJavaScriptIntrinsicInvocation = (
|
||||
let explicitReceiver = false;
|
||||
for (;;) {
|
||||
callee = unwrapJavaScriptExpression(callee).node;
|
||||
if (t.isSequenceExpression(callee)) {
|
||||
const finalExpression = callee.expressions.at(-1);
|
||||
if (finalExpression === undefined) return undefined;
|
||||
// Comma yields a value, not a member reference. An outer invocation
|
||||
// can still supply an explicit receiver for that value.
|
||||
explicitReceiver = true;
|
||||
callee = finalExpression;
|
||||
continue;
|
||||
}
|
||||
if (visited.has(callee)) return undefined;
|
||||
visited.add(callee);
|
||||
let path = intrinsicPath(callee);
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
type JavaScriptIntrinsicInvocation,
|
||||
} from "./javascriptElectronMemberWrites.js";
|
||||
import { resolveJavaScriptIntrinsicInvocation } from "./javascriptIntrinsicInvocation.js";
|
||||
import { semanticPropertyPathKeyMatches } from "./javascriptSemanticPropertyPaths.js";
|
||||
import { SemanticPropertyPathCoverage } from "./javascriptSemanticPropertyPaths.js";
|
||||
import {
|
||||
readExactJavaScriptLiteral,
|
||||
unwrapJavaScriptExpression,
|
||||
@@ -71,16 +71,6 @@ interface InteropHelper {
|
||||
readonly identity: boolean;
|
||||
}
|
||||
|
||||
const intrinsicWriteCovers = (
|
||||
written: readonly (string | null)[],
|
||||
read: readonly string[],
|
||||
): boolean =>
|
||||
written.length <= read.length &&
|
||||
written.every((key, index) => {
|
||||
const name = read[index];
|
||||
return name !== undefined && semanticPropertyPathKeyMatches(key, name);
|
||||
});
|
||||
|
||||
/** Prove one inert namespace conversion without relaxing general assignment semantics. */
|
||||
export const createSemanticModuleInterop = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
@@ -92,7 +82,7 @@ export const createSemanticModuleInterop = (
|
||||
const writes: {
|
||||
readonly scope: string;
|
||||
readonly offset: number;
|
||||
readonly path: readonly (string | null)[];
|
||||
readonly coverage: SemanticPropertyPathCoverage;
|
||||
}[] = [];
|
||||
const invalidatedBindings = new Map<string, boolean>();
|
||||
const invalidatedCalls = new WeakMap<t.Node, boolean>();
|
||||
@@ -127,12 +117,6 @@ export const createSemanticModuleInterop = (
|
||||
const { root, members } = electronMemberPath(current);
|
||||
if (members.some((member) => member === null)) return finish(undefined);
|
||||
suffix = [...(members as readonly string[]), ...suffix];
|
||||
if (t.isSequenceExpression(root)) {
|
||||
const value = root.expressions.at(-1);
|
||||
if (value === undefined) return finish(undefined);
|
||||
current = value;
|
||||
continue;
|
||||
}
|
||||
for (const global of ["Object", "Function", "Reflect"])
|
||||
if (isUnshadowedGlobal(root, state, global))
|
||||
return finish(["intrinsic", global, ...suffix]);
|
||||
@@ -173,20 +157,8 @@ export const createSemanticModuleInterop = (
|
||||
let capturedAt = node;
|
||||
let suffixLength = 0;
|
||||
for (;;) {
|
||||
current = unwrapJavaScriptExpression(current).node;
|
||||
if (suffixLength === 0)
|
||||
capturedAt =
|
||||
t.isMemberExpression(current) || t.isOptionalMemberExpression(current)
|
||||
? current.property
|
||||
: current;
|
||||
const { root, members } = electronMemberPath(current);
|
||||
suffixLength += members.length;
|
||||
if (t.isSequenceExpression(root)) {
|
||||
const value = root.expressions.at(-1);
|
||||
if (value === undefined) return undefined;
|
||||
current = value;
|
||||
continue;
|
||||
}
|
||||
if (!t.isIdentifier(root)) return undefined;
|
||||
const binding = resolveSemanticBindingState(state, root, root.name);
|
||||
if (binding === undefined) return { path, capturedAt };
|
||||
@@ -237,56 +209,24 @@ export const createSemanticModuleInterop = (
|
||||
node: t.Node,
|
||||
path: readonly string[],
|
||||
): boolean => {
|
||||
let current = unwrapJavaScriptExpression(node).node;
|
||||
let currentPath = path;
|
||||
for (;;) {
|
||||
const method = currentPath.at(-1);
|
||||
const invocationMethod =
|
||||
method === "bind" || method === "call" || method === "apply";
|
||||
if (
|
||||
invocationMethod &&
|
||||
(t.isMemberExpression(current) || t.isOptionalMemberExpression(current))
|
||||
) {
|
||||
// Reading an invocation member does not recapture the stored function.
|
||||
// Check member writes now, then check its base at the earlier capture.
|
||||
const scope = opaqueMutationPath(current).join(".");
|
||||
const offset = current.property.start ?? -1;
|
||||
if (
|
||||
writes.some(
|
||||
(write) =>
|
||||
(write.scope === scope || write.scope === "intrinsic") &&
|
||||
write.offset < offset &&
|
||||
((write.path.length >= currentPath.length &&
|
||||
intrinsicWriteCovers(write.path, currentPath)) ||
|
||||
intrinsicWriteCovers(write.path, [
|
||||
"intrinsic",
|
||||
"Function",
|
||||
"prototype",
|
||||
method,
|
||||
])),
|
||||
)
|
||||
)
|
||||
return true;
|
||||
current = unwrapJavaScriptExpression(current.object).node;
|
||||
currentPath = currentPath.slice(0, -1);
|
||||
continue;
|
||||
}
|
||||
const capture = capturedIntrinsic(current)?.capturedAt ?? current;
|
||||
const scope = opaqueMutationPath(capture).join(".");
|
||||
return writes.some(
|
||||
(write) =>
|
||||
(write.scope === scope || write.scope === "intrinsic") &&
|
||||
write.offset < (capture.start ?? -1) &&
|
||||
(intrinsicWriteCovers(write.path, currentPath) ||
|
||||
(invocationMethod &&
|
||||
intrinsicWriteCovers(write.path, [
|
||||
"intrinsic",
|
||||
"Function",
|
||||
"prototype",
|
||||
method,
|
||||
]))),
|
||||
);
|
||||
}
|
||||
const capture = capturedIntrinsic(node)?.capturedAt ?? node;
|
||||
const scope = opaqueMutationPath(capture).join(".");
|
||||
const method = path.at(-1);
|
||||
const invocationMethod =
|
||||
method === "bind" || method === "call" || method === "apply";
|
||||
return writes.some(
|
||||
(write) =>
|
||||
(write.scope === scope || write.scope === "intrinsic") &&
|
||||
write.offset < (capture.start ?? -1) &&
|
||||
(write.coverage.covers(path) ||
|
||||
(invocationMethod &&
|
||||
write.coverage.covers([
|
||||
"intrinsic",
|
||||
"Function",
|
||||
"prototype",
|
||||
method,
|
||||
]))),
|
||||
);
|
||||
};
|
||||
|
||||
const resolveBoundIntrinsic = (
|
||||
@@ -330,7 +270,7 @@ export const createSemanticModuleInterop = (
|
||||
if (members.at(-1) === "bind") {
|
||||
// A direct .bind may continue a bound callable, without discarding members.
|
||||
if (!terminal && members.length !== 1) return undefined;
|
||||
bindReads.push(current.callee);
|
||||
bindReads.push(captured?.capturedAt ?? current.callee);
|
||||
} else {
|
||||
// Reuse the invocation owner for generic call/apply/Reflect.apply of bind.
|
||||
const invocation = resolveJavaScriptIntrinsicInvocation(
|
||||
@@ -350,8 +290,6 @@ export const createSemanticModuleInterop = (
|
||||
captured = capturedIntrinsic(bindTarget);
|
||||
terminal = captured !== undefined;
|
||||
path = captured?.path;
|
||||
opaqueArguments ||=
|
||||
path !== undefined && intrinsicReadChanged(bindTarget, path);
|
||||
}
|
||||
receiver = bindingArguments?.[0];
|
||||
const ownArguments = bindingArguments?.slice(1) ?? [];
|
||||
@@ -366,9 +304,17 @@ export const createSemanticModuleInterop = (
|
||||
continue;
|
||||
}
|
||||
const boundPath = [...path, "bind"];
|
||||
opaqueArguments ||= bindReads.some((capture) =>
|
||||
intrinsicReadChanged(capture, boundPath),
|
||||
);
|
||||
const functionBind = ["intrinsic", "Function", "prototype", "bind"];
|
||||
opaqueArguments ||= bindReads.some((capture) => {
|
||||
const scope = opaqueMutationPath(capture).join(".");
|
||||
return writes.some(
|
||||
(write) =>
|
||||
(write.scope === scope || write.scope === "intrinsic") &&
|
||||
write.offset < (capture.start ?? -1) &&
|
||||
(write.coverage.covers(boundPath) ||
|
||||
write.coverage.covers(functionBind)),
|
||||
);
|
||||
});
|
||||
return {
|
||||
kind: opaqueArguments ? "opaque" : "known",
|
||||
path,
|
||||
@@ -656,7 +602,7 @@ export const createSemanticModuleInterop = (
|
||||
(write) =>
|
||||
(write.scope === scope || write.scope === "intrinsic") &&
|
||||
write.offset < (capturedAt.start ?? -1) &&
|
||||
intrinsicWriteCovers(write.path, path),
|
||||
write.coverage.covers(path),
|
||||
);
|
||||
}) ?? false;
|
||||
return {
|
||||
@@ -675,10 +621,12 @@ export const createSemanticModuleInterop = (
|
||||
isFreshObject,
|
||||
opaqueMutationPath,
|
||||
retainWrite: (node: t.Node, path: readonly (string | null)[]) => {
|
||||
const coverage = new SemanticPropertyPathCoverage();
|
||||
coverage.retain(path[0] === "opaque-intrinsic" ? ["intrinsic"] : path);
|
||||
writes.push({
|
||||
scope: opaqueMutationPath(node).join("."),
|
||||
offset: node.start ?? Infinity,
|
||||
path: path[0] === "opaque-intrinsic" ? ["intrinsic"] : path,
|
||||
coverage,
|
||||
});
|
||||
},
|
||||
invalidated: (binding: JavaScriptSemanticBindingState): boolean => {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
};
|
||||
@@ -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,
|
||||
|
||||
@@ -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([]);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -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,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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),
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -37,10 +37,6 @@ const INTRINSIC_MUTATIONS = [
|
||||
'const change = Object.defineProperty.bind(null,Object,"create"); change({value:customCreate});',
|
||||
],
|
||||
["receiver.cjs", 'Reflect.set({},"create",customCreate,Object);'],
|
||||
[
|
||||
"sequence.cjs",
|
||||
'(0,Object.defineProperty)(Object,"create",{value:customCreate});',
|
||||
],
|
||||
[
|
||||
"deep-call.cjs",
|
||||
'Function.prototype.call.call.call(Object.defineProperty,null,Object,"create",{value:customCreate});',
|
||||
@@ -93,7 +89,6 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
function hoistedFunction() {}
|
||||
const captured = Object.defineProperty;
|
||||
Object.defineProperty = custom;
|
||||
captured.call(null,metadata,"captured",{value:1});
|
||||
${ROLLDOWN_MODULE_INTEROP.replace("__defProp = Object.defineProperty", "__defProp = captured")}
|
||||
let electron = require("electron");
|
||||
electron = __toESM(electron, 1);
|
||||
@@ -124,7 +119,6 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
require("./generic-bind.cjs");
|
||||
require("./replaced-apply.cjs");
|
||||
require("./receiver.cjs");
|
||||
require("./sequence.cjs");
|
||||
require("./deep-call.cjs");
|
||||
require("./deep-apply.cjs");
|
||||
throw new Error("must not execute main");
|
||||
@@ -153,7 +147,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)(
|
||||
preload_entrypoints: 1,
|
||||
});
|
||||
expect(result.statistics.parse_failures).toBe(0);
|
||||
expect(result.statistics.parsed_javascript_files).toBe(13);
|
||||
expect(result.statistics.parsed_javascript_files).toBe(12);
|
||||
const windows = result.graph.nodes.filter(
|
||||
({ kind }) => kind === "browser-window",
|
||||
);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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"]);
|
||||
|
||||
@@ -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([
|
||||
|
||||
@@ -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);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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 },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user