Files
reverse-engineering-anything/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.ts
T
morluto 5c53bcaed8 feat(mcp)!: retire the full schema profiles and declare schema facts as typed annotations (#10693)
* test(mcp): check advertised schemas against a portable dialect in every profile

* fix(mcp): re-emit advertised patterns in a portable regex grammar

* fix(mcp): present discover_tools input through the selected profile

The hot-cold catalog registered discover_tools directly with the SDK, so
the default compact input profile still advertised its canonical schema,
including page-size defaults clients apply on their own (#5322). Route
every listed input schema, transport discovery included, through one
server-owned presentation, and pass the selected presentation to the
deferred server, which serves recorded tool schemas but not discovery.

* fix(mcp): keep the Evidence union on described borrowed inputs

borrowEvidenceInput installed its advertised projection on one schema
instance. A call site's .describe() rebuilds the schema from its
definition, so match_native_functions advertised left and right as
unconstrained values in every input profile. Install the projection in
the borrowed parser's constructor so derived schemas keep it, for both
borrowed inputs and borrowed arrays.

* fix(mcp): validate advertised dialect by selected profile

* fix(mcp): preserve schema widening through references

* feat(mcp): project compact input schemas into the portable advertised dialect

One projection (advertisedDialectProjection.ts) owns the compact input
advertisement: one type per node, items on every array, string literals
as enums, oneOf widened to anyOf, allOf merged, tuples as element unions,
exclusive bounds made inclusive, and every keyword outside the dialect
dropped. Each rewrite is exact or widening; server validation is
unchanged. The root description and sentences for dropped cross-field
constraints move to the tool description, which Codex and Zed keep.

The compact baseline falls to nullable values only (29), which the
dialect cannot express without narrowing an input. The gateway shape
repairs (typeArrayItemUnions, hasGatewayIncompatibleShape), the second
dependentRequired-to-prose copy and the strict-gateway test denylist are
removed; the dialect checker gates the inline presentation instead.

* feat(mcp): omit output schemas from tools/list by default

No surveyed model API reads an output schema, MCP client validators
repeat REA's own result validation, and complete output schemas were
about 92% of the default tools/list. REA_MCP_OUTPUT_SCHEMA_PROFILE now
resolves to off through one owner (resolveMcpOutputSchemaProfile);
compact and full remain selectable. structuredContent is still
delivered, and the deferred server serves both off and full from the
recorded catalog with the matching recorded identity.

Tests and artifact verifiers that validate results against complete
advertised output contracts select full explicitly.

* docs: describe omitted output schemas as the default in README translations

* fix(mcp): select schemas in verification workflows

* fix(mcp): refuse zero-padded repeat bounds and record host-specific path patterns

* fix(mcp): keep projected schemas permissive

* fix(mcp): keep references valid when presentation widens their targets

* fix(mcp): keep a single union branch's closure scoped to its properties

* fix(mcp): select complete output schemas in the Electron verifier

* fix(mcp): select complete output schemas in standalone verifier probes

* fix(mcp): keep an allOf member's tuple tail with its own positions

* fix(mcp): relax references into negations and conditionals presentation may remove

* refactor(contracts): declare root discriminators as typed schema annotations

* test(mcp): select the borrowed Evidence contract from its family

* fix(mcp): keep astral literals and dynamic references widening in every mode

* fix(mcp): omit astral literals and relax untracked references when presentation widens

* fix(mcp): select complete output schemas in every verifier transport

* fix(mcp): read reference pointers by schema position, not segment spelling

* fix(mcp): protect references into collapsing boolean unions and keep referencing branches out of the collapse

* fix(mcp): keep reduced schemas open when their root admits names by pattern

* test(mcp): keep the reduced-schema pattern case outside the size-limited block

* fix(mcp): omit patterns whose classes name astral characters

* fix(mcp): decide union collapse and pointer protection from canonical branches

* docs(mcp): document non-u astral matching and pin BMP agreement across V8 modes

* fix(mcp): keep prototype-named properties as own properties in the dialect projection

* test(mcp): select full output schemas in packet and signal schema checks

* test(mcp): expect the advertised base64 schema to omit the unbounded pad-bit probe

* fix(mcp): protect references into unevaluated keywords lost evaluation removes

* fix(mcp): validate the doctor probe reply against the canonical output contract (#10655)

* fix(mcp): validate the doctor probe reply against the canonical output contract

* test(mcp): replay doctor probe validation under every output profile

* test(mcp): accept typed-branch nullable unions in the advertised dialect (#10649)

* test(mcp): select full output schemas in HTTP session workflows

* fix(mcp): emit stack-safe classes with non-ASCII members and protect draft-07 reference siblings

* fix(mcp): protect references into literal siblings of relaxed draft-07 references

* feat(mcp): omit output schemas from tools/list by default (#10646)

* feat(mcp): omit output schemas from tools/list by default

No surveyed model API reads an output schema, MCP client validators
repeat REA's own result validation, and complete output schemas were
about 92% of the default tools/list. REA_MCP_OUTPUT_SCHEMA_PROFILE now
resolves to off through one owner (resolveMcpOutputSchemaProfile);
compact and full remain selectable. structuredContent is still
delivered, and the deferred server serves both off and full from the
recorded catalog with the matching recorded identity.

Tests and artifact verifiers that validate results against complete
advertised output contracts select full explicitly.

* fix(mcp): select schemas in verification workflows

* fix(mcp): select complete output schemas in the Electron verifier

* fix(mcp): select complete output schemas in standalone verifier probes

* fix(mcp): select complete output schemas in every verifier transport

* test(mcp): select full output schemas in packet and signal schema checks

* fix(mcp): validate the doctor probe reply against the canonical output contract (#10655)

* fix(mcp): validate the doctor probe reply against the canonical output contract

* test(mcp): replay doctor probe validation under every output profile

* test(mcp): accept typed-branch nullable unions in the advertised dialect (#10649)

* test(mcp): select full output schemas in HTTP session workflows

* fix(mcp): keep the Evidence union on described borrowed inputs (#10597)

* fix(mcp): keep the Evidence union on described borrowed inputs

borrowEvidenceInput installed its advertised projection on one schema
instance. A call site's .describe() rebuilds the schema from its
definition, so match_native_functions advertised left and right as
unconstrained values in every input profile. Install the projection in
the borrowed parser's constructor so derived schemas keep it, for both
borrowed inputs and borrowed arrays.

* test(mcp): select the borrowed Evidence contract from its family

* docs(mcp): admit baseline growth only for restored contract declarations

* fix(mcp): state reduced multi-type properties as typed branches, not type lists

The reduced fallback derived a property's types and emitted them as a type
list, which Gemini, Moonshot and Ark reject. A property whose canonical
schema is anyOf string and number therefore traded a typed union for a
rejected construct when the inline projection fell back. Emit one type, or
anyOf typed branches, so [T, null] becomes the dialect's nullable union.

* feat(mcp)!: retire the full schema profiles and declare complete observations as a typed annotation (#10718)

* refactor(mcp): declare complete observations as a typed annotation applied only on the wire

* test(mcp): compare complete-observation declarations with their owning text

* refactor(schema): couple Zod checks with their JSON Schema constraint keywords (#10725)

* refactor(schema): couple Zod checks with their JSON Schema constraint keywords

* refactor(schema): declare pattern approximations and object output roots as typed annotations (#10754)

* refactor(schema): declare pattern approximations and object output roots as typed annotations

* fix(schema): refuse pattern declarations JSON Schema cannot state

* test(schema): select guided_workflows from its contract family

* feat(mcp)!: retire the full input and output schema profiles (#10841)

* feat(mcp)!: retire the full input and output schema profiles

The compact input presentation is now the only advertised input schema, and
output schemas are either omitted (`off`, the default) or bounded
(`compact`). Catalog identity, the build-recorded digests and the recorded
startup catalog collapse to those presentations: two digest profiles instead
of six, one recorded catalog instead of two, and no input dialect baseline.

Tests and verifiers that validated replies against listed full output
schemas now validate against the canonical output contract, which REA
already enforces server-side; tests that asserted canonical input
restrictions read the canonical input schema instead of a full listing.

BREAKING CHANGE: `REA_MCP_INPUT_SCHEMA_PROFILE=full` and
`REA_MCP_OUTPUT_SCHEMA_PROFILE=full` are refused at startup and by `rea setup`
with a configuration error naming the setting. Remove the setting from the
client registration (or rerun setup with `REA_MCP_INPUT_SCHEMA_PROFILE=compact`
/ `REA_MCP_OUTPUT_SCHEMA_PROFILE=compact`). `REA_MCP_INPUT_SCHEMA_PROFILE`
still accepts `compact`. Server-side validation is unchanged.

* test(mcp): validate replies against canonical output contracts at every listed-schema reader

tools/list omits output schemas by default, so fixtures, verifiers and the
Android analysis runners that read a listed outputSchema now bind the
canonical contract instead. connectLocalToolsMcp and advertisedMcpToolSchemas
hand the SDK a definition carrying the canonical output schema, so the SDK
client and caller-supplied validators check every successful reply.

* test(mcp): resolve Android runners' output contracts from the selected repository

The Android efficiency runners imported the canonical output-schema helper from the harness checkout while --repository selects the revision under test. Import it from the selected repository, as the runners already do for the SDK and Ajv.

* test(mcp): let Android runners compare revisions before the canonical output helper

A selected revision without scripts/lib/canonical-output-schema.mjs could not start the Android runners. Choose the output contracts in one harness helper: the selected revision's canonical contracts when it has them, otherwise its listed schemas under the full output profile it still supports.

* fix(scripts): keep caller launch settings when the real Hopper verifier builds its server environment

The verifier deleted REA_VERIFY_SERVER_COMMAND and REA_VERIFY_SERVER_ARGS_JSON from process.env itself before reading them, so a caller selecting an installed REA command silently ran the checkout's dist/main.js. Copy the environment, as main does, so only the child's environment changes.

* test(mcp): validate whole replies against canonical output contracts wherever a listed definition is held

tools/list omits output schemas by default and the full output profile is gone, so tests that handed the SDK a listed definition no longer checked complete replies. Attach the canonical output schema with withCanonicalOutputSchema at every held REA tool definition. Environment-served tools (not REA contracts), and the deferred-runtime and doctor tests that exercise per-profile listings, keep their listed definitions.

* test(mcp): record the advertised catalog summary without the retired full profiles

Retiring the full input and output profiles leaves only the compact input and compact output listings, so the summary drops the full-profile digests and every pattern only the full listings carried. Regenerated with npm run verify:advertised-schemas -- --update-summary.
2026-11-15 21:51:18 +08:00

1019 lines
34 KiB
TypeScript

import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { expect } from "vitest";
import { Scalar, stringify } from "yaml";
import {
effectiveClientServer,
parseClientConfiguration,
clientRegistrationEntry,
} from "../../../src/application/ClientConfigurationDocument.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
// Registration configuration tests must not discover installed providers or
// plan provider-environment edits based on the machine running the suite.
const missingHopperAndGhidraEnvironment = (home: string) => ({
HOPPER_LAUNCHER_PATH: join(home, "missing-hopper"),
GHIDRA_INSTALL_DIR: join(home, "missing-ghidra"),
JAVA_HOME: join(home, "missing-java"),
});
cliTest(
"retains selected MCP settings and unavailable provider paths in a new registration",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-selected-registration-");
const config = join(home, ".qwen/settings.json");
const selected = {
HOPPER_LAUNCHER_PATH: join(home, "missing-hopper"),
HOPPER_LOADER_ARGS_JSON: '["", "--loader", "Mach-O"]',
GHIDRA_INSTALL_DIR: join(home, "offline-ghidra"),
GHIDRA_HEADLESS_MAXMEM: "512M",
GHIDRA_MAXMEM: "3G",
JAVA_HOME: join(home, "offline-jdk"),
REA_IDA_MCP_CONFIG: join(home, "offline-ida.json"),
REA_JADX_MCP_JAR: join(home, "offline-jadx.jar"),
REA_KUNA_COMMAND: join(home, "offline-kuna"),
REA_ADB_PATH: join(home, "offline-adb"),
REA_APKTOOL_COMMAND: join(home, "offline-apktool"),
REA_TSHARK_COMMAND: join(home, "offline-tshark"),
REA_CAPINFOS_COMMAND: join(home, "offline-capinfos"),
REA_TSHARK_PRLIMIT_COMMAND: join(home, "offline-prlimit"),
REA_OBJDUMP_COMMAND: join(home, "offline-objdump"),
REA_GDB_COMMAND: join(home, "offline-gdb"),
REA_RIZIN_COMMAND: join(home, "offline-rizin"),
REA_CUTTER_BRIDGE_DIR: join(home, "cutter-bridge"),
REA_WABT_BIN_DIRECTORY: join(home, "wabt"),
REA_WAKARU_COMMAND: join(home, "offline-wakaru"),
REA_JAVASCRIPT_PRLIMIT_COMMAND: join(home, "javascript-prlimit"),
REA_BINWALK_COMMAND: join(home, "offline-binwalk"),
REA_UNBLOB_COMMAND: join(home, "offline-unblob"),
REA_FIRMWARE_PRLIMIT_COMMAND: join(home, "firmware-prlimit"),
REA_EVM_PRLIMIT_COMMAND: join(home, "evm-prlimit"),
REA_SIGROK_COMMAND: join(home, "offline-sigrok"),
REA_SIGROK_PRLIMIT_COMMAND: join(home, "sigrok-prlimit"),
REA_MITMDUMP_COMMAND: join(home, "offline-mitmdump"),
REA_BROWSER_EXECUTABLE: join(home, "offline-chromium"),
REA_BROWSER_NO_SANDBOX: "false",
REA_PWNTOOLS_PYTHON: join(home, "offline-python"),
REA_PWNTOOLS_MAX_INPUT_BYTES: "67108864",
REA_PWNDBG_GDB: join(home, "pwndbg-gdb"),
REA_PWNDBG_GDBINIT: join(home, "pwndbg-gdbinit"),
REA_PWNDBG_VENV_PATH: join(home, "pwndbg-venv"),
...(process.platform === "darwin"
? {}
: {
REA_DARWIN_SWIFTC_PATH: join(home, "offline-swiftc"),
REA_DARWIN_MODULE_CACHE_PATH: join(home, "swift-module-cache"),
SDKROOT: join(home, "macos-sdk"),
}),
REA_SWIFTC_COMPILE_TIMEOUT_MS: "180000",
REA_LOG_LEVEL: "warn",
REA_ASAR_MAX_LISTING_BYTES: "134217728",
REA_GHIDRA_VALUE_FLOW_MAX_OPERATIONS: "6000",
REA_GHIDRA_VALUE_FLOW_MAX_INPUTS_PER_OPERATION: "128",
REA_GHIDRA_VALUE_FLOW_MAX_EDGES: "24000",
REA_GHIDRA_DECOMPILE_MAX_PAYLOAD_MIB: "128",
REA_REFERENCE_SECRET_PATTERNS_JSON: '["explicit-private-value"]',
REA_ANALYSIS_PROVIDER: "ghidra",
REA_MCP_INPUT_SCHEMA_PROFILE: "compact",
REA_MCP_OUTPUT_SCHEMA_PROFILE: "off",
REA_MCP_MAX_RESPONSE_BYTES: "20971520",
REA_MCP_TOOL_FAMILIES: "session",
};
const environment = {
HOME: home,
USERPROFILE: home,
QWEN_HOME: join(home, ".qwen"),
...selected,
CALLER_UNRELATED_SETTING: "do not copy",
REA_UNKNOWN_SETTING: "do not copy",
REA_PROCESS_RUN_ID: "do not copy",
REA_TOKEN: "do not copy",
HOPPER_TARGET_PATH: "do not copy",
};
const run = () =>
cli.run({
arguments: [
"setup",
"--client",
"qwen_code",
"--skill=false",
"--yes",
"--json",
],
cwd: home,
environment,
});
const setup = await run();
expect(setup.exitCode, setup.stdout).toBe(0);
const configured = await readFile(config, "utf8");
expect(JSON.parse(configured)).toMatchObject({
mcpServers: { rea: { env: selected } },
});
expect(configured).not.toContain("do not copy");
// A later setup must update a selection rather than retaining the first value.
selected.REA_MCP_TOOL_FAMILIES = "session,application";
environment.REA_MCP_TOOL_FAMILIES = selected.REA_MCP_TOOL_FAMILIES;
selected.REA_OBJDUMP_COMMAND = join(home, "replacement-objdump");
environment.REA_OBJDUMP_COMMAND = selected.REA_OBJDUMP_COMMAND;
selected.HOPPER_LOADER_ARGS_JSON = "[]";
environment.HOPPER_LOADER_ARGS_JSON = selected.HOPPER_LOADER_ARGS_JSON;
// Empty headless heap explicitly selects the lower-priority caller value.
selected.GHIDRA_HEADLESS_MAXMEM = "";
selected.GHIDRA_MAXMEM = "768M";
environment.GHIDRA_HEADLESS_MAXMEM = selected.GHIDRA_HEADLESS_MAXMEM;
environment.GHIDRA_MAXMEM = selected.GHIDRA_MAXMEM;
const updated = await run();
expect(updated.exitCode, updated.stdout).toBe(0);
const updatedConfiguration = await readFile(config, "utf8");
expect(JSON.parse(updatedConfiguration)).toMatchObject({
mcpServers: { rea: { env: selected } },
});
expect(updatedConfiguration).not.toContain("do not copy");
const repeated = await run();
expect(repeated.exitCode, repeated.stdout).toBe(0);
expect(repeated.json).toMatchObject({
plannedActions: [],
appliedActions: [],
});
expect(await readFile(config, "utf8")).toBe(updatedConfiguration);
},
);
cliTest(
"persists, updates and validates tool-family scopes without losing client configuration",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-family-registration-");
const config = join(home, ".qwen/settings.json");
const foreign = { command: "foreign-tool", args: ["keep"] };
const original = JSON.stringify({ mcpServers: { foreign } });
await mkdir(dirname(config), { recursive: true });
await writeFile(config, original);
const environment = {
HOME: home,
USERPROFILE: home,
QWEN_HOME: join(home, ".qwen"),
...missingHopperAndGhidraEnvironment(home),
REA_MCP_INPUT_SCHEMA_PROFILE: "compact",
REA_MCP_OUTPUT_SCHEMA_PROFILE: "compact",
};
const run = (families: string) =>
cli.run({
arguments: [
"setup",
"--client",
"qwen_code",
"--tool-families",
families,
"--skill=false",
"--yes",
"--json",
],
cwd: home,
environment,
});
const first = await run("session");
expect(first.exitCode, first.stdout).toBe(0);
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original);
const scope = "native,application,session";
const updated = await run(scope);
expect(updated.exitCode, updated.stdout).toBe(0);
const selected = await readFile(config, "utf8");
expect(JSON.parse(selected)).toMatchObject({
mcpServers: {
foreign,
rea: {
env: {
REA_MCP_TOOL_FAMILIES: scope,
REA_MCP_INPUT_SCHEMA_PROFILE: "compact",
REA_MCP_OUTPUT_SCHEMA_PROFILE: "compact",
},
},
},
});
const backup = await readFile(`${config}.rea.backup`, "utf8");
const repeated = await run(scope);
expect(repeated.exitCode, repeated.stdout).toBe(0);
expect(repeated.json).toMatchObject({
plannedActions: [],
appliedActions: [],
});
const rejected = await run("session,typo");
expect(rejected.exitCode).not.toBe(0);
expect(rejected.stdout + rejected.stderr).toContain(
"REA_MCP_TOOL_FAMILIES",
);
expect(await readFile(config, "utf8")).toBe(selected);
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(backup);
},
);
cliTest.skipIf(process.platform !== "win32")(
"rejects lowercase Windows provider settings in doctor and setup without writing",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-registration-case-");
const config = join(home, ".cursor/mcp.json");
await mkdir(dirname(config), { recursive: true });
const original = JSON.stringify({
mcpServers: {
rea: clientRegistrationEntry(
"json",
[process.execPath, resolve("scripts/rea.mjs"), "mcp"],
{ rea_analysis_provider: "invalid provider" },
),
},
});
await writeFile(config, original);
const environment = {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
...missingHopperAndGhidraEnvironment(home),
};
const doctor = await cli.run({
arguments: ["doctor", "--client", "cursor", "--skill=false", "--json"],
cwd: home,
environment,
});
expect(doctor.exitCode).toBe(1);
expect(doctor.json).toMatchObject({
scope_checks: expect.arrayContaining([
expect.objectContaining({
name: "registration:cursor",
ok: false,
classification: "config_drift",
remediation: expect.stringContaining("REA_ANALYSIS_PROVIDER"),
}),
]),
});
const setup = await cli.run({
arguments: [
"setup",
"--client",
"cursor",
"--skill=false",
"--yes",
"--json",
],
cwd: home,
environment,
});
expect(setup.exitCode).toBe(1);
expect(setup.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining("REA_ANALYSIS_PROVIDER"),
});
expect(await readFile(config, "utf8")).toBe(original);
await expect(access(`${config}.rea.backup`)).rejects.toMatchObject({
code: "ENOENT",
});
},
);
const scenarios = [
{
client: "cursor",
format: "json",
path: ".cursor/mcp.json",
setting: "HOPPER_LOADER_ARGS_JSON",
invalid: { HOPPER_LOADER_ARGS_JSON: "{" },
repaired: { HOPPER_LOADER_ARGS_JSON: '["", "--loader", "Mach-O"]' },
},
{
client: "dsh",
format: "dsh",
path: ".dsh/cordis.patch.yml",
setting: "REA_GHIDRA_COMPILER_SPEC_ID",
invalid: { REA_GHIDRA_COMPILER_SPEC_ID: "borlandcpp" },
repaired: {
REA_GHIDRA_COMPILER_SPEC_ID: "borlandcpp",
REA_GHIDRA_LANGUAGE_ID: "x86:LE:32:default",
},
},
] as const;
cliTest.for([
{
client: "cursor",
format: "json",
path: ".cursor/mcp.json",
position: "value",
},
{
client: "cursor",
format: "json",
path: ".cursor/mcp.json",
position: "name",
},
{
client: "dsh",
format: "dsh",
path: ".dsh/cordis.patch.yml",
position: "value",
},
{
client: "dsh",
format: "dsh",
path: ".dsh/cordis.patch.yml",
position: "name",
},
{
client: "dsh",
format: "dsh",
path: ".dsh/cordis.patch.yml",
position: "expression name",
},
] as const)(
"refuses a NUL environment $position in $client before setup writes",
async (scenario, { cli }) => {
const home = await createTestTempDirectory("rea-registration-nul-");
const config = join(home, scenario.path);
await mkdir(dirname(config), { recursive: true });
const environment = {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
DSH_HOME: join(home, ".dsh"),
...missingHopperAndGhidraEnvironment(home),
};
const registration = (env: Readonly<Record<string, string>>) => {
const entry = clientRegistrationEntry(
scenario.format,
[process.execPath, resolve("scripts/rea.mjs"), "mcp"],
env,
);
if (scenario.position === "expression name")
entry.env = Object.fromEntries(
Object.entries(env).map(([key, value]) => {
if (!key.includes("\0")) return [key, value];
const expression = new Scalar("process.env.CALLER_SETTING");
expression.tag = "tag:yaml.org,2002:js";
return [key, expression];
}),
);
return scenario.format === "dsh"
? stringify([
{
insert: [
{
id: "rea-mcp",
name: "@deepseek-ai/dsh-mcp-client",
config: entry,
},
],
},
])
: JSON.stringify({ mcpServers: { rea: entry } });
};
const valueMarker = "reaNulFixtureValue_6c04e2";
const original = registration(
scenario.position === "value"
? { CALLER_SETTING: `${valueMarker}\0value` }
: { ["CALLER\0SETTING"]: `${valueMarker} value` },
);
await writeFile(config, original);
const doctor = await cli.run({
arguments: [
"doctor",
"--client",
scenario.client,
"--skill=false",
"--json",
],
cwd: home,
environment,
});
expect(doctor.exitCode).toBe(1);
expect(doctor.json).toMatchObject({
scope_checks: expect.arrayContaining([
expect.objectContaining({
name: `registration:${scenario.client}`,
ok: false,
classification: "config_drift",
remediation: expect.stringContaining("NUL"),
}),
]),
});
const setup = await cli.run({
arguments: [
"setup",
"--client",
scenario.client,
"--skill=false",
"--yes",
"--json",
],
cwd: home,
environment,
});
expect(setup.exitCode).toBe(1);
expect(setup.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining("NUL"),
});
expect(setup.stdout + doctor.stdout).not.toContain(valueMarker);
expect(await readFile(config, "utf8")).toBe(original);
await expect(access(`${config}.rea.backup`)).rejects.toMatchObject({
code: "ENOENT",
});
const repaired = registration({
CALLER_SETTING: "ordinary\nvalue=二\t",
EMPTY_SETTING: "",
});
await writeFile(config, repaired);
const healthy = await cli.run({
arguments: [
"doctor",
"--client",
scenario.client,
"--skill=false",
"--json",
],
cwd: home,
environment,
});
expect(healthy.exitCode, healthy.stdout).toBe(0);
expect(healthy.json).toMatchObject({ healthy: true });
expect(await readFile(config, "utf8")).toBe(repaired);
},
);
for (const scenario of scenarios)
cliTest(
`setup and doctor reject ${scenario.client} overrides rejected by MCP startup`,
async ({ cli }) => {
const home = await createTestTempDirectory("rea-registration-runtime-");
const config = join(home, scenario.path);
await mkdir(dirname(config), { recursive: true });
const environment = {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
DSH_HOME: join(home, ".dsh"),
...missingHopperAndGhidraEnvironment(home),
};
const registration = (env: Readonly<Record<string, string>>) => {
const server = {
command: "npx",
args: ["-y", "rea-agents@6.6.0", "mcp"],
env: {
CALLER_SETTING: "keep exactly",
["__proto__"]: "retain caller key",
...env,
},
};
return scenario.client === "dsh"
? stringify([
{
insert: [
{
id: "rea-mcp",
name: "@deepseek-ai/dsh-mcp-client",
config: {
serverName: "rea",
transport: "stdio",
...server,
},
},
],
},
])
: JSON.stringify({ mcpServers: { rea: server } });
};
const original = registration(scenario.invalid);
await writeFile(config, original);
const startup = await cli.run({
arguments: ["mcp"],
cwd: home,
environment: { ...environment, ...scenario.invalid },
});
expect(startup.exitCode).toBe(1);
expect(startup.stderr).toContain(scenario.setting);
expect(startup.stdout).toBe("");
const run = (args: readonly string[]) =>
cli.run({ arguments: [...args, "--json"], cwd: home, environment });
const setup = await run([
"setup",
"--client",
scenario.client,
"--skill=false",
"--yes",
]);
expect(setup.exitCode).toBe(1);
expect(setup.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining(scenario.setting),
});
const doctor = await run(["doctor", "--client", scenario.client]);
expect(doctor.exitCode).toBe(1);
expect(doctor.json).toMatchObject({
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({
client: scenario.client,
state: "invalid",
remediation: expect.stringContaining(scenario.setting),
}),
]),
},
});
expect(await readFile(config, "utf8")).toBe(original);
await expect(access(`${config}.rea.backup`)).rejects.toMatchObject({
code: "ENOENT",
});
// Model the caller repairing the named setting before rerunning setup.
const repaired = registration(scenario.repaired);
await writeFile(config, repaired);
const configured = await run([
"setup",
"--client",
scenario.client,
"--skill=false",
"--yes",
]);
expect(configured.exitCode, configured.stdout).toBe(0);
const text = await readFile(config, "utf8");
const parsed = parseClientConfiguration(text, scenario.format);
expect(effectiveClientServer(parsed, "rea")).toMatchObject({
env: {
CALLER_SETTING: "keep exactly",
["__proto__"]: "retain caller key",
...scenario.repaired,
},
});
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(repaired);
const repeated = await run([
"setup",
"--client",
scenario.client,
"--skill=false",
"--yes",
]);
expect(repeated.json).toMatchObject({
status: "ready",
appliedActions: [],
plannedActions: [],
});
expect(await readFile(config, "utf8")).toBe(text);
},
);
cliTest(
"OpenCode CLI validates dependent settings after merging JSON and JSONC",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-layered-runtime-cli-");
const directory = join(home, ".config/opencode");
await mkdir(directory, { recursive: true });
const lower = join(directory, "opencode.json");
const upper = join(directory, "opencode.jsonc");
const content = (env: Record<string, string>) =>
JSON.stringify({
mcp: {
rea: clientRegistrationEntry(
"opencode",
[process.execPath, resolve("scripts/rea.mjs"), "mcp"],
env,
),
},
});
const lowerContent = content({
REA_GHIDRA_LANGUAGE_ID: "x86:LE:32:default",
});
const upperContent = content({
...missingHopperAndGhidraEnvironment(home),
REA_GHIDRA_COMPILER_SPEC_ID: "borlandcpp",
});
await writeFile(lower, lowerContent);
await writeFile(upper, upperContent);
const environment = {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
...missingHopperAndGhidraEnvironment(home),
};
const run = (args: readonly string[]) =>
cli.run({ arguments: [...args, "--json"], cwd: home, environment });
const setup = await run([
"setup",
"--client",
"opencode",
"--skill=false",
"--yes",
]);
expect(setup.exitCode, setup.stdout).toBe(0);
expect(setup.json).toMatchObject({
status: "ready",
plannedActions: [],
appliedActions: [],
});
const doctor = await run(["doctor", "--client", "opencode"]);
expect(doctor.exitCode, doctor.stdout).toBe(0);
expect(doctor.json).toMatchObject({
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({ client: "opencode", state: "aligned" }),
]),
},
});
expect(await readFile(lower, "utf8")).toBe(lowerContent);
expect(await readFile(upper, "utf8")).toBe(upperContent);
await writeFile(lower, content({ CALLER_SETTING: "retained" }));
const missing = await run([
"setup",
"--client",
"opencode",
"--skill=false",
"--yes",
]);
expect(missing.exitCode).toBe(1);
expect(missing.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining("REA_GHIDRA_COMPILER_SPEC_ID"),
});
const invalidDoctor = await run(["doctor", "--client", "opencode"]);
expect(invalidDoctor.exitCode).toBe(1);
expect(invalidDoctor.json).toMatchObject({
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({ client: "opencode", state: "invalid" }),
]),
},
});
expect(await readFile(upper, "utf8")).toBe(upperContent);
for (const path of [lower, upper])
await expect(access(`${path}.rea.backup`)).rejects.toMatchObject({
code: "ENOENT",
});
},
);
cliTest(
"public setup propagates selected provider deadlines and input profile to Codex and Kimi",
async ({ cli }) => {
const home = await createTestTempDirectory(
"rea-selected-registration-env-",
);
const codexHome = join(home, "codex");
const kimiHome = join(home, "kimi");
await Promise.all(
[codexHome, kimiHome].map((path) => mkdir(path, { recursive: true })),
);
const environment = {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
CODEX_HOME: codexHome,
KIMI_CODE_HOME: kimiHome,
...missingHopperAndGhidraEnvironment(home),
REA_ANALYSIS_PROVIDER: "auto",
REA_BRIDGE_MAX_REQUEST_BYTES: "33554432",
REA_GHIDRA_STARTUP_TIMEOUT_MS: "2700001",
REA_HOPPER_STARTUP_TIMEOUT_MS: "2800002",
REA_JEB_MCP_TIMEOUT_MS: "2900003",
REA_MCP_INPUT_SCHEMA_PROFILE: "compact",
REA_CAPTURE_DECODER_OLD_GENERATION_MIB: "256",
REA_REGEX_MATCHING_DEADLINE_MS: "10000",
REA_REGEX_WORKER_HEAP_REQUEST_MIB: "256",
REA_MCP_INITIALIZE_BUDGET_MS: "16000",
REA_MCP_TOOLS_LIST_BUDGET_MS: "6000",
REA_MCP_FIRST_CATALOG_BUDGET_MS: "21000",
REA_MCP_DOCTOR_DEADLINE_MS: "31000",
REA_UNRELATED_MARKER: "do-not-persist",
};
const run = (arguments_: readonly string[]) =>
cli.run({
arguments: [...arguments_, "--json"],
cwd: home,
environment,
});
for (const client of ["codex", "kimi"] as const) {
const setup = await run([
"setup",
"--client",
client,
"--skill=false",
"--yes",
]);
expect(setup.exitCode, setup.stderr).toBe(0);
expect(setup.json).toMatchObject({ status: "ready" });
}
const codexConfig = await readFile(join(codexHome, "config.toml"), "utf8");
const codexRegistration = effectiveClientServer(
parseClientConfiguration(codexConfig, "toml"),
"rea",
);
expect(codexRegistration).toMatchObject({ tool_timeout_sec: 3021 });
expect(codexConfig).toContain('REA_BRIDGE_MAX_REQUEST_BYTES = "33554432"');
expect(codexConfig).toContain('REA_JEB_MCP_TIMEOUT_MS = "2900003"');
expect(codexConfig).toContain(
'REA_CAPTURE_DECODER_OLD_GENERATION_MIB = "256"',
);
expect(codexConfig).toContain('REA_REGEX_MATCHING_DEADLINE_MS = "10000"');
expect(codexConfig).toContain('REA_REGEX_WORKER_HEAP_REQUEST_MIB = "256"');
expect(codexConfig).toContain('REA_MCP_INITIALIZE_BUDGET_MS = "16000"');
expect(codexConfig).toContain('REA_MCP_TOOLS_LIST_BUDGET_MS = "6000"');
expect(codexConfig).toContain('REA_MCP_FIRST_CATALOG_BUDGET_MS = "21000"');
expect(codexConfig).toContain('REA_MCP_DOCTOR_DEADLINE_MS = "31000"');
expect(codexConfig).not.toContain("REA_UNRELATED_MARKER");
const kimiPath = join(kimiHome, "mcp.json");
const kimiRegistration = effectiveClientServer(
parseClientConfiguration(await readFile(kimiPath, "utf8"), "kimi"),
"rea",
);
expect(kimiRegistration).toMatchObject({
toolTimeoutMs: 3_020_003,
env: {
REA_ANALYSIS_PROVIDER: "auto",
REA_BRIDGE_MAX_REQUEST_BYTES: "33554432",
REA_GHIDRA_STARTUP_TIMEOUT_MS: "2700001",
REA_HOPPER_STARTUP_TIMEOUT_MS: "2800002",
REA_JEB_MCP_TIMEOUT_MS: "2900003",
REA_MCP_INPUT_SCHEMA_PROFILE: "compact",
REA_CAPTURE_DECODER_OLD_GENERATION_MIB: "256",
REA_REGEX_MATCHING_DEADLINE_MS: "10000",
REA_REGEX_WORKER_HEAP_REQUEST_MIB: "256",
REA_MCP_INITIALIZE_BUDGET_MS: "16000",
REA_MCP_TOOLS_LIST_BUDGET_MS: "6000",
REA_MCP_FIRST_CATALOG_BUDGET_MS: "21000",
REA_MCP_DOCTOR_DEADLINE_MS: "31000",
},
});
expect(await readFile(kimiPath, "utf8")).not.toContain(
"REA_UNRELATED_MARKER",
);
const doctor = await run(["doctor", "--client", "kimi"]);
expect(doctor.exitCode, doctor.stderr).toBe(0);
expect(doctor.json).toMatchObject({
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({ client: "kimi", state: "aligned" }),
]),
},
});
},
);
for (const [client, provider] of [
["codex", "ida"],
["kimi", "ida"],
["kimi", "auto"],
] as const)
cliTest(
`public ${client} setup and doctor use the effective IDA registration request budget with ${provider} selection`,
async ({ cli }) => {
const home = await createTestTempDirectory(
"rea-ida-registration-budget-",
);
const clientHome = join(home, client);
await mkdir(clientHome, { recursive: true });
const idaConfig = join(home, "ida.json");
const writeRegistration = (timeoutMs: number) =>
writeFile(
idaConfig,
JSON.stringify({
url: "http://127.0.0.1:12345/mcp",
protocol: "legacy",
headers: { Authorization: "Bearer fixture-credential" },
timeoutMs,
}),
);
await writeRegistration(1_800_001);
const environment = {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
CODEX_HOME: clientHome,
KIMI_CODE_HOME: clientHome,
...missingHopperAndGhidraEnvironment(home),
};
const setupArguments = [
"setup",
"--client",
client,
"--skill=false",
"--yes",
"--json",
];
const configured = await cli.run({
arguments: setupArguments,
cwd: home,
environment: {
...environment,
REA_ANALYSIS_PROVIDER: provider,
REA_IDA_MCP_CONFIG: idaConfig,
},
});
expect(configured.exitCode, configured.stdout).toBe(0);
const config = join(
clientHome,
client === "codex" ? "config.toml" : "mcp.json",
);
const text = await readFile(config, "utf8");
expect(
effectiveClientServer(
parseClientConfiguration(text, client === "codex" ? "toml" : "kimi"),
"rea",
),
).toMatchObject({
...(client === "codex"
? { tool_timeout_sec: 1921 }
: { toolTimeoutMs: 1_920_001 }),
env: { REA_ANALYSIS_PROVIDER: provider, REA_IDA_MCP_CONFIG: idaConfig },
});
expect(text).not.toContain("fixture-credential");
const run = (arguments_: readonly string[]) =>
cli.run({ arguments: arguments_, cwd: home, environment });
const healthy = await run(["doctor", "--client", client, "--json"]);
expect(healthy.exitCode, healthy.stdout).toBe(0);
expect(JSON.stringify(healthy.json)).not.toContain('"advisory"');
// Only the stored client's provider path identifies this changed budget;
// the doctor/setup process has no IDA configuration in its environment.
await writeRegistration(2_400_001);
const doctor = await run(["doctor", "--client", client, "--json"]);
expect(doctor.exitCode, doctor.stdout).toBe(0);
expect(doctor.json).toMatchObject({
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({
client,
state: "aligned",
advisory: expect.stringContaining(
client === "codex"
? "tool_timeout_sec = 2521 seconds"
: "toolTimeoutMs = 2520001 ms",
),
}),
]),
},
});
const repeated = await run(setupArguments);
expect(repeated.exitCode, repeated.stdout).toBe(0);
expect(repeated.json).toMatchObject({
status: "ready",
plannedActions: [],
appliedActions: [],
});
expect(await readFile(config, "utf8")).toBe(text);
await expect(access(`${config}.rea.backup`)).rejects.toMatchObject({
code: "ENOENT",
});
if (provider === "ida") {
await writeRegistration(0);
const invalidDoctor = await run([
"doctor",
"--client",
client,
"--json",
]);
expect(invalidDoctor.exitCode).toBe(1);
expect(invalidDoctor.json).toMatchObject({
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({
client,
state: "invalid",
remediation: expect.stringContaining("REA_IDA_MCP_CONFIG"),
}),
]),
},
});
const invalidSetup = await run(setupArguments);
expect(invalidSetup.exitCode).toBe(1);
expect(invalidSetup.stdout).toContain("REA_IDA_MCP_CONFIG");
expect(await readFile(config, "utf8")).toBe(text);
await expect(access(`${config}.rea.backup`)).rejects.toMatchObject({
code: "ENOENT",
});
}
},
);
for (const invalidSetting of [
{ setting: "REA_MCP_INPUT_SCHEMA_PROFILE", value: "unknown" },
{ setting: "REA_GHIDRA_STARTUP_TIMEOUT_MS", value: "0" },
{ setting: "REA_JEB_MCP_TIMEOUT_MS", value: "1.5" },
] as const)
cliTest(
`setup rejects malformed selected ${invalidSetting.setting} before writing`,
async ({ cli }) => {
const home = await createTestTempDirectory(
"rea-invalid-selected-registration-env-",
);
const kimiHome = join(home, "kimi");
await mkdir(kimiHome, { recursive: true });
const config = join(kimiHome, "mcp.json");
const environment = {
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, ".config"),
KIMI_CODE_HOME: kimiHome,
...missingHopperAndGhidraEnvironment(home),
[invalidSetting.setting]: invalidSetting.value,
};
const result = await cli.run({
arguments: [
"setup",
"--client",
"kimi",
"--skill=false",
"--yes",
"--json",
],
cwd: home,
environment,
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining(invalidSetting.setting),
});
expect(`${result.stdout}\n${result.stderr}`).toContain(
invalidSetting.setting,
);
await expect(access(config)).rejects.toMatchObject({ code: "ENOENT" });
await expect(access(`${config}.rea.backup`)).rejects.toMatchObject({
code: "ENOENT",
});
},
);
cliTest(
"public VS Code setup registers in VSCODE_APPDATA without changing the default configuration",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-vscode-appdata-cli-");
const selectedData = join(home, "selected data");
const config = join(selectedData, "Code", "User", "mcp.json");
const defaultData =
process.platform === "win32"
? join(home, "AppData", "Roaming")
: process.platform === "darwin"
? join(home, "Library", "Application Support")
: join(home, ".config");
const defaultConfig = join(defaultData, "Code", "User", "mcp.json");
const original = JSON.stringify({
servers: { foreign: { command: "keep" } },
});
const defaultOriginal = JSON.stringify({
servers: { defaultServer: { command: "untouched" } },
});
await mkdir(dirname(config), { recursive: true });
await mkdir(dirname(defaultConfig), { recursive: true });
await writeFile(config, original);
await writeFile(defaultConfig, defaultOriginal);
const setup = await cli.run({
arguments: [
"setup",
"--client",
"vscode",
"--skill=false",
"--yes",
"--json",
],
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
APPDATA: join(home, "AppData", "Roaming"),
XDG_CONFIG_HOME: join(home, ".config"),
VSCODE_APPDATA: selectedData,
VSCODE_PORTABLE: "",
...missingHopperAndGhidraEnvironment(home),
},
});
expect(setup.exitCode, setup.stdout + setup.stderr).toBe(0);
expect(setup.json).toMatchObject({ status: "ready" });
expect(JSON.parse(await readFile(config, "utf8"))).toMatchObject({
servers: {
foreign: { command: "keep" },
rea: {
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
},
},
});
expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original);
expect(await readFile(defaultConfig, "utf8")).toBe(defaultOriginal);
await expect(access(`${defaultConfig}.rea.backup`)).rejects.toMatchObject({
code: "ENOENT",
});
},
);