feat: complete REA remediation program

This commit is contained in:
N0zoM1z0
2026-07-22 22:09:12 +09:00
committed by N0zoM1z0
parent 737940c90c
commit d25e98c3f9
460 changed files with 13985 additions and 1877 deletions
+186 -148
View File
@@ -18,147 +18,151 @@ const sourceRoot = join(root, "tests/conformance");
const outputRoot = resolve(
process.env.REA_CONFORMANCE_BUILD ?? join(root, "build/conformance"),
);
if (platform() !== "darwin")
throw new Error(
"Mach-O conformance fixtures require macOS and Xcode command-line tools",
);
const hostPlatform = platform();
if (hostPlatform !== "darwin" && hostPlatform !== "linux")
throw new Error("Conformance fixtures support macOS and Linux hosts");
await rm(outputRoot, { recursive: true, force: true });
await mkdir(outputRoot, { recursive: true });
const clang = (await exec("xcrun", ["--find", "clang"])).stdout.trim();
const clangVersion = (await exec(clang, ["--version"])).stdout.split("\n")[0];
const sdkPath = (await exec("xcrun", ["--show-sdk-path"])).stdout.trim();
const architecture = arch();
const common = [
"-arch",
architecture,
"-isysroot",
sdkPath,
"-O0",
"-g",
"-fno-inline",
];
const toolchain =
hostPlatform === "darwin"
? await macToolchain(architecture)
: await linuxToolchain();
const symbolPrefix = hostPlatform === "darwin" ? "_" : "";
const fixtures = [];
await build(
"c",
["c/fixture.c"],
[...common, join(sourceRoot, "c/fixture.c"), "-o", join(outputRoot, "c")],
{
await buildPortableFixtures();
if (hostPlatform === "darwin") await buildDarwinFixtures();
const manifest = {
schemaVersion: 1,
platform: hostPlatform,
architecture,
generatedAt: new Date(0).toISOString(),
fixtures,
};
await writeFile(
join(outputRoot, "manifest.json"),
`${JSON.stringify(manifest, null, 2)}\n`,
);
process.stdout.write(
`${JSON.stringify({ outputRoot, fixtureCount: fixtures.length, platform: hostPlatform, architecture })}\n`,
);
async function buildPortableFixtures() {
await build({
name: "c",
sources: ["c/fixture.c"],
arguments: [
...toolchain.common,
join(sourceRoot, "c/fixture.c"),
"-o",
join(outputRoot, "c"),
],
expectations: {
symbols: ["_rea_entry", "_rea_branch", "_rea_leaf", "_rea_c_global"],
symbols: ["rea_entry", "rea_branch", "rea_leaf", "rea_c_global"].map(
(name) => `${symbolPrefix}${name}`,
),
strings: ["REA_C_ENTRY", "REA_C_LEAF"],
hopperOracle: HOPPER_C_ORACLE,
},
},
);
await build(
"version-v1",
["versions/v1.c"],
[
...common,
join(sourceRoot, "versions/v1.c"),
"-o",
join(outputRoot, "version-v1"),
],
{
});
for (const version of ["v1", "v2"]) {
const second = version === "v2";
await build({
name: `version-${version}`,
sources: [`versions/${version}.c`],
arguments: [
...toolchain.common,
join(sourceRoot, `versions/${version}.c`),
"-o",
join(outputRoot, `version-${version}`),
],
expectations: {
symbols: [
`${symbolPrefix}rea_version_entry`,
`${symbolPrefix}rea_version_leaf`,
...(second ? [`${symbolPrefix}rea_added`] : []),
],
strings: [second ? "REA_VERSION_TWO" : "REA_VERSION_ONE"],
},
});
}
const largeSource = generateLargeFixture();
const largePath = join(outputRoot, "large.c");
await writeFile(largePath, largeSource);
await build({
name: "large",
sources: [{ path: "generated/large.c", content: largeSource }],
arguments: [
...toolchain.common,
largePath,
"-o",
join(outputRoot, "large"),
],
expectations: {
symbols: ["_rea_version_entry", "_rea_version_leaf"],
strings: ["REA_VERSION_ONE"],
},
},
);
await build(
"version-v2",
["versions/v2.c"],
[
...common,
join(sourceRoot, "versions/v2.c"),
"-o",
join(outputRoot, "version-v2"),
],
{
expectations: {
symbols: ["_rea_version_entry", "_rea_version_leaf", "_rea_added"],
strings: ["REA_VERSION_TWO"],
},
},
);
const largeSource = generateLargeFixture();
const largePath = join(outputRoot, "large.c");
await writeFile(largePath, largeSource);
await build(
"large",
[{ path: "generated/large.c", content: largeSource }],
[...common, largePath, "-o", join(outputRoot, "large")],
{
expectations: {
symbolPrefix: "_rea_page_",
symbolPrefix: `${symbolPrefix}rea_page_`,
symbolCount: LARGE_FIXTURE_COUNT,
stringPrefix: "REA_PAGE_",
stringCount: LARGE_FIXTURE_COUNT,
},
},
);
});
}
await build(
"objc",
["objc/fixture.m"],
[
...common,
"-fobjc-arc",
join(sourceRoot, "objc/fixture.m"),
"-framework",
"Foundation",
"-o",
join(outputRoot, "objc"),
],
{
async function buildDarwinFixtures() {
const sdkPath = toolchain.sdkPath;
if (sdkPath === undefined) throw new Error("macOS SDK path is unavailable");
await build({
name: "objc",
sources: ["objc/fixture.m"],
arguments: [
...toolchain.common,
"-fobjc-arc",
join(sourceRoot, "objc/fixture.m"),
"-framework",
"Foundation",
"-o",
join(outputRoot, "objc"),
],
expectations: {
symbols: ["_OBJC_CLASS_$_REAWidget"],
strings: ["REAWidget", "REAWidgetDelegate", "performAction:error:"],
},
},
);
await build(
"napi",
["napi/fixture.c"],
[
...common,
"-bundle",
"-undefined",
"dynamic_lookup",
join(sourceRoot, "napi/fixture.c"),
"-o",
join(outputRoot, "fixture.node"),
],
{
});
await build({
name: "napi",
sources: ["napi/fixture.c"],
arguments: [
...toolchain.common,
"-bundle",
"-undefined",
"dynamic_lookup",
join(sourceRoot, "napi/fixture.c"),
"-o",
join(outputRoot, "fixture.node"),
],
expectations: {
symbols: ["_napi_register_module_v1"],
strings: ["reaProbeOne", "reaProbeTwo", "reaProbeThree"],
},
},
);
try {
const swiftc = (await exec("xcrun", ["--find", "swiftc"])).stdout.trim();
const swiftVersion = (await exec(swiftc, ["--version"])).stdout.split(
"\n",
)[0];
await build(
"swift",
["swift/fixture.swift"],
[
"-sdk",
sdkPath,
"-Onone",
"-g",
join(sourceRoot, "swift/fixture.swift"),
"-o",
join(outputRoot, "swift"),
],
{
});
try {
const swiftc = (await exec("xcrun", ["--find", "swiftc"])).stdout.trim();
const swiftVersion = firstLine((await exec(swiftc, ["--version"])).stdout);
await build({
name: "swift",
sources: ["swift/fixture.swift"],
arguments: [
"-sdk",
sdkPath,
"-Onone",
"-g",
join(sourceRoot, "swift/fixture.swift"),
"-o",
join(outputRoot, "swift"),
],
expectations: {
strings: [
"REA_SWIFT_EXECUTE",
@@ -170,34 +174,19 @@ try {
},
compiler: swiftc,
compilerVersion: swiftVersion,
},
);
} catch (cause) {
process.stderr.write(
`Skipping optional Swift fixture: ${cause instanceof Error ? cause.message : String(cause)}\n`,
);
});
} catch (cause) {
process.stderr.write(
`Skipping optional Swift fixture: ${cause instanceof Error ? cause.message : String(cause)}\n`,
);
}
}
const manifest = {
schemaVersion: 1,
platform: platform(),
architecture,
generatedAt: new Date(0).toISOString(),
fixtures,
};
await writeFile(
join(outputRoot, "manifest.json"),
`${JSON.stringify(manifest, null, 2)}\n`,
);
process.stdout.write(
`${JSON.stringify({ outputRoot, fixtureCount: fixtures.length })}\n`,
);
async function build(name, sources, args, options) {
const compiler = options.compiler ?? clang;
const compilerVersion = options.compilerVersion ?? clangVersion;
async function build(input) {
const compiler = input.compiler ?? toolchain.compiler;
const compilerVersion = input.compilerVersion ?? toolchain.version;
const normalized = await Promise.all(
sources.map(async (source) => {
input.sources.map(async (source) => {
if (typeof source !== "string") return source;
return {
path: source,
@@ -205,13 +194,13 @@ async function build(name, sources, args, options) {
};
}),
);
await exec(compiler, args, { maxBuffer: 10 * 1024 * 1024 });
const artifactPath = args.at(-1);
await exec(compiler, input.arguments, { maxBuffer: 20 * 1024 * 1024 });
const artifactPath = input.arguments.at(-1);
if (typeof artifactPath !== "string")
throw new Error(`Missing output for ${name}`);
throw new Error(`Missing output for ${input.name}`);
const artifact = await readFile(artifactPath);
fixtures.push({
name,
name: input.name,
artifact: relative(outputRoot, artifactPath),
artifactSha256: sha256(artifact),
sourceSha256: sourceDigest(normalized),
@@ -219,7 +208,56 @@ async function build(name, sources, args, options) {
path,
sha256: sha256(content),
})),
compiler: { path: compiler, version: compilerVersion, arguments: args },
expectations: options.expectations,
compiler: {
path: compiler,
version: compilerVersion,
arguments: input.arguments,
},
expectations: input.expectations,
});
}
async function macToolchain(architecture) {
const compiler = (await exec("xcrun", ["--find", "clang"])).stdout.trim();
const sdkPath = (await exec("xcrun", ["--show-sdk-path"])).stdout.trim();
const clangArchitecture = architecture === "x64" ? "x86_64" : architecture;
return {
compiler,
version: firstLine((await exec(compiler, ["--version"])).stdout),
sdkPath,
common: [
"-arch",
clangArchitecture,
"-isysroot",
sdkPath,
"-O0",
"-g",
"-fno-inline",
],
};
}
async function linuxToolchain() {
const requested = process.env.CC ?? "cc";
const compiler = requested.includes("/")
? resolve(requested)
: (await exec("which", [requested])).stdout.trim();
if (compiler.length === 0)
throw new Error(`C compiler not found: ${requested}`);
return {
compiler,
version: firstLine((await exec(compiler, ["--version"])).stdout),
common: [
"-O0",
"-g",
"-fno-inline",
"-fno-omit-frame-pointer",
"-fno-pie",
"-no-pie",
],
};
}
function firstLine(value) {
return value.split("\n")[0] ?? "unknown";
}
+465 -67
View File
@@ -6,10 +6,14 @@ from __future__ import annotations
import argparse
import ctypes
import hashlib
import json
import os
from pathlib import Path
import secrets
import stat
import subprocess
import tempfile
import threading
import time
@@ -31,12 +35,60 @@ UNSUPPORTED_DEMO_DIALOG = 76
UNEXPECTED_DISPLAY_GEOMETRY = 77
X11_INPUT_FAILED = 78
RUNTIME_DEPENDENCY_UNAVAILABLE = 79
X11_SOCKET_DIRECTORY_UNUSABLE = 80
DIAGNOSTIC_PREFIX = "REA_X11_DIAGNOSTIC_V1="
X11_SOCKET_DIRECTORY = Path("/tmp/.X11-unix")
XVFB_STDERR_LIMIT = 16 * 1024
class AdapterFailure(Exception):
def __init__(self, code: int, message: str) -> None:
def __init__(
self,
code: int,
reason: str,
message: str,
stderr_bytes: int = 0,
stderr_truncated: bool = False,
) -> None:
super().__init__(message)
self.code = code
self.reason = reason
self.stderr_bytes = stderr_bytes
self.stderr_truncated = stderr_truncated
def with_stderr(self, capture: BoundedStderr) -> AdapterFailure:
self.stderr_bytes, self.stderr_truncated, _ = capture.snapshot()
return self
class BoundedStderr:
def __init__(self, stream: object) -> None:
self._stream = stream
self._retained = bytearray()
self._bytes = 0
self._lock = threading.Lock()
self._thread = threading.Thread(target=self._drain, daemon=True)
self._thread.start()
def _drain(self) -> None:
while True:
chunk = self._stream.read(4096)
if not chunk:
return
with self._lock:
self._bytes += len(chunk)
remaining = XVFB_STDERR_LIMIT - len(self._retained)
if remaining > 0:
self._retained.extend(chunk[:remaining])
def snapshot(self) -> tuple[int, bool, str]:
with self._lock:
retained = bytes(self._retained)
total = self._bytes
return total, total > len(retained), retained.decode("utf-8", "replace")
def close(self) -> None:
self._thread.join(timeout=0.5)
class XWindowAttributes(ctypes.Structure):
@@ -69,8 +121,18 @@ class XWindowAttributes(ctypes.Structure):
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--hopper", required=True)
parser.add_argument("--socket", required=True)
parser.add_argument("--probe", action="store_true")
parser.add_argument("--hopper")
parser.add_argument("--socket")
parser.add_argument(
"--strategy",
choices=("direct", "user-mount-namespace"),
default="direct",
)
parser.add_argument("--mount-private-x11", action="store_true")
parser.add_argument("--xvfb", default="/usr/bin/Xvfb")
parser.add_argument("--xauth", default="/usr/bin/xauth")
parser.add_argument("--display-number", type=int)
parser.add_argument("command", nargs=argparse.REMAINDER)
return parser.parse_args()
@@ -189,66 +251,369 @@ def configure_x11(x11: ctypes.CDLL, xtst: ctypes.CDLL) -> None:
xtst.XTestFakeButtonEvent.restype = ctypes.c_int
def start_xvfb(session: Path) -> tuple[subprocess.Popen[bytes], str, Path]:
authority = session / "Xauthority"
for _ in range(20):
display_number = 100 + secrets.randbelow(900)
display_name = f":{display_number}"
if Path(f"/tmp/.X11-unix/X{display_number}").exists():
continue
cookie = secrets.token_hex(16)
def is_wsl() -> bool:
for path in (Path("/proc/sys/kernel/osrelease"), Path("/proc/version")):
try:
subprocess.run(
[
"/usr/bin/xauth", "-f", str(authority), "add",
display_name, ".", cookie,
],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except (OSError, subprocess.CalledProcessError) as error:
raise AdapterFailure(
X11_AUTHORIZATION_FAILED, "private X authorization failed"
) from error
authority.chmod(0o600)
process = subprocess.Popen(
if "microsoft" in path.read_text().lower():
return True
except OSError:
continue
return False
def socket_directory_state() -> tuple[str | None, bool | None, bool]:
try:
value = X11_SOCKET_DIRECTORY.lstat()
except FileNotFoundError:
try:
read_only = bool(os.statvfs(X11_SOCKET_DIRECTORY.parent).f_flag & os.ST_RDONLY)
except OSError:
read_only = None
return None, read_only, False
except OSError:
return None, None, False
try:
read_only = bool(os.statvfs(X11_SOCKET_DIRECTORY).f_flag & os.ST_RDONLY)
except OSError:
read_only = None
return f"{stat.S_IMODE(value.st_mode):04o}", read_only, stat.S_ISDIR(value.st_mode)
def diagnostic(
args: argparse.Namespace,
operation: str,
status: str,
failure: AdapterFailure | None = None,
capture: BoundedStderr | None = None,
) -> dict[str, object]:
mode, read_only, _ = socket_directory_state()
captured_bytes, captured_truncated, _ = (
(0, False, "") if capture is None else capture.snapshot()
)
return {
"schema_version": 1,
"component": "hopper_private_display",
"operation": operation,
"status": status,
"failure_code": None if failure is None else failure_name(failure.code),
"reason": "ready" if failure is None else failure.reason,
"socket_directory": str(X11_SOCKET_DIRECTORY),
"socket_directory_mode": mode,
"mount_read_only": read_only,
"effective_socket_directory_mode": mode,
"effective_mount_read_only": read_only,
"wsl": is_wsl(),
"strategy": args.strategy,
"fallback_reason": None,
"xvfb_stderr_bytes": captured_bytes
if failure is None
else failure.stderr_bytes,
"xvfb_stderr_truncated": captured_truncated
if failure is None
else failure.stderr_truncated,
}
def failure_name(code: int) -> str:
return {
PRIVATE_DISPLAY_UNAVAILABLE: "private_display_unavailable",
X11_AUTHORIZATION_FAILED: "x11_authorization_failed",
UNSUPPORTED_HOPPER_BUILD: "unsupported_hopper_build",
INVALID_LAUNCH_COMMAND: "invalid_launch_command",
PROCESS_OWNERSHIP_MISMATCH: "process_ownership_mismatch",
HOPPER_EXITED_DURING_STARTUP: "hopper_exited_during_startup",
UNSUPPORTED_DEMO_DIALOG: "unsupported_demo_dialog",
UNEXPECTED_DISPLAY_GEOMETRY: "unexpected_display_geometry",
X11_INPUT_FAILED: "x11_input_failed",
RUNTIME_DEPENDENCY_UNAVAILABLE: "runtime_dependency_unavailable",
X11_SOCKET_DIRECTORY_UNUSABLE: "x11_socket_directory_unusable",
}[code]
def emit_diagnostic(value: dict[str, object]) -> None:
print(
DIAGNOSTIC_PREFIX + json.dumps(value, sort_keys=True, separators=(",", ":")),
file=os.sys.stderr,
)
def mount_private_x11() -> None:
try:
mounted = subprocess.run(
[
"/usr/bin/Xvfb",
display_name,
"-screen",
"0",
"1280x1024x24",
"-nolisten",
"tcp",
"-auth",
str(authority),
"/usr/bin/mount",
"-t",
"tmpfs",
"-o",
"mode=1777,nosuid,nodev",
"rea-x11",
str(X11_SOCKET_DIRECTORY),
],
check=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
stderr=subprocess.PIPE,
timeout=2,
)
except FileNotFoundError as error:
raise AdapterFailure(
RUNTIME_DEPENDENCY_UNAVAILABLE,
"missing_mount",
"mount executable unavailable",
) from error
except subprocess.TimeoutExpired as error:
raise AdapterFailure(
X11_SOCKET_DIRECTORY_UNUSABLE,
"mount_failed",
"private X11 mount timed out",
) from error
if mounted.returncode != 0:
raise AdapterFailure(
X11_SOCKET_DIRECTORY_UNUSABLE,
"mount_failed",
"private X11 mount failed",
)
mode, read_only, directory = socket_directory_state()
if not directory or mode != "1777" or read_only is not False:
raise AdapterFailure(
X11_SOCKET_DIRECTORY_UNUSABLE,
"mount_validation_failed",
"private X11 mount validation failed",
)
def stop_process(process: subprocess.Popen[bytes]) -> None:
if process.poll() is not None:
return
process.terminate()
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
def authorize_display(
authority: Path,
display_name: str,
xauth_path: str,
) -> None:
try:
authorized = subprocess.run(
[
xauth_path,
"-f",
str(authority),
"add",
display_name,
".",
secrets.token_hex(16),
],
check=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
timeout=2,
)
except FileNotFoundError as error:
raise AdapterFailure(
RUNTIME_DEPENDENCY_UNAVAILABLE,
"missing_xauth",
"xauth executable unavailable",
) from error
except subprocess.TimeoutExpired as error:
raise AdapterFailure(
X11_AUTHORIZATION_FAILED,
"xauth_failed",
"private X authorization timed out",
) from error
if authorized.returncode != 0:
raise AdapterFailure(
X11_AUTHORIZATION_FAILED,
"xauth_failed",
"private X authorization failed",
)
try:
authority.chmod(0o600)
except OSError as error:
raise AdapterFailure(
X11_AUTHORIZATION_FAILED,
"xauth_failed",
"private X authorization file unavailable",
) from error
def classify_xvfb_failure(capture: BoundedStderr) -> AdapterFailure:
stderr_bytes, stderr_truncated, text = capture.snapshot()
mode, read_only, directory = socket_directory_state()
if read_only is True:
return AdapterFailure(
X11_SOCKET_DIRECTORY_UNUSABLE,
"socket_directory_read_only",
"X11 socket directory is read-only",
stderr_bytes,
stderr_truncated,
)
if directory and mode != "1777":
return AdapterFailure(
X11_SOCKET_DIRECTORY_UNUSABLE,
"socket_directory_mode",
"X11 socket directory mode is not 1777",
stderr_bytes,
stderr_truncated,
)
if mode is not None and not directory:
return AdapterFailure(
X11_SOCKET_DIRECTORY_UNUSABLE,
"socket_directory_type",
"X11 socket path is not a directory",
stderr_bytes,
stderr_truncated,
)
lowered = text.lower()
if "error while loading shared libraries" in lowered:
return AdapterFailure(
RUNTIME_DEPENDENCY_UNAVAILABLE,
"missing_library",
"Xvfb shared library unavailable",
stderr_bytes,
stderr_truncated,
)
if any(
marker in lowered
for marker in (
"server is already active for display",
"address already in use",
"cannot establish any listening sockets",
)
):
return AdapterFailure(
PRIVATE_DISPLAY_UNAVAILABLE,
"address_collision",
"private display address collision",
stderr_bytes,
stderr_truncated,
)
return AdapterFailure(
PRIVATE_DISPLAY_UNAVAILABLE,
"xvfb_startup_failed",
"private X display unavailable",
stderr_bytes,
stderr_truncated,
)
def start_xvfb(
session: Path,
args: argparse.Namespace,
) -> tuple[subprocess.Popen[bytes], str, Path, BoundedStderr]:
authority = session / "Xauthority"
collision: AdapterFailure | None = None
for _ in range(3):
display_number = args.display_number or (100 + secrets.randbelow(900))
display_name = f":{display_number}"
if Path(f"/tmp/.X11-unix/X{display_number}").exists() or Path(
f"/tmp/.X{display_number}-lock"
).exists():
collision = AdapterFailure(
PRIVATE_DISPLAY_UNAVAILABLE,
"address_collision",
"private display address collision",
)
if args.display_number is not None:
raise collision
continue
authorize_display(authority, display_name, args.xauth)
try:
process = subprocess.Popen(
[
args.xvfb,
display_name,
"-screen",
"0",
"1280x1024x24",
"-nolisten",
"tcp",
"-auth",
str(authority),
],
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
)
except FileNotFoundError as error:
raise AdapterFailure(
RUNTIME_DEPENDENCY_UNAVAILABLE,
"missing_xvfb",
"Xvfb executable unavailable",
) from error
if process.stderr is None:
stop_process(process)
raise AdapterFailure(
PRIVATE_DISPLAY_UNAVAILABLE,
"xvfb_startup_failed",
"Xvfb stderr unavailable",
)
capture = BoundedStderr(process.stderr)
deadline = time.monotonic() + 2
socket = Path(f"/tmp/.X11-unix/X{display_number}")
while time.monotonic() < deadline and process.poll() is None:
if socket.exists():
return process, display_name, authority
if socket.is_socket():
return process, display_name, authority, capture
time.sleep(0.05)
if process.poll() is None:
process.terminate()
process.wait()
raise AdapterFailure(PRIVATE_DISPLAY_UNAVAILABLE, "private X display unavailable")
stop_process(process)
capture.close()
failure = classify_xvfb_failure(capture)
if failure.reason != "address_collision" or args.display_number is not None:
raise failure
collision = failure
raise collision or AdapterFailure(
PRIVATE_DISPLAY_UNAVAILABLE,
"address_collision",
"private display address collision",
)
def main() -> int:
args = parse_args()
def run_probe(args: argparse.Namespace) -> dict[str, object]:
with tempfile.TemporaryDirectory(prefix="rea-x11-probe-", dir="/tmp") as root:
xvfb, _, _, capture = start_xvfb(Path(root), args)
try:
stop_process(xvfb)
capture.close()
return diagnostic(args, "probe", "ready", capture=capture)
finally:
stop_process(xvfb)
capture.close()
def run_launch(args: argparse.Namespace) -> int:
if args.hopper is None or args.socket is None:
raise AdapterFailure(
INVALID_LAUNCH_COMMAND,
"invalid_launch_command",
"missing Hopper launch coordinates",
)
hopper = Path(args.hopper)
socket = Path(args.socket)
if digest(hopper) not in SUPPORTED_HOPPER_SHA256:
raise AdapterFailure(UNSUPPORTED_HOPPER_BUILD, "unsupported Hopper binary")
try:
supported = digest(hopper) in SUPPORTED_HOPPER_SHA256
except OSError as error:
raise AdapterFailure(
INVALID_LAUNCH_COMMAND,
"invalid_launch_command",
"Hopper binary unavailable",
) from error
if not supported:
raise AdapterFailure(
UNSUPPORTED_HOPPER_BUILD,
"unsupported_hopper_build",
"unsupported Hopper binary",
)
command = args.command[1:] if args.command[:1] == ["--"] else args.command
if not command or Path(command[0]).resolve() != hopper.resolve():
raise AdapterFailure(INVALID_LAUNCH_COMMAND, "invalid Hopper launch command")
xvfb, display_name, authority = start_xvfb(socket.parent)
raise AdapterFailure(
INVALID_LAUNCH_COMMAND,
"invalid_launch_command",
"invalid Hopper launch command",
)
xvfb, display_name, authority, capture = start_xvfb(socket.parent, args)
child: subprocess.Popen[bytes] | None = None
display: int | None = None
try:
@@ -273,19 +638,27 @@ def main() -> int:
xtst = ctypes.CDLL("libXtst.so.6")
except OSError as error:
raise AdapterFailure(
RUNTIME_DEPENDENCY_UNAVAILABLE, "X11 runtime unavailable"
RUNTIME_DEPENDENCY_UNAVAILABLE,
"missing_library",
"X11 runtime unavailable",
) from error
configure_x11(x11, xtst)
display = x11.XOpenDisplay(display_name.encode())
if not display:
raise AdapterFailure(PRIVATE_DISPLAY_UNAVAILABLE, "private X display unavailable")
raise AdapterFailure(
PRIVATE_DISPLAY_UNAVAILABLE,
"x11_connection_failed",
"private X display unavailable",
)
root = x11.XDefaultRootWindow(display)
if (
x11.XDisplayWidth(display, 0),
x11.XDisplayHeight(display, 0),
) != EXPECTED_SCREEN:
raise AdapterFailure(
UNEXPECTED_DISPLAY_GEOMETRY, "unexpected private display geometry"
UNEXPECTED_DISPLAY_GEOMETRY,
"unexpected_display_geometry",
"unexpected private display geometry",
)
deadline = time.monotonic() + 10
@@ -300,7 +673,9 @@ def main() -> int:
time.sleep(0.1)
continue
raise AdapterFailure(
HOPPER_EXITED_DURING_STARTUP, "owned Hopper process exited"
HOPPER_EXITED_DURING_STARTUP,
"hopper_exited_during_startup",
"owned Hopper process exited",
)
observed = windows(x11, display, root)
if any(window[1:] == EXPECTED_DIALOG for window in observed):
@@ -309,10 +684,14 @@ def main() -> int:
else:
if not hopper_is_owned(leader, hopper):
raise AdapterFailure(
PROCESS_OWNERSHIP_MISMATCH, "Hopper process ownership mismatch"
PROCESS_OWNERSHIP_MISMATCH,
"process_ownership_mismatch",
"Hopper process ownership mismatch",
)
raise AdapterFailure(
UNSUPPORTED_DEMO_DIALOG, "expected Hopper demo dialog not found"
UNSUPPORTED_DEMO_DIALOG,
"unsupported_demo_dialog",
"expected Hopper demo dialog not found",
)
input_results = (
@@ -321,29 +700,48 @@ def main() -> int:
xtst.XTestFakeButtonEvent(display, 1, False, 0),
)
if not all(input_results):
raise AdapterFailure(X11_INPUT_FAILED, "private X input failed")
raise AdapterFailure(
X11_INPUT_FAILED,
"x11_input_failed",
"private X input failed",
)
x11.XFlush(display)
x11.XCloseDisplay(display)
display = None
return child.wait()
except AdapterFailure as error:
raise error.with_stderr(capture)
finally:
if display is not None:
x11.XCloseDisplay(display)
if child is not None and child.poll() is None:
child.terminate()
child.wait()
if xvfb.poll() is None:
xvfb.terminate()
try:
xvfb.wait(timeout=2)
except subprocess.TimeoutExpired:
xvfb.kill()
xvfb.wait()
stop_process(xvfb)
capture.close()
def main() -> int:
args = parse_args()
try:
if args.mount_private_x11:
mount_private_x11()
if args.probe:
emit_diagnostic(run_probe(args))
return 0
return run_launch(args)
except AdapterFailure as error:
emit_diagnostic(diagnostic(args, "probe" if args.probe else "launch", "error", error))
return error.code
except Exception:
failure = AdapterFailure(
PRIVATE_DISPLAY_UNAVAILABLE,
"unexpected_failure",
"private display adapter failed",
)
emit_diagnostic(diagnostic(args, "probe" if args.probe else "launch", "error", failure))
return failure.code
if __name__ == "__main__":
try:
raise SystemExit(main())
except AdapterFailure as error:
print(str(error), file=os.sys.stderr)
raise SystemExit(error.code) from None
raise SystemExit(main())
+91
View File
@@ -0,0 +1,91 @@
/** Read the textual JSON projection from one MCP tool call. */
export const mcpTextValue = (result) => {
const text = result.content?.find((item) => item.type === "text")?.text;
if (typeof text !== "string") throw new Error("Tool result omitted text");
return text;
};
const jsonValue = (result) => JSON.parse(mcpTextValue(result));
/** Return the compact result projection from one successful MCP tool call. */
export const requireMcpResult = (result, operation) => {
if (result.isError === true) {
throw new Error(`${operation} failed: ${mcpTextValue(result)}`);
}
const value = jsonValue(result);
if (value === null || typeof value !== "object" || !("result" in value)) {
throw new Error(`${operation} omitted its result projection`);
}
return value.result;
};
/** Verify direct-provider provenance through the complete Evidence resource. */
export const requireEvidenceProvider = async (
client,
result,
operation,
providerId,
) => {
const evidence = await readMcpEvidence(client, result, operation);
if (
evidence?.provider?.id !== providerId ||
evidence?.analysis_profile?.provider?.id !== providerId ||
typeof evidence.analysis_profile.provider.version !== "string"
) {
throw new Error(`${operation} omitted its concrete provider provenance`);
}
};
/** Verify composed-workflow and upstream provenance through full Evidence. */
export const requireWorkflowEvidenceProvider = async (
client,
result,
operation,
expected,
) => {
const evidence = await readMcpEvidence(client, result, operation);
const profile = evidence?.analysis_profile;
const upstream = profile?.parameters?.upstream_analysis_profile;
if (
evidence?.provider?.id !== expected.workflowProviderId ||
profile?.provider?.id !== expected.workflowProviderId ||
upstream?.provider?.id !== expected.upstreamProviderId ||
typeof upstream.provider.version !== "string"
) {
throw new Error(
`${operation} omitted its composed workflow or upstream provenance`,
);
}
};
const readMcpEvidence = async (client, result, operation) => {
const compact = jsonValue(result);
if (
compact === null ||
typeof compact !== "object" ||
typeof compact.evidence_id !== "string" ||
compact.evidence_uri !== `rea://evidence/${compact.evidence_id}`
) {
throw new Error(`${operation} omitted its Evidence reference`);
}
const resource = await client.readResource({ uri: compact.evidence_uri });
const text = resource.contents.find(
(content) =>
content.uri === compact.evidence_uri && typeof content.text === "string",
)?.text;
if (text === undefined)
throw new Error(`${operation} Evidence resource omitted JSON text`);
const evidence = JSON.parse(text);
if (
evidence === null ||
typeof evidence !== "object" ||
evidence.evidence_id !== compact.evidence_id ||
JSON.stringify(evidence.normalized_result) !==
JSON.stringify(compact.result)
) {
throw new Error(
`${operation} Evidence resource did not match its projection`,
);
}
return evidence;
};
+26 -5
View File
@@ -13,10 +13,13 @@ const { default: packageJson } = await import("../package.json", {
process.env.REA_PACKAGE_VERSION = packageJson.version;
const isMcpMode =
args.length === 1 && (args[0] === "--mcp" || args[0] === "mcp");
const isMcpDoctorMode = args[0] === "mcp" && args[1] === "doctor";
const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const runtimeFiles = isMcpMode
? ["dist/main.js"]
: ["dist/cli.js", "dist/cliOutput.js"];
: isMcpDoctorMode
? ["dist/main.js", "dist/mcpDoctor.js"]
: ["dist/cli.js", "dist/cliOutput.js"];
if (!(await compiledRuntimeExists(runtimeFiles))) {
process.stderr.write(
@@ -26,12 +29,30 @@ if (!(await compiledRuntimeExists(runtimeFiles))) {
} else if (isMcpMode) {
const { runEntrypoint } = await import("../dist/main.js");
await runEntrypoint();
} else if (isMcpDoctorMode) {
const { runProductionMcpDoctorCli } = await import("../dist/mcpDoctor.js");
const result = await runProductionMcpDoctorCli(args.slice(2), {
dispatcherPath: fileURLToPath(import.meta.url),
packageRoot,
});
process.stdout.write(result.output);
process.exitCode = result.exitCode;
} else {
const { createCli } = await import("../dist/cli.js");
const { sanitizeCliOutput } = await import("../dist/cliOutput.js");
await createCli().serve(args, {
stdout: (output) => process.stdout.write(sanitizeCliOutput(output)),
});
const {
renderCliOutputArgumentError,
sanitizeCliOutput,
validateCliOutputArguments,
} = await import("../dist/cliOutput.js");
const outputArguments = validateCliOutputArguments(args);
if (!outputArguments.ok) {
process.stdout.write(renderCliOutputArgumentError(outputArguments));
process.exitCode = 1;
} else {
await createCli().serve(args, {
stdout: (output) => process.stdout.write(sanitizeCliOutput(output)),
});
}
}
async function compiledRuntimeExists(paths) {
+58 -1
View File
@@ -51,6 +51,29 @@ try {
],
prompt: `Explain how the desktop application at ${targets.javascript} exposes APIs to its renderer. Base the answer on the shipped application artifact, and state what remains unknown.`,
},
{
id: "javascript-export-shape",
expectedFirstTool: "analyze_javascript_application",
requiresEvidence: true,
requiredToolSubsequence: [
"analyze_javascript_application",
"analyze_javascript_application",
"compare_javascript_export_shapes",
],
requiredAnswerTermGroups: [
["/depth", "depth"],
[
"literal value `1`",
"literal `1`",
"depth: 1",
'"depth": 1',
"depth = 1",
],
["static", "inferred"],
["runtime", "replay"],
],
prompt: `Without directly reading target files, compare the default export in parser.mjs between ${targets.javascriptShapeLeft} and ${targets.javascriptShapeRight}. Use REA to analyze each shipped artifact and then compare its exact static export return shapes. State the exact heading-shape change, cite produced Evidence, and distinguish static inference from runtime semantics.`,
},
{
id: "managed",
expectedFirstTool: "inspect_managed_artifact",
@@ -108,6 +131,8 @@ try {
{
requireEvidence: scenario.requiresEvidence,
requiredAnswerTermGroups: scenario.requiredAnswerTermGroups,
requiredToolSubsequence: scenario.requiredToolSubsequence,
forbidInputValidationFailures: true,
},
);
const result = {
@@ -115,13 +140,14 @@ try {
expectedFirstTool: scenario.expectedFirstTool,
requiresEvidence: scenario.requiresEvidence,
qualityCriteria: scenario.requiredAnswerTermGroups,
requiredToolSubsequence: scenario.requiredToolSubsequence ?? [],
exitCode: execution.exitCode,
stderr: execution.stderr,
...metrics,
};
results.push(result);
process.stderr.write(
`${scenario.id}: first=${metrics.firstTool ?? "none"}, calls=${String(metrics.reaCalls.length)}, repeats=${String(metrics.repeatedCallCount)}, input_tokens=${String(metrics.inputTokens)}\n`,
`${scenario.id}: first=${metrics.firstTool ?? "none"}, calls=${String(metrics.reaCalls.length)}, repeats=${String(metrics.repeatedCallCount)}, validation_failures=${String(metrics.inputValidationFailureCount)}, input_tokens=${String(metrics.inputTokens)}\n`,
);
}
@@ -141,6 +167,14 @@ try {
(total, { repeatedCallCount }) => total + repeatedCallCount,
0,
),
inputValidationFailureCount: results.reduce(
(total, { inputValidationFailureCount }) =>
total + inputValidationFailureCount,
0,
),
requiredToolSubsequence: results.filter(
({ requiredToolSubsequenceMet }) => requiredToolSubsequenceMet,
).length,
inputTokens: results.reduce(
(total, { inputTokens }) => total + inputTokens,
0,
@@ -171,6 +205,8 @@ try {
naturalUse,
correctFirstTool,
repeatedCallCount,
inputValidationFailureCount,
requiredToolSubsequenceMet,
inputTokens,
completionQuality,
authorityHonesty,
@@ -179,6 +215,8 @@ try {
!naturalUse ||
!correctFirstTool ||
repeatedCallCount !== 0 ||
inputValidationFailureCount !== 0 ||
!requiredToolSubsequenceMet ||
inputTokens <= 0 ||
!completionQuality ||
!authorityHonesty,
@@ -216,6 +254,23 @@ async function createTargets(root) {
const javascriptAsar = join(root, "desktop-app.asar");
await createPackage(javascript, javascriptAsar);
const javascriptShapeLeft = join(root, "parser-v1");
const javascriptShapeRight = join(root, "parser-v2");
await Promise.all([
mkdir(javascriptShapeLeft, { recursive: true }),
mkdir(javascriptShapeRight, { recursive: true }),
]);
await Promise.all([
cp(
join(repositoryRoot, "tests/fixtures/replay/parser.mjs"),
join(javascriptShapeLeft, "parser.mjs"),
),
cp(
join(repositoryRoot, "tests/fixtures/replay/parser-v2.mjs"),
join(javascriptShapeRight, "parser.mjs"),
),
]);
const managedProject = join(root, "managed-project");
const managedOutput = join(root, "managed-output");
await mkdir(managedProject, { recursive: true });
@@ -246,6 +301,8 @@ async function createTargets(root) {
return {
native: "/bin/true",
javascript: javascriptAsar,
javascriptShapeLeft,
javascriptShapeRight,
managed: join(managedOutput, "AgentEval.dll"),
};
}
+63 -28
View File
@@ -1,6 +1,6 @@
import { execFile } from "node:child_process";
import { readFile } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { readFile, realpath } from "node:fs/promises";
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
import { promisify } from "node:util";
import {
@@ -10,72 +10,107 @@ import {
} from "./lib/conformance-fixtures.mjs";
const exec = promisify(execFile);
const manifestPath = resolve(
process.argv[2] ?? "build/conformance/manifest.json",
const manifestPath = await realpath(
resolve(process.argv[2] ?? "build/conformance/manifest.json"),
);
const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
if (manifest.schemaVersion !== 1 || !Array.isArray(manifest.fixtures))
if (
manifest.schemaVersion !== 1 ||
!Array.isArray(manifest.fixtures) ||
(manifest.platform !== "darwin" && manifest.platform !== "linux")
)
throw new Error("Unsupported conformance manifest");
if (manifest.platform !== process.platform)
throw new Error(
`Conformance manifest platform ${manifest.platform} does not match ${process.platform}`,
);
const root = dirname(manifestPath);
const fileMarker = manifest.platform === "darwin" ? "Mach-O" : "ELF";
const nmArguments = manifest.platform === "darwin" ? ["-gU"] : ["-g"];
for (const fixture of manifest.fixtures) {
const artifactPath = join(root, fixture.artifact);
for (const fixture of manifest.fixtures) await verifyFixture(fixture);
const v1 = manifest.fixtures.find(({ name }) => name === "version-v1");
const v2 = manifest.fixtures.find(({ name }) => name === "version-v2");
if (v1 === undefined || v2 === undefined)
throw new Error("Conformance manifest omitted the version pair");
if (v1.artifactSha256 === v2.artifactSha256)
throw new Error("Version-pair artifacts unexpectedly have equal hashes");
process.stdout.write(
`${JSON.stringify({ verified: manifest.fixtures.length, manifestPath, platform: manifest.platform })}\n`,
);
async function verifyFixture(fixture) {
const artifactPath = await confinedPath(root, fixture.artifact);
const sources = [];
for (const source of fixture.sources ?? []) {
if (typeof source.path !== "string" || typeof source.sha256 !== "string")
throw new Error(`${fixture.name}: invalid source declaration`);
const content =
source.path === "generated/large.c"
? generateLargeFixture()
: await readFile(join(process.cwd(), "tests/conformance", source.path));
: await readFile(
await confinedPath(
resolve(process.cwd(), "tests/conformance"),
source.path,
),
);
if (sha256(content) !== source.sha256)
throw new Error(
`${fixture.name}: source hash mismatch for ${source.path}`,
);
sources.push({ path: source.path, content });
}
if (
fixture.sourceSha256 !== undefined &&
sourceDigest(sources) !== fixture.sourceSha256
)
if (sourceDigest(sources) !== fixture.sourceSha256)
throw new Error(`${fixture.name}: source manifest digest mismatch`);
const artifact = await readFile(artifactPath);
if (sha256(artifact) !== fixture.artifactSha256)
throw new Error(`${fixture.name}: artifact hash mismatch`);
const fileOutput = (await exec("file", [artifactPath])).stdout;
if (!fileOutput.includes("Mach-O"))
throw new Error(`${fixture.name}: not Mach-O`);
if (!fileOutput.includes(fileMarker))
throw new Error(`${fixture.name}: not ${fileMarker}`);
const symbols = (
await exec("nm", ["-gU", artifactPath], { maxBuffer: 20 * 1024 * 1024 })
await exec("nm", [...nmArguments, artifactPath], {
maxBuffer: 20 * 1024 * 1024,
})
).stdout;
const strings = (
await exec("strings", [artifactPath], { maxBuffer: 20 * 1024 * 1024 })
).stdout;
for (const symbol of fixture.expectations.symbols ?? [])
const expectations = fixture.expectations ?? {};
for (const symbol of expectations.symbols ?? [])
if (!symbols.includes(symbol))
throw new Error(`${fixture.name}: missing symbol ${symbol}`);
for (const value of fixture.expectations.strings ?? [])
for (const value of expectations.strings ?? [])
if (!strings.includes(value))
throw new Error(`${fixture.name}: missing string ${value}`);
verifyCount(
symbols,
fixture.expectations.symbolPrefix,
fixture.expectations.symbolCount,
expectations.symbolPrefix,
expectations.symbolCount,
fixture.name,
);
verifyCount(
strings,
fixture.expectations.stringPrefix,
fixture.expectations.stringCount,
expectations.stringPrefix,
expectations.stringCount,
fixture.name,
);
}
const v1 = manifest.fixtures.find(({ name }) => name === "version-v1");
const v2 = manifest.fixtures.find(({ name }) => name === "version-v2");
if (v1?.artifactSha256 === v2?.artifactSha256)
throw new Error("Version-pair artifacts unexpectedly have equal hashes");
process.stdout.write(
`${JSON.stringify({ verified: manifest.fixtures.length, manifestPath })}\n`,
);
async function confinedPath(rootPath, declaredPath) {
if (typeof declaredPath !== "string")
throw new Error("Conformance manifest path is invalid");
const path = await realpath(resolve(rootPath, declaredPath));
const relation = relative(rootPath, path);
if (
relation === ".." ||
relation.startsWith(`..${sep}`) ||
isAbsolute(relation)
)
throw new Error(`Conformance path escapes its root: ${declaredPath}`);
return path;
}
function verifyCount(output, prefix, expected, fixture) {
if (prefix === undefined || expected === undefined) return;
@@ -6,11 +6,13 @@ import { parseArgs } from "node:util";
import { analyzeJavaScriptApplication } from "../dist/application/JavaScriptApplicationService.js";
import {
compareApplicationVersionsEvidence,
compareJavaScriptExportShapesEvidence,
traceApplicationFeatureEvidence,
} from "../dist/application/JavaScriptApplicationWorkflowService.js";
import { PermissionAuthority } from "../dist/application/PermissionAuthority.js";
import { applicationVersionComparisonResultSchema } from "../dist/domain/javascriptApplicationVersionComparisonSchemas.js";
import { applicationFeatureTraceResultSchema } from "../dist/domain/javascriptFeatureTraceSchemas.js";
import { javaScriptExportShapeComparisonResultSchema } from "../dist/domain/javascriptExportShapeComparisonSchemas.js";
import { createPermissionPolicy } from "../dist/domain/permissionPolicy.js";
const options = parseArgs({
@@ -20,6 +22,10 @@ const options = parseArgs({
"seed-kind": { type: "string", default: "module" },
"seed-value": { type: "string" },
"source-map-read-approved": { type: "boolean", default: false },
"left-module-path": { type: "string" },
"left-export-name": { type: "string" },
"right-module-path": { type: "string" },
"right-export-name": { type: "string" },
},
strict: true,
allowPositionals: false,
@@ -68,6 +74,23 @@ const traceResult =
trace === null
? null
: applicationFeatureTraceResultSchema.parse(trace.value.normalized_result);
const exportShapeSelector = resolveExportShapeSelector(left, right, options);
const exportShapeComparison =
exportShapeSelector === null
? null
: compareJavaScriptExportShapesEvidence({
left,
right,
...exportShapeSelector,
});
if (exportShapeComparison !== null && !exportShapeComparison.ok)
throw exportShapeComparison.error;
const exportShapeResult =
exportShapeComparison === null
? null
: javaScriptExportShapeComparisonResultSchema.parse(
exportShapeComparison.value.normalized_result,
);
process.stdout.write(
`${JSON.stringify({
@@ -78,6 +101,19 @@ process.stdout.write(
summary: comparisonResult.summary,
matching: comparisonResult.matching,
coverage: comparisonResult.coverage,
export_shape_comparison:
exportShapeResult === null
? null
: {
comparison_id: exportShapeResult.comparison_id,
evidence_id: exportShapeComparison.value.evidence_id,
left: exportShapeResult.left,
right: exportShapeResult.right,
summary: exportShapeResult.summary,
changes: exportShapeResult.changes,
coverage: exportShapeResult.coverage,
runtime_validation: exportShapeResult.runtime_validation,
},
trace:
traceResult === null
? null
@@ -98,6 +134,67 @@ process.stdout.write(
})}\n`,
);
function resolveExportShapeSelector(left, right, values) {
const explicit = [
values["left-module-path"],
values["left-export-name"],
values["right-module-path"],
values["right-export-name"],
];
if (explicit.some((value) => value !== undefined)) {
if (explicit.some((value) => value === undefined))
throw new Error(
"Explicit export-shape verification requires all left/right module and export selectors",
);
return {
left_module_path: explicit[0],
left_export_name: explicit[1],
right_module_path: explicit[2],
right_export_name: explicit[3],
};
}
const leftSelectors = returnShapeSelectors(left.normalized_result.graph);
const rightSelectors = new Set(
returnShapeSelectors(right.normalized_result.graph).map(selectorKey),
);
const common = leftSelectors.find((selector) =>
rightSelectors.has(selectorKey(selector)),
);
return common === undefined
? null
: {
left_module_path: common.modulePath,
left_export_name: common.exportName,
right_module_path: common.modulePath,
right_export_name: common.exportName,
};
}
function returnShapeSelectors(graph) {
const selectors = [];
for (const node of graph.nodes) {
for (const observation of node.observations) {
const properties = observation.properties;
if (
properties.semantic_role === "export-return-shapes" &&
typeof properties.module_path === "string" &&
typeof properties.exported_name === "string"
)
selectors.push({
modulePath: properties.module_path,
exportName: properties.exported_name,
});
}
}
return selectors.sort((left, right) =>
selectorKey(left).localeCompare(selectorKey(right), "en"),
);
}
function selectorKey(selector) {
return `${selector.modulePath}\0${selector.exportName}`;
}
async function analyze(path, authority) {
const result = await analyzeJavaScriptApplication(authority, {
input_path: path,
+12 -2
View File
@@ -32,11 +32,17 @@ const REQUIRED_LLM_TOPICS = [
export async function verifyPackageDiscovery({ cli, environment }) {
const help = await run(cli, ["--help"], environment);
const llms = await run(cli, ["--llms"], environment);
const doctorExecution = await runWithStatus(
const summaryExecution = await runWithStatus(
cli,
["doctor", "--json"],
environment,
);
const doctorExecution = await runWithStatus(
cli,
["doctor", "--detail", "full", "--json"],
environment,
);
const summary = json(summaryExecution.stdout);
const doctor = json(doctorExecution.stdout);
const supportedSetupHost =
doctor.checks?.find(({ name }) => name === "host")?.ok === true;
@@ -52,10 +58,14 @@ export async function verifyPackageDiscovery({ cli, environment }) {
missingLlms.length !== 0 ||
doctor.healthy !== expectedDoctorHealth ||
doctorExecution.status !== (expectedDoctorHealth ? 0 : 1) ||
summary.healthy !== doctor.healthy ||
summaryExecution.status !== doctorExecution.status ||
summary.checks !== undefined ||
!Array.isArray(summary.failed_scope_checks) ||
doctor.checks?.find(({ name }) => name === "hopper")?.ok !== true
)
throw new Error(
`packaged CLI discovery or doctor failed: ${JSON.stringify({ helpSetup: help.includes("setup"), llmsDecompile: llms.includes("decompile"), doctor })}`,
`packaged CLI discovery or doctor failed: ${JSON.stringify({ helpSetup: help.includes("setup"), llmsDecompile: llms.includes("decompile"), summary, doctor })}`,
);
return { supportedSetupHost };
}
+17
View File
@@ -1,5 +1,7 @@
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
@@ -7,6 +9,8 @@ import { TOOL_CONTRACTS } from "../dist/contracts/toolContracts.js";
import * as prompts from "./verify-package-prompts.mjs";
import { json } from "./lib/verify-package-core.mjs";
const execute = promisify(execFile);
const verifyMcpToolsAndPrompts = async (client, mcpOptions) => {
if (
(await client.listTools(undefined, mcpOptions)).tools.length !==
@@ -177,6 +181,19 @@ export async function verifyPackageMcp({
evidenceRoot,
investigationReplay,
}) {
const diagnosed = json(
(
await execute(cli, ["mcp", "doctor", "--json"], {
env: environment,
timeout: 30_000,
})
).stdout,
);
if (
diagnosed.healthy !== true ||
diagnosed.inventory?.tools?.observed !== TOOL_CONTRACTS.length
)
throw new Error("packaged production MCP doctor failed");
const transport = new StdioClientTransport({
command: cli,
args: ["mcp"],
+36 -57
View File
@@ -20,6 +20,12 @@ import {
requireSafeDiagnostics,
verifyRealHopperFixture,
} from "./lib/real-hopper-semantic.mjs";
import {
mcpTextValue,
requireEvidenceProvider,
requireMcpResult,
requireWorkflowEvidenceProvider,
} from "./lib/mcp-verifier-results.mjs";
import { openAndVerifyLargeFixture } from "./lib/real-hopper-pagination.mjs";
const execFileAsync = promisify(execFile);
const timeout = 180_000;
@@ -36,54 +42,8 @@ const parseServerArgs = (encoded) => {
const sessionsBefore = new Set(
(await readdir("/tmp")).filter((name) => name.startsWith("rea-")),
);
const textValue = (result) => {
const text = result.content?.find((item) => item.type === "text")?.text;
if (typeof text !== "string") throw new Error("Tool result omitted text");
return text;
};
const jsonValue = (result) => JSON.parse(textValue(result));
const requireSuccessfulTool = (result, operation) => {
if (result.isError === true) {
throw new Error(`${operation} failed: ${textValue(result)}`);
}
const value = jsonValue(result);
if (
value === null ||
typeof value !== "object" ||
!("normalized_result" in value)
) {
throw new Error(`${operation} omitted its evidence result`);
}
return value.normalized_result;
};
const requireHopperEvidence = (result, operation) => {
const envelope = jsonValue(result);
if (
envelope?.provider?.id !== HOPPER_PROVIDER_IDENTITY.id ||
envelope?.analysis_profile?.provider?.id !== HOPPER_PROVIDER_IDENTITY.id ||
typeof envelope.analysis_profile.provider.version !== "string"
)
throw new Error(`${operation} omitted its concrete Hopper provenance`);
};
const requireHopperWorkflowEvidence = (result, operation) => {
const envelope = jsonValue(result);
const profile = envelope?.analysis_profile;
const upstream = profile?.parameters?.upstream_analysis_profile;
if (
envelope?.provider?.id !== REA_WORKFLOW_PROVIDER.id ||
profile?.provider?.id !== REA_WORKFLOW_PROVIDER.id ||
upstream?.provider?.id !== HOPPER_PROVIDER_IDENTITY.id ||
typeof upstream.provider.version !== "string"
) {
throw new Error(
`${operation} omitted its composed workflow or upstream Hopper provenance`,
);
}
};
const textValue = mcpTextValue;
const requireSuccessfulTool = requireMcpResult;
const requireHopperSelection = (status, expected) => {
const candidates = status.analysis_provider_candidates;
@@ -286,9 +246,9 @@ const verifyCurrentTarget = async (client, options) => {
};
};
const fixtureManifestPath = process.env.REA_HOPPER_CONFORMANCE_MANIFEST_PATH;
if (!fixtureManifestPath)
throw new Error("REA_HOPPER_CONFORMANCE_MANIFEST_PATH is required");
const fixtureManifestPath =
process.env.REA_HOPPER_CONFORMANCE_MANIFEST_PATH ??
"build/conformance/manifest.json";
const fixtureTargets = await loadRealHopperFixtureTargets(fixtureManifestPath);
const targetA = fixtureTargets.primary.path;
const targetB = fixtureTargets.secondary.path;
@@ -341,7 +301,7 @@ try {
options,
);
const initialSession = await fullSessionStatus();
const initialStatus = jsonValue(initialSession);
const initialStatus = requireMcpResult(initialSession, "binary_session");
if (initialStatus.open !== false)
throw new Error("The verifier did not start without a target");
requireHopperSelection(initialStatus, {
@@ -353,7 +313,10 @@ try {
options,
);
if (opened.isError === true) throw new Error(textValue(opened));
const firstStatus = jsonValue(await fullSessionStatus());
const firstStatus = requireMcpResult(
await fullSessionStatus(),
"binary_session",
);
const providerBinding = requireHopperSelection(firstStatus, {
targetSupport: "supported",
selected: true,
@@ -366,8 +329,18 @@ try {
{ name: "binary_overview", arguments: {} },
options,
);
requireHopperEvidence(documents, "list_documents");
requireHopperWorkflowEvidence(overview, "binary_overview");
await Promise.all([
requireEvidenceProvider(
client,
documents,
"list_documents",
HOPPER_PROVIDER_IDENTITY.id,
),
requireWorkflowEvidenceProvider(client, overview, "binary_overview", {
workflowProviderId: REA_WORKFLOW_PROVIDER.id,
upstreamProviderId: HOPPER_PROVIDER_IDENTITY.id,
}),
]);
const segments = await client.callTool(
{ name: "list_segments", arguments: {} },
options,
@@ -405,7 +378,10 @@ try {
options,
);
if (switched.isError === true) throw new Error(textValue(switched));
const secondSession = jsonValue(await fullSessionStatus());
const secondSession = requireMcpResult(
await fullSessionStatus(),
"binary_session",
);
if (secondSession.path !== targetB)
throw new Error("The real session did not switch to target B");
requireHopperSelection(secondSession, {
@@ -447,7 +423,10 @@ try {
options,
);
if (closed.isError === true) throw new Error(textValue(closed));
const closedSession = jsonValue(await fullSessionStatus());
const closedSession = requireMcpResult(
await fullSessionStatus(),
"binary_session",
);
if (closedSession.open !== false)
throw new Error("The real session remained open after close_binary");
+72
View File
@@ -0,0 +1,72 @@
import { mkdtemp, readdir, realpath, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, relative, resolve } from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const vitestPath = resolve(repositoryRoot, "node_modules/vitest/vitest.mjs");
const OWNED_ENTRY = /^(?:rea-|bb-session-)/u;
const findOwnedEntries = async (root, directory = root) => {
const owned = [];
for (const entry of await readdir(directory, { withFileTypes: true })) {
const path = join(directory, entry.name);
if (OWNED_ENTRY.test(entry.name)) {
owned.push(relative(root, path));
continue;
}
if (entry.isDirectory())
owned.push(...(await findOwnedEntries(root, path)));
}
return owned;
};
const canonicalTemporaryRoot = await realpath(tmpdir());
const isolatedTemporaryRoot = await mkdtemp(
join(canonicalTemporaryRoot, "rea-test-hygiene-"),
);
try {
const result = spawnSync(
process.execPath,
[vitestPath, "run", "--coverage.enabled=false", ...process.argv.slice(2)],
{
cwd: repositoryRoot,
env: {
...process.env,
TEMP: isolatedTemporaryRoot,
TMP: isolatedTemporaryRoot,
TMPDIR: isolatedTemporaryRoot,
},
stdio: "inherit",
},
);
const failures = [];
if (result.error !== undefined) failures.push(result.error.message);
if (result.status !== 0) {
failures.push(
result.signal === null
? `Vitest exited with status ${String(result.status)}`
: `Vitest exited after signal ${result.signal}`,
);
}
const residues = await findOwnedEntries(isolatedTemporaryRoot);
if (residues.length > 0) {
failures.push(`Owned temporary residues:\n${residues.join("\n")}`);
}
if (failures.length > 0) throw new Error(failures.join("\n\n"));
process.stdout.write(
"Test temporary-directory hygiene verified: no owned residues remain.\n",
);
} finally {
await rm(isolatedTemporaryRoot, {
recursive: true,
force: true,
maxRetries: 3,
retryDelay: 25,
});
}